gin - 1

75 阅读1分钟

快速入门

func index(c *gin.Context){
    c.String(200,"hello world")
}
​
func main(){
    r := gin.Default()
    r.GET("/",index)
    r.Run(":8080")  //  http.ListenAndServer(":8080")
}

响应

字符串

c.String(200,"hello")

json

  • s.String(ststus,str)
  • s.JSON(status,map/struct)
type User struct{
    Name string json:"name"
    age int json:"age"
    password string json:"-"    //  代表不渲染json化
}
//  如果属性名小写也不会渲染 
​
umap := make(map[int]string)
umap[0] = "he"
umap[1] = "she"
umap[2] = "it"
s.JSON(200,umap)
//  map输出顺序无序

模板

golang常用库:text/templates & html/templates

模板语法

//所有变量放在{{}}
//注释: {{/*  */}}
  • pipline指数据产生的操作,变量:name := pipline
  • 条件判断

    {{if bool}}
    {{else if bool}}
    {{else}}
    {{end }}
    
  • range

    {{range pipline}}t{{end}}
    ​
    {{range pipline}}p
    {{else}}q
    {{end}}
    
  • with

    {{with pipline }}t{{end}}\
    {{with pipline}}
    {{else}}
    {{end}}
    

创建路由

只需要r.METHOD // 注意method为大写

常用method: get post put delete

如何获取参数

get: Gin的hander提供了三种方法:

  • c.Query():如果查询不存在或为空则返回空
  • c.DefaultQuery():如果查询不存在或为空则返回第二个参数作为值
  • c.GetQuery(): 同c.Querey(),但是多返回一个bool值显示是否存在

post: Gin同样提供了三种方法,且类似:

  • c.PostForm()
  • c.DefaultPostForm()
  • c.GetPostForm()