Go语言常用知识(二)

Go语言常用知识(二)—— Gin

Gin

func main(){

   // 返回json
   //创建一个默认的路由引擎

   r := gin.Default()

   // 1. 使用map
   r.GET("/map_json", func(c *gin.Context){
      c.JSON(http.StatusOK, gin.H{
         "message" : "Hello Golang!",
      })
   })

   // 2. 结构体
   type msg struct{
      Name string `json:"name"` 	//反射时用到,可以让解析出的json文件Name字段变成name
      Age int
   }
   r.GET("/struct_json", func(c *gin.Context) {
      data := msg{
         Name:"老王",
         Age: 18,
      }
      c.JSON(http.StatusOK,data)
   })

   r.Run(":9090")

}

善用 ShouldBind函数

  • 可以获取 querystring
  • form表单
  • json
type UserInfo struct {
   Name string    `form:"name"`
   Age int    `form:"age"`
}

r.POST("/form", func(c *gin.Context) {
   var u UserInfo
   err := c.ShouldBind(&u)
   if err !=nil{
      c.JSON(http.StatusBadRequest,gin.H{
         "error":err.Error(),
      })
   }else {
      fmt.Printf("%#v\n",u)
      c.JSON(http.StatusOK,gin.H{
         "name":u.Name,
         "age":u.Age,
      })
   }

路由组

r.Group("/xxx")		//xxx是公用的前缀

Gin中间件

定义中间件

Gin的中间件必须是一个gin.HandlerFunc类型。

import (
   "fmt"
   "github.com/gin-gonic/gin"
   "net/http"
   "time"
)

func indexHandler(c *gin.Context){

   fmt.Println("index ")
   //使用 Set Get 从中间件中 存取数据到 indexHandler中
   name, ok := c.Get("name")
   if !ok{
      name = "nil"
   }
   c.JSON(http.StatusOK,gin.H{
      "name":name,
   })
}

//定义一个中间件m1 计时
func m1(c *gin.Context){
   fmt.Println("m1 in...")
   start := time.Now()
   //使用 Set Get 从中间件中 存取数据到 indexHandler中
   c.Set("name","zhangsan")
   c.Next() //调用后续的处理函数,即后面的 indexHandler
   //c.Abort() //阻止调用后续的处理函数

   cost := time.Since(start)

   fmt.Printf("cost : %v\n", cost)
   fmt.Println("m1 out...")
}

func main() {

   r := gin.Default() //Default 默认使用 logger 和 recovery 中间件

   /**
    * Get函数定义如下,最后可以跟多个 handlers类型的参数
    *func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
    * return group.handle(http.MethodGet, relativePath, handlers)
    *}
    */

   //还可以全局注册中间件函数 m1
   r.Use(m1)
   r.GET("/index", indexHandler)


   r.Run(":9090")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值