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")
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM