gin模板渲染
//创建一个默认的路由引擎
r := gin.Default()
//指定模板的位置
r.LoadHTMLGlob("templates/**/*")
//使用get函数
r.GET("/posts/index", func(c *gin.Context) {
/**
第一个参数 状态码
第二个参数 文件的名称,如果未设定则使用文件名称,使用{{define "文件名称"}} {{end}}
第三个参数 要渲染的模板中定义的key
*/
c.HTML(http.StatusOK, "posts/index.html", gin.H{
"title": "posts/index",
})
})
/**
在模板函数中如果没有我们要使用的模板,那么我们需要自己定义一个模板
*/
r.SetFuncMap(template.FuncMap{
/**
key 自定义模板名称
value 为自定义模板实现的逻辑
*/
"safe": func(str string) template.HTML{
return template.HTML(str)
},
})
gin返回json
r := gin.Default()
r.GET("/json", func(c *gin.Context) {
//自己拼接JSON
c.JSON(http.StatusOK, gin.H{
"name": "hui",
"msg": "加油",
})
//
c.JSON(http.StatusOK,&结构体名称)
})
r.Run(":9000")
gin获取参数
r.GET("/hello", func(c *gin.Context) {
/**
第一个参数为key
第二个参数代表如果没有这个参数 使用这个作为默认值
*/
name := c.DefaultQuery("name", "哈哈")
name := c.Query(参数的key)
c.JSON(http.StatusOK, gin.H{
"name": name,
})
})
gin获取form参数
r.POST("/user/search", func(c *gin.Context) {
// DefaultPostForm取不到值时会返回指定的默认值
//username := c.DefaultPostForm("username", "哈哈")
username := c.PostForm("username")
//输出json结果给调用方
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
})
})
gin获取json参数
r.POST("/json", func(c *gin.Context) {
// 注意:下面为了举例子方便,暂时忽略了错误处理
b, _ := c.GetRawData() // 从c.Request.Body读取请求数据
// 定义map或结构体
var m map[string]interface{}
// 反序列化
_ = json.Unmarshal(b, &m)
c.JSON(http.StatusOK, m)
})
gin获取URL路径参数
r.GET("/user/search/:username/:address", func(c *gin.Context) {
username := c.Param("username")
address := c.Param("address")
//输出json结果给调用方
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
})
})
gin文件上传
r.POST("/upload", func(c *gin.Context) {
//根据name获取文件
f, err := c.FormFile("f1")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
}
//拼接文件要存储的位置
dst := path.Join("./", f.Filename)
//存储文件
c.SaveUploadedFile(f, dst)
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
gin重定向
//重定向
r.GET("/index", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
})
//请求转发 个人理解
r.GET("/a", func(c *gin.Context) {
c.Request.URL.Path = "/b"
r.HandleContext(c)
})
r.GET("/b", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
中间件
//中间件需要返回 gin.HandlerFunc
func StatCost() gin.HandlerFunc {
return func(c *gin.Context) {
log.Println("中间件")
start := time.Now()
//送往下一级的数据
//c.Set("name","hello")
//送往下一级
c.Next()
//阻止往下传递
//c.Abort()
cost := time.Since(start)
fmt.Println(cost)
}
}
func main() {
r := gin.Default()
//注册全局中间件
r.Use(StatCost())
r.GET("/index", func(c *gin.Context) {
//接收下一级的数据
//c.Get("name")
log.Println("main####")
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
r.Run(":9090")
}