go gin 数据绑定及HTML模板

参考:https://github.com/gin-gonic/gin#parameters-in-path

1. gin 数据解析绑定

模型绑定可以将请求体绑定给一个类型,目前支持绑定的类型有 JSON, XML 和标准表单数据(foo=bar&boo=baz)。要注意的是绑定时需要给字段设置绑定类型的标签。比如绑定 JSON 数据时,设置json:"fieldname" 。使用绑定方法时,Gin 会根据请求头中 Content-Type 来自动判断需要解析的类型。如果你明确绑定的类型,你可以不用自动推断,而用 BindWith 方法。你也可以指定某字段是必需的。如果一个字段被binding:"required"修饰而值却是空的,请求会失败并返回错误。

package main

import  "github.com/gin-gonic/gin"

type Login struct {
	User string   `form:"user"  json:"user" binding:"required"`
	Password string   `form:"password"  json:"password" binding:"required"`
}


func main() {
	r :=gin.Default()

	r.POST("/login",func(c *gin.Context) {
		var json  Login
		if c.BindJSON(&json) == nil{
			if json.User == "manu" && json.Password == "123" {
				c.JSON(200,gin.H{  "status":"Login successfully!"})
			}else{
				c.JSON(200,gin.H{
					"status":"Login Failed!",
					})
			}
		}
	})

	r.Run()
}

客官稍等

xml/yaml等也一样:

	r.GET("/someXML", func(c *gin.Context) {
		c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	r.GET("/someYAML", func(c *gin.Context) {
		c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

2. gin HTML rendering

(1)单template

main.go

package main   

import  "github.com/gin-gonic/gin"


func main() {
	r :=gin.Default()
	r.LoadHTMLGlob("templates/*")
	r.GET("/index",func(c *gin.Context) {
		c.HTML(200,"index.tmpl",gin.H{
				"title":"Main site",
			})
	})


	r.Run()
}

templates/index.tmpl

<html>
	<h1>
		{{ .title }}
	</h1>
</html>

(2)不同路径template

package main  

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

func main() {
	r :=gin.Default()
	r.LoadHTMLGlob("templates/**/*")
	r.GET("/posts/index",func(c *gin.Context) {
		c.HTML(200,"posts/index.tmpl",gin.H{
				"title":"Posts",
			})
		
	})

	r.GET("/users/index",func(c *gin.Context) {
	c.HTML(200,"users/index.tmpl",gin.H{
				"title":"Users",
			})
		
	})

	//重定向网址
	r.GET("/Redirect", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com/")
	})

    //路径重定向
	r.GET("/test", func(c *gin.Context) {
    	c.Request.URL.Path = "/test2"
    	r.HandleContext(c)
	})

	r.GET("/test2", func(c *gin.Context) {
    	c.JSON(200, gin.H{"hello": "world"})
	})

	r.Run()
}

templates/posts/index.tmpl

{{ define "posts/index.tmpl" }}
<html><h1>
	{{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}

templates/users/index.tmpl

{{ define "users/index.tmpl" }}
<html><h1>
	{{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}

发布了123 篇原创文章 · 获赞 71 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/boke14122621/article/details/100513086