gin學習筆記--模板渲染與獲取參數


gin學習筆記--模板渲染與獲取參數

廢話不說,先上代碼

目錄結構:

mark

說明:

  • [x] 主程序main.go
  • [x] template文件夾下放置兩個html模板文件
  • [x] static文件夾下防止靜態文件,這里放的是一張圖片,用於后面靜態文件加

源碼:

main.go:


package main
import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func loginHandle(c *gin.Context){
	//渲染模板,已經解析好的模板里填充字段
	c.HTML(http.StatusOK,"login.html",gin.H{
		"msg":"我愛你",
	})
}
func indexHandle(c *gin.Context){
	//渲染
	c.HTML(http.StatusOK,"index.html",gin.H{
		"msg":"快滾",
	})
}
//json渲染
func jsonHandle(c *gin.Context){

	var user struct{
		Name string`json:"user"`
		Id int
		Age int
	}
	user.Name="zhouzheng"
	user.Age=24
	user.Id=1

	c.JSON(200,user)
}
//yaml渲染
func yamlHandle(c *gin.Context){
	c.YAML(http.StatusOK, gin.H{"message": "ok", "status": http.StatusOK})
}
//query-string提取
func queryHandle(c *gin.Context)	{
	//拿到請求行里的query-string信息
	firstname := c.DefaultQuery("firstname", "Guest")//設置默認值
	lastname := c.Query("lastname")
	c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
}
//form信息提取
func formHandle(c *gin.Context){
	//拿到form表單信息,原生的里是用r.Form得到
	// DefaultPostForm取不到值時會返回指定的默認值
	//username := c.DefaultPostForm("username", "小王子")
	username := c.PostForm("username")
	address := c.DefaultQuery("addresss","beijing")//設置默認值
	//輸出json結果給調用方(渲染)
	c.JSON(http.StatusOK, gin.H{
		"status":gin.H{//又內嵌了一個結構體
			"id":10,
		},
		"message":  "ok",
		"username": username,
		"address":  address,
	})
}
//提取path參數
func pathHandle(c *gin.Context){
	//Param returns the value of the URL param.解析路徑=參數
	username:=c.Param("username")
	lastname:=c.Param("lastname")
	//渲染並發送
	c.JSON(200,gin.H{
		"username":username,
		"lastname":lastname,
	})
}
func main(){
	// 創建一個默認的路由引擎
	r := gin.Default()
	//加載模板文件,等價於template里面的template.ParseFiles()
    //r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")
	r.LoadHTMLGlob("template/*")
	//則會之靜態文件目錄
	//第一參數=是代碼里使用的路徑,第二個路徑是真正你靜態文件的路徑
	r.Static("/dsb","./static")//就是做了個路徑的替換
	r.GET("/login",loginHandle)
	r.GET("/index",indexHandle)
	r.GET("/json",jsonHandle)
	r.GET("/yaml", yamlHandle)
	r.GET("/welcome", queryHandle )
	r.POST("/form", formHandle )
	r.GET("/user/search/:username/:address", pathHandle )
	r.Run()
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
</head>
<body>
    <h1>  index</h1>
    <div> {{.msg}}</div>
<img src="/dsb/image/ycy.jpg" alt=" ">  //用靜態文件嵌入了一張圖片
</body>
</html>

login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>login</title>
</head>
<body>
    <h1>  login</h1>
    <div> {{.msg}}</div>
</body>
</html>

代碼講解:

  1. html渲染

    首先看html渲染部分,Gin框架中使用LoadHTMLGlob()或者LoadHTMLFiles()方法進行HTML模板渲染。

    r.LoadHTMLGlob("template/*")代表解析template目錄下所有模板。等價於r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")

  2. json和yaml渲染

    json和yaml渲染沒啥好說的,分別調用c.Json()c.Yaml()即可。

    這里c.Json()渲染有兩種方法,一種是直接傳一個結構體進去,像上文c.JSON(200,user),也可以在函數里使用gin.H拼接,例如c.JSON(http.StatusOK, gin.H{"message": "Hello world!"})

  3. query-string 獲取

    query string參數與body參數

    web提供的服務通常是client和server的交互。其中客戶端向服務器發送請求,除了路由參數,其他的參數無非兩種,查詢字符串query string和報文體body參數。所謂query string,即路由用,用?以后連接的key1=value2&key2=value2的形式的參數。當然這個key-value是經過urlencode編碼。

    這里我理解為當使用GET方法時,query-string是放在url中的內容,當使用POST時,信息由form表單提交,鍵值對信息存儲在請求體body中。

    query string

    對於參數的處理,經常會出現參數不存在的情況,對於是否提供默認值,gin也考慮了,並且給出了一個優雅的方案:使用c.DefaultQuery方法讀取參數,其中當參數不存在的時候,提供一個默認值;使用Query方法讀取正常參數,當參數不存在的時候,返回空字串。

    body

    http的報文體傳輸數據就比query string稍微復雜一點,常見的格式就有四種。例如application/jsonapplication/x-www-form-urlencoded, application/xmlmultipart/form-data。后面一個主要用於圖片上傳。json格式的很好理解,urlencode其實也不難,無非就是把query string的內容,放到了body體里,同樣也需要urlencode。默認情況下,c.PostFROM解析的是x-www-form-urlencodedfrom-data的參數。

    與get處理query參數一樣,post方法也提供了處理默認參數的情況。同理,如果參數不存在,將會得到空字串。

    本段參考內容:https://www.jianshu.com/p/a31e4ee25305

  4. path參數提取

    這里不是很明白。

  5. 靜態文件處理

    核心函數r.Static("/dsb","./static"),與index.html里的<img src="/dsb/image/ycy.jpg" alt=" ">對應。

調試結果:

  1. 主程序運行

mark

  1. 使用postman進行測試

mark

image-20200528010113938

mark

mark

mark

mark

推薦閱讀:

gin框架介紹和使用

Golang 微框架 Gin 簡介

golang輕量級框架-Gin入門


免責聲明!

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



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