gin系列- 渲染

Gin渲染

HTML渲染

#main.go
package main

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

func main() {
	r := gin.Default()
	r.LoadHTMLGlob("templates/**/*")   //模板解析
	//r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")
	r.GET("/posts/index", func(c *gin.Context) {
		//HTTP请求
		c.HTML(http.StatusOK, "posts/index.html", gin.H{  //模板渲染
			"title": "zisefeizhu",
		})
	})

	r.GET("/users/index", func(c *gin.Context) {
		//HTTP请求
		c.HTML(http.StatusOK, "users/index.html", gin.H{  //模板渲染
			"title": "jingxing",
		})
	})
	r.Run(":9090")   //启动server
}

#posts/index.html
{{define "posts/index.html"}}
    <!DOCTYPE html>
    <html lang="en">

    <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>posts/index</title>
    </head>
    <body>
    {{.title}}
    </body>
    </html>
{{end}}


#users/index.html
{{define "users/index.html"}}
    <!DOCTYPE html>
    <html lang="en">
    <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>users/index</title>
    </head>
    <body>
    {{.title}}
    </body>
    </html>
{{end}}


自定义模板函数

#main.go

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

func main() {
	r := gin.Default()
	//gin框架给模板添加自定义函数
	r.SetFuncMap(template.FuncMap{
		"safe": func(str string) template.HTML{
			return template.HTML(str)
		},
	})
	r.LoadHTMLGlob("./index.tmpl")
	r.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", "<a href='https://www.cnblogs.com/zisefeizhu/'>zisefeizhu的博客</a>")
	})

	r.Run(":9090")   //启动server
}

在index.tmpl中使用定义好的safe模板函数
#index.tmpl
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>修改模板引擎的标识符</title>
</head>
<body>
<div>{{ . | safe }}</div>
</body>
</html>

静态文件处理

#main.go
import (
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
)

//静态文件
//html 页面上用到的样式文件.css js文件 图片
func main() {
	r := gin.Default()
	//加载静态文件
	r.Static("/static", "./static")
	r.LoadHTMLGlob("templates/**/*")
	r.GET("/users/index", func(c *gin.Context) {
		//HTTP请求
		c.HTML(http.StatusOK, "users/index.html", gin.H{  //模板渲染
			"title": "jingxing",
		})
	})

	r.Run(":9090")   //启动server
}

#index.html    注意css 和js的配置 head   body
{{define "users/index.html"}}
    <!DOCTYPE html>
    <html lang="en">
    <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">
        <link rel="stylesheet" href="/static/index.css">
        <title>users/index</title>
    </head>
    <body>
    {{.title}}
    <script src="/static/index.js"></script>
    </body>
    </html>
{{end}}

#index.js
alert(123);

#index.css
body {
    background-color: cadetblue;
}


例子

下载:http://sc.chinaz.com/moban/191216115340.htm#down

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

//静态文件
//html 页面上用到的样式文件.css js文件 图片
func main() {
	r := gin.Default()
	//加载静态文件
	r.Static("/static", "./static")
	r.LoadHTMLGlob("templates/**/*")
 
	//返回从网上下载的模板
	r.GET("/home", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	r.Run(":9090")   //启动server
}

index.html 改css js png路径为static


JSON渲染

package main

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

func main() {
	r := gin.Default()
	r.GET("/json", func(c *gin.Context) {
		//方法1 使用map
		data :=  map[string]interface{}{
			"name": "zisefeizhu",
			"message": "hello world",
			"age": 18,
		}
		//方法2 字节拼接json    //gin.H 就是map类型
		c.JSON(http.StatusOK, gin.H{
			"name": "jingxing",
			"message": "hello world",
			"age": 18,
		})
		c.JSON(http.StatusOK, data)
		//方法3 使用结构体
		//使用结构体      
    //灵活使用tag对结构体字段做定制化操作
		type msg struct{    //字段要外部访问不能小写
			Name string `json:"user"`
			Message string
			Age int
		}
		data3 := msg{
			Name:    "yike",
			Message: "hello world",
			Age:     21,
		}
		c.JSON(http.StatusOK, data3)  //json的序列化
	})
	r.Run(":9090")
}

获取querystring参数

多用于Get请求

package main

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

//querystring

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

	//GET请求URL ?后面的是querystring参数
	//key=value格式,多个key-value用&连接
	///web?query=zisefeizhu&age=22
	r.GET("/web", func(c *gin.Context) {
		////获取浏览器发请求携带的query String 参数
		//方式1
		name := c.Query("query")  //通过Query获取请求中携带的querystring参数
		age := c.Query("age")
		//方式2
		//name := c.DefaultQuery("query","nothing")  //取不到用nothing
		//方式3
    //name, ok := c.GetQuery("query")  //取到返回(值, true),取不到返回("",false)
		//if !ok {
		//	//取不到
		//	name = "nothing"
		//}
		c.JSON(http.StatusOK, gin.H{
			"name" : name,
			"age" : age,
		})
	})
	r.Run(":9090")
}

获取form参数

POST请求

package main

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

//获取form表单提交的参数
//一次请求对应一次响应
func main() {
	r := gin.Default()
	r.LoadHTMLFiles("./login.html","./index.html")
	r.GET("/login", func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.html",nil)
	})

	//login post
	r.POST("/login", func(c *gin.Context) {
		//获取form表单提交的数据
		//方法1
		//username := c.PostForm("username")
		//password := c.PostForm("password")  //取到就返回值,取不到就返回空字符串
		//方法2   后面是默认值
		//username :=  c.DefaultPostForm("username","nothing")
		//password := c.DefaultPostForm("password", "123456")
		//方法3
		username, ok := c.GetPostForm("username")
		if !ok {
			username = "zisefeizhu"
		}
		password, ok := c.GetPostForm("password")
		if !ok{
			password = "xxx"
		}

		c.HTML(http.StatusOK, "index.html", gin.H{
			"Name": username,
			"Password": password,
		})
	})

	r.Run(":9090")

}


获取URI路径参数

package main
//注意uri的匹配不要冲突
import (
	"github.com/gin-gonic/gin"
	"net/http"
)

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

	r.GET("/user/:name/:age", func(c *gin.Context) {
		//获取路径参数
		name := c.Param("name")
		age := c.Param("age")   //string类型
		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"age": age,
		})
	})

	r.GET("/blog/:year/:month", func(c *gin.Context) {
		year := c.Param("year")
		month := c.Param("month")
		c.JSON(http.StatusOK, gin.H{
			"year": year,
			"month": month,
		})
	})
	r.Run(":9090")
}


posted @ 2020-04-18 18:03  紫色飞猪  阅读(1340)  评论(0编辑  收藏  举报