GoWeb开发:004.Gin返回数据

134 阅读1分钟

返回Html模板

type User struct {
	Id   uint
	Name string
}

r.LoadHTMLGlob("templates/*")

r.GET("/html", func(c *gin.Context) {
	users := make([]User, 0)
	users = append(users, User{Id: 1, Name: "Jim"})
	users = append(users, User{Id: 2, Name: "Tom"})
	users = append(users, User{Id: 3, Name: "Mike"})

	c.HTML(200, "index.tmpl", gin.H{
		"title": "Hello",
		"users": users,
	})
})

/templates/index.tmpl

<html>
	<h1>
		{{ .title }}
	</h1>
    <ul>
         {{range $i, $v := .users}}
             <li>
                <span>{{$v.Id}}</span>
                <span>{{$v.Name}}</span>
            </li>
         {{end}}
    </ul>
</html>

返回字符串

r.GET("/string", func(c *gin.Context) {
	c.String(200, "Hello string")
})

返回JSON

r.GET("/json", func(c *gin.Context) {
	data := map[string]interface{}{
		"name": "jim",
		"age":  20,
	}

	c.JSON(200, gin.H{
		"code": 200,
		"data": data,
		"msg":  "ok",
	})
})

返回JSONP

r.GET("/jsonp", func(c *gin.Context) {
	data := map[string]interface{}{
		"name": "jim",
		"age":  20,
	}

	c.JSONP(200, data)
})

重定向

r.GET("/baidu", func(c *gin.Context) {
	c.Redirect(301, "https://www.baidu.com")
})