标签:== model lin run git col date context ted
一键生成 后端 restful api主要用这个库 gitee.com/konyshe/gogo, 详情可以去查看说明文件。
只要连接好数据库表,不用 数据库的 models文件,就可以最简单的办法 生成 restful api.
原项目有一个小问题,
需要修改 源码 SQLUtils.go
239行修改
case "INT":
{
queryData[queryCount][a] = new(sql.NullInt64)
}
290 追加
case *sql.NullInt64:
result[columnsType[a].Name()] = *s
是因为涉及到 数据库里面 int 字段 允许为空,默认是null, 数据库读取的时候 会报错
sql: Scan error on column index 3, name "created_on": converting driver.Value type <nil> ("<nil>") to a int32: invalid syntax
package main
import (
"net/http"
"strconv"
"gitee.com/konyshe/gogo"
)
func main() {
// 初始化数据库连接
if err := gogo.SQLInit("mysql", "root:1234567890@tcp(192.168.100.50:3306)/go?charset=utf8&parseTime=true", 10, 1); err != nil {
gogo.Log().Error(err.Error())
return
}
// 增
gogo.POST("/restful/:tablename", func(ctx *gogo.HTTPContext) {
affect, err := gogo.SQLInsert(
ctx.GetPathParam(":tablename"),
ctx.GetPostBody())
if err != nil {
gogo.Log().Error(err.Error())
ctx.WriteString(err.Error())
} else {
ctx.WriteString(strconv.FormatInt(affect, 10))
}
})
// 删
gogo.DELETE("/restful/:tablename/:id", func(ctx *gogo.HTTPContext) {
affect, err := gogo.SQLDelete(
ctx.GetPathParam(":tablename"),
"id="+ctx.GetPathParam(":id"))
if err != nil {
gogo.Log().Error(err.Error())
ctx.WriteString(err.Error())
} else {
ctx.WriteString(strconv.FormatInt(affect, 10))
}
})
// 改
gogo.PUT("/restful/:tablename/:id", func(ctx *gogo.HTTPContext) {
affect, err := gogo.SQLUpdate(
ctx.GetPathParam(":tablename"),
"id="+ctx.GetPathParam(":id"),
ctx.GetPostBody())
if err != nil {
gogo.Log().Error(err.Error())
ctx.WriteString(err.Error())
} else {
ctx.WriteString(strconv.FormatInt(affect, 10))
}
})
// 查
gogo.GET("/restful/:tablename/:id", func(ctx *gogo.HTTPContext) {
queryData, err := gogo.SQLQueryByMap(
"",
ctx.GetString("feilds"),
ctx.GetPathParam(":tablename"),
"id="+ctx.GetPathParam(":id"),
"", 0, 1)
if err != nil {
gogo.Log().Error(err.Error())
ctx.WriteString(err.Error())
} else {
ctx.WriteJSON(queryData)
}
})
// 查
gogo.GET("/restful/:tablename", func(ctx *gogo.HTTPContext) {
queryData, err := gogo.SQLQueryByMap(
ctx.GetString("columnname"),
ctx.GetString("feilds"),
ctx.GetPathParam(":tablename"),
ctx.GetString("where"),
ctx.GetString("order"),
ctx.GetInt("offset", 0),
ctx.GetInt("count", 10))
if err != nil {
gogo.Log().Error(err.Error())
ctx.WriteString(err.Error())
} else {
ctx.WriteJSON(queryData)
}
})
// 404页面
gogo.STATUS(http.StatusNotFound, func(ctx *gogo.HTTPContext) {
ctx.WriteHeader(http.StatusNotFound)
l, err := gogo.SQLQueryByMap("webname", "*", "dede_flink", "", "", 0, 100)
if err == nil {
ctx.WriteExecute(l,
"views/notfound.tmpl")
return
}
})
// 启动HTTP服务
gogo.Run(":8080")
}
标签:== model lin run git col date context ted
原文地址:https://blog.51cto.com/hequan/2355891