016-Go Iris Restful测试

1:data/data.go

package data

import(
    "fmt"
    "database/sql"
    _"github.com/lib/pq"
)

const(
    host = "192.168.72.128"
    port = 5432
    user = "test"
    password = "test"
    dbname = "testdb"
)

var Db *sql.DB

func init(){
    var err error

    pgInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", 
        host, port, user, password, dbname)
    
    Db, err = sql.Open("postgres", pgInfo)

    if err != nil{
        panic(err)
    }
}

 

2:result/result.go

package result


type Result struct{
    No    int             `json:"no"`
    Msg    string         `json:"msg"`
    Obj interface{} `json:"obj,omitempty"`
}

 

3:user/user_data.go

package user

import(
    ."iristest/data"
)

type User struct{
    ID        int     `json:"id"`
    Name    string    `json:"name"`
    Age        int        `json:"age"`
}

func (user *User) Insert() (err error){
    sql := "insert into t_user(name,age) values($1,$2)"
    _, err = Db.Exec(sql, user.Name, user.Age)
    return
}

func Delete(id int) (err error){
    sql := "delete from t_user where id=$1"
    _,err = Db.Exec(sql, id)
    return
}

func (user *User) Update()(err error){
    sql := "update t_user set name=$1,age=$2 where id=$3"
    _,err = Db.Exec(sql, user.Name, user.Age, user.ID)
    return
}

func Select(id int)(user User, err error){
    sql := "select id,name,age from t_user where id=$1"
    user = User{}
    err = Db.QueryRow(sql, id).Scan(&user.ID, &user.Name, &user.Age)
    return
}

func SelectList()(users []User, err error){
    sql := "select id,name,age from t_user"
    users = []User{}
    rows,err := Db.Query(sql)
    if err != nil{
        panic(err.Error)
    }
    defer rows.Close()

    for rows.Next(){
        rows.Columns()
        var user User
        err = rows.Scan(&user.ID, &user.Name, &user.Age)
        if err != nil{
            panic(err.Error)
        }

        users = append(users, user)
    }

    return
}

 

4:user/user_web.go

package user

import(
    "github.com/kataras/iris"    
    "strconv"
    ."iristest/result"
)

func CreateUser(ctx iris.Context){
    var user User
    ctx.ReadJSON(&user)

    err := user.Insert()

    result := Result{}

    if err != nil{
        result.No = 0
        result.Msg = err.Error()
    }else{
        result.No = 1
        result.Msg = "成功保存用户信息"
    }

    ctx.JSON(result)
}

func GetUserById(ctx iris.Context){
    id,_ := strconv.Atoi(ctx.Params().Get("id"))
    user, err := Select(id)

    result := Result{}

    if err != nil{
        result.No = 0
        result.Msg = err.Error()
    }else{
        result.No = 1
        result.Msg = "成功获取用户信息"
        result.Obj = user
    }

    ctx.JSON(result)
}

func GetUserList(ctx iris.Context){
    users, err := SelectList()

    result := Result{}

    if err != nil{
        result.No = 0
        result.Msg = err.Error()
    }else{
        result.No = 1
        result.Msg = "成功获取用户列表信息"
        result.Obj = users
    }

    ctx.JSON(result)
}

func DeleteUserById(ctx iris.Context){
    id,_ := strconv.Atoi(ctx.Params().Get("id"))
    err := Delete(id)

    result := Result{}

    if err != nil{
        result.No = 0
        result.Msg = err.Error()
    }else{
        result.No = 1
        result.Msg = "成功删除用户信息"
    }

    ctx.JSON(result)
}

5:main.go

package main

import(
    "github.com/kataras/iris"
    "github.com/kataras/iris/middleware/logger"
    "github.com/kataras/iris/middleware/recover"
    ."iristest/user"
)

func main(){
    app := iris.New()
    app.Logger().SetLevel("debug")
    app.Use(recover.New())
    app.Use(logger.New())

    app.RegisterView(iris.HTML("./public", ".html"))
    app.Get("/", func(ctx iris.Context){
        ctx.View("index.html")
    })//users
    usersRoutes := app.Party("/users", func(ctx iris.Context){
        ctx.Next()
    })
    {
        usersRoutes.Post("/", CreateUser)
        usersRoutes.Delete("/{id:int}", DeleteUserById)
        usersRoutes.Get("/{id:int}", GetUserById)
        usersRoutes.Get("/", GetUserList)
    }

    app.Run(iris.Addr(":8080"),iris.WithCharset("UTF-8"),iris.WithoutServerError(iris.ErrServerClosed))
}

 

posted @ 2018-06-18 16:34  yshy  阅读(763)  评论(0编辑  收藏  举报