gin返回html

package main

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

func main() {
	r := gin.Default()
	r.LoadHTMLFiles("index.tmpl") //解析模板

	r.GET("/index", func(c *gin.Context) {
		//http请求
		c.HTML(200, "index.tmpl", gin.H{ //模板渲染
			"title": "baidu.com",
		})
	})
	r.Run(":9090") //启动server
}

模板
index.tmpl

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello</title>
</head>
<body>
    {{.title}}
</body>
</html>

gin返回json

package main

import (
	"net/http"

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

type message struct {
	Name string `json:"name"`
	Msg  string
	Age  int
}

func main() {
	r := gin.Default()
	r.LoadHTMLFiles("index.tmpl") //解析模板

	r.GET("/index", func(c *gin.Context) {
		//http请求
		//方法1:使用map
		// data := map[string]interface{}{
		// 	"name":    "张三",
		// 	"message": "是个人才。",
		// 	"age":     18,
		// }
		//方法2 go定义好的gin.H(相对于map)
		data := gin.H{"name": "张三", "message": "是个人才。", "age": 18}
		c.JSON(http.StatusOK, data)

	})

	r.GET("/indexstruct", func(c *gin.Context) {
		//方法3:结构体
		data := message{
			"张三struct",
			"是个人才。",
			18,
		}
		c.JSON(http.StatusOK, data)
	})
	r.Run(":9090") //启动server
}


模板
index.tmpl

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello</title>
</head>
<body>
    {{.data}}
</body>
</html>
posted on 2021-08-22 21:16  飞飞乐园  阅读(1183)  评论(0编辑  收藏  举报