上一篇文章拆分了控制器和路由,下面看一下这个问题
package controller
//controller/Index.go
import (
"github.com/gin-gonic/gin"
"myGin/response"
)
func Index(context *gin.Context) *response.Response {
return response.Resp().String(context.Request.Host)
}
结果
如果我只要host不带端口就需要这样做
package controller
//controller/Index.go
import (
"github.com/gin-gonic/gin"
"myGin/response"
"strings"
)
func Index(context *gin.Context) *response.Response {
return response.Resp().String(context.Request.Host[:strings.Index(context.Request.Host, ":")])
}
这样实现一点都不优雅,就算封装成一个函数每次还要调用,比较好的方式是直接从context中获取,例如:context.Domain()
这需要重写一下context
在项目下创建一个context目录并创建context.go文件
package context
//context/context.go
import (
"github.com/gin-gonic/gin"
"strings"
)
type Context struct {
*gin.Context
}
func (c *Context) Domain() string {
return c.Request.Host[:strings.Index(c.Request.Host, ":")]
}
继承gin.Context并添加Domain()方法
修改一下控制器中的context,换成我们实现的context.Context
package controller
//controller/Index.go
import (
"myGin/context"
"myGin/response"
)
func Index(context *context.Context) *response.Response {
return response.Resp().String(context.Domain())
}
同时routes.go中的代码也要修改
package routes
//routes/routes.go
import (
"github.com/gin-gonic/gin"
"myGin/context"
"myGin/controller"
"myGin/response"
)
func Load(r *gin.Engine) {
r.GET("/", convert(controller.Index))
}
func convert(f func(*context.Context) *response.Response) gin.HandlerFunc {
return func(c *gin.Context) {
resp := f(&context.Context{Context: c})
data := resp.GetData()
switch item := data.(type) {
case string:
c.String(200, item)
case gin.H:
c.JSON(200, item)
}
}
}
运行后,访问
完成