这是我参与「第五届青训营 」伴学笔记创作活动的第 5 天
本文将接上文,继续记录Gin框架的数据响应,HTML模板渲染,重定向的内容
项目结构修改如下
主要是routers目录下的修改,view目录下存放静态网页
routers.r3代码如下
package routers
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/testdata/protoexample"
"net/http"
)
func resJSON(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"msg": "resJSON", "status": 200})
}
func resStruct(ctx *gin.Context) {
//请注意,需要将结构体内成员变量以大写字母命名,否则返回JSON为空。
//小写字母默认为私有变量, 在包内输出时正常, 但是c.JSON()调用JSON/marshal()进行序列化, 属于包外方法, 无法解析到小写字母开头的成员变量.
type msg struct {
Msg string
Name string
}
var msg1 = msg{}
msg1.Name = "sName"
msg1.Msg = "sMsg"
fmt.Println(msg1)
ctx.JSON(http.StatusOK, msg1)
}
func resXML(c *gin.Context) {
c.XML(200, gin.H{"msg": "XML"})
}
func resYAML(c *gin.Context) {
c.YAML(200, gin.H{"msg": "YAML"})
}
func resProtoBuf(c *gin.Context) {
var reps []int64
//定义数据
label := "label"
//传protobuf格式数据
data := &protoexample.Test{
Label: &label,
Reps: reps,
}
c.ProtoBuf(200, data)
}
func Loadr3(engine *gin.Engine) {
engine.GET("/resJSON", resJSON)
engine.GET("/resStruct", resStruct)
engine.GET("/resXML", resXML)
engine.GET("/resYAML", resYAML)
engine.GET("/resProtoBuf", resProtoBuf)
}
以上主要进行了几种数据类型的响应,对应不同的方法
routers.r4代码如下
package routers
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
"time"
)
func index(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index.html", gin.H{
"title": "INDEX",
"msg": "INDEX!",
})
}
func index2(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index2.html", gin.H{
"title": "INDEX",
"msg": "INDEX!",
})
}
func direct(ctx *gin.Context) {
//code为301
ctx.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
}
func async_1(ctx *gin.Context) {
copyctx := ctx.Copy()
log.Println("HELLO!")
go func() {
time.Sleep(3 * time.Second)
log.Println("异步执行:" + copyctx.Request.URL.Path)
}()
log.Println("HELLO2!")
}
func sync_1(ctx *gin.Context) {
log.Println("HELLO!")
time.Sleep(3 * time.Second)
log.Println("同步执行:" + ctx.Request.URL.Path)
log.Println("HELLO2!")
}
func Loadr4(engine *gin.Engine) {
engine.GET("/index", index)
engine.GET("/index2", index2)
engine.GET("/dir", direct)
engine.GET("/async", async_1)
engine.GET("/sync", sync_1)
}
主要进行了静态网页的渲染,跳转与同步异步执行的操作
html网页
HTML网页源码相同,只是名字与位置不一样拿来测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
</head>
<body>
{{.msg}}
</body>
</html>
main函数如下
package main
import (
"Gin3/routers"
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
route := gin.Default()
//加载文件夹下全部静态文件
route.LoadHTMLGlob("view/**/*")
//加载单独一个静态文件
route.LoadHTMLFiles("view/index2.html")
//若是静态文件,例如js图片视频等等,可使用Static或StaticFS方法,二者不同在于后者把文件夹也展示出来
routers.LoadR1(route)
routers.LoadR2(route)
routers.Loadr3(route)
routers.Loadr4(route)
err := route.Run(":80")
if err != nil {
fmt.Println("ERROR")
return
}
}