结合 gin+gorm+go-Redis 写一个基础 API(中篇)
在上篇里,我介绍了读取配置,并尝试连接了数据库,那么这一篇呢,我们主要利用gin框架来写写简单的接口。
路由
为了便于管理,还是将路由文件单独出来,新建routes:
package router
import (
"net/http"
"github.com/gin-gonic/gin"
"local.com/sai0556/gin-frame/controller"
)
func Load(g *gin.Engine) *gin.Engine {
g.Use(gin.Recovery())
// 404
g.NoRoute(func (c *gin.Context) {
c.String(http.StatusNotFound, "404 not found");
})
g.GET("/", controller.Index)
return g
}
控制器
上面的代码中我们看到了controller,我们建一个目录controller:
先建base.go文件,用于写一些基础的方法,如SendResponse返回json。
package controller
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func SendResponse(c *gin.Context, code int, message string, data interface{}) {
c.JSON(http.StatusOK, Response{
Code: code,
Message: message,
Data: data,
})
}
再来写个index.go,处理逻辑。
package controller
import (
"github.com/gin-gonic/gin"
)
func Index(c *gin.Context) {
SendResponse(c, 0, "success", nil)
}
启动gin
// main.go
// 在连接数据可后加入以下代码
gin.SetMode("debug")
g := gin.New()
g = router.Load(g)
g.Run(":8080")
不妨启动看看效果。
go run main.go -c=./conf/config.yaml
当然,这里的服务启动和停止可以写得再优雅一些。
推荐文章:
本作品采用《CC 协议》,转载必须注明作者和本文链接