Gin 基础 :
Gin 的hello world :
package mainimport("github.com/gin-gonic/gin"
"net/http")
func main() {
engine :=gin.Default()
engine.GET("/", func(context *gin.Context) {
context.String(http.StatusOK,"hello world!")
})
engine.Run()
}
View Code
Gin 的 context.Params(path 参数) :
package mainimport("fmt"
"github.com/gin-gonic/gin"
"net/http")
func main() {
engine :=gin.Default()
engine.GET("/:name/*rest", func(context *gin.Context) {
context.String(http.StatusOK,"hello world!")
fmt.Println(context.Params)
params :=context.Params
fmt.Printf("%T", params)
ret,ok := params.Get("name")ifok{
fmt.Println(ret)
}
fmt.Println(params[0])
})
engine.Run()
}
View Code
Gin 的 context.Query (get 参数):
package mainimport("fmt"
"github.com/gin-gonic/gin"
"net/http")
func main() {
engine :=gin.Default()
engine.GET("/", func(context *gin.Context) {
context.String(http.StatusOK,"hello world!")
fmt.Println(context.Query("name")) //如果不存在返回 空串
fmt.Println(context.DefaultQuery("name","none"))//如果不存在返回 none
})
engine.Run()
}
View Code
Gin 的 context.PostForm(post 参数):
package mainimport("fmt"
"github.com/gin-gonic/gin"
"net/http")
func main() {
engine :=gin.Default()
engine.POST("/", func(context *gin.Context) {
context.String(http.StatusOK,"hello world")
fmt.Println(context.PostForm("name"))
fmt.Println(context.DefaultPostForm("name","none"))
})
engine.Run()
}
View Code
Gin 的HTML渲染:
package mainimport("github.com/gin-gonic/gin"
"html/template"
"net/http")
func main() {
eng :=gin.Default()
eng.SetFuncMap(template.FuncMap{"safe": func(s string)template.HTML {returntemplate.HTML(s)
},
})
eng.LoadHTMLGlob("templates/**/*")
eng.GET("/test01", func(context *gin.Context) {
context.HTML(http.StatusOK,"test/test01.html",gin.H{"a":`百度一下`,
})
})
eng.Run()
}
main.go
{{define "test/test01.html"}}
posts/indexhello test01
{{ .a|safe }}{{end}}
templates/test/test01.html
注意:使用自定义模板函数的时候要先 SetFuncMap 后 LoadHTMLGlob
当HTML文件中引用了静态文件时:
package mainimport("github.com/gin-gonic/gin"
"html/template"
"net/http")
func main() {
eng :=gin.Default()
eng.SetFuncMap(template.FuncMap{"safe": func(s string)template.HTML {returntemplate.HTML(s)
},
})
eng.Static("/xxx","./static")
eng.LoadHTMLGlob("templates/**/*")
eng.GET("/test01", func(context *gin.Context) {
context.HTML(http.StatusOK,"test/test01.html",gin.H{"a":`百度一下`,
})
})
eng.Run()
}
main.go
{{define "test/test01.html"}}
posts/index