controller控制器怎么写_结合 gin+gorm+go-Redis 写一个基础 API(中篇)

b140eb27f761434b1a07032883d60b44.png

在上篇里,我介绍了读取配置,并尝试连接了数据库,那么这一篇呢,我们主要利用 gin 框架来写写简单的接口。

路由

为了便于管理,还是将路由文件单独出来,新建 routes:

package router

import (
    "net/http"

    "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"

    "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 (
    "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

当然,这里的服务启动和停止可以写得再优雅一些。

推荐文章:

Golang 服务器热重启、热升级、热更新 (safe and graceful hot-restart/reload http server) 详解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值