0
点赞
收藏
分享

微信扫一扫

Gin框架学习(七)

闲嫌咸贤 2022-04-30 阅读 43

Gin框架基础

学习思维导图

Gin框架思维导图

互动

五一啦,祝大家五一劳动节快乐!
受疫情影响没法出门的话,可以来学习,加油加油!

进阶篇

restgate

安全认证中间件通过restgate来实现

package main
import (
	"github.com/gin-gonic/gin"
	"github.com/pjebs/restgate"
	"net/http"
)
//设置验证
func Safemiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		gate := restgate.New("New_Key",
			"New_Secret",
			restgate.Static,
			restgate.Config{
				Key:                []string{"user", "KeyOK"},
				Secret:             []string{"pwd", "SecretOK"},
				//关闭https验证
				HTTPSProtectionOff: true,
			})
		Called:=false
		Adapter:= func(http.ResponseWriter, *http.Request) {
			Called=true
			c.Next()
		}
		//代理
		gate.ServeHTTP(c.Writer,c.Request,Adapter)
		if Called==false {
			c.AbortWithStatus(401)
		}
	}
}
func main() {
	r:=gin.Default()
	r.Use(Safemiddleware())
	//进行验证
	r.GET("/", func(c *gin.Context) {
		res:= struct {
			Code int `json:"code"`
			Msg string `json:"msg"`
			Data interface{} `json:"data"`
		}{http.StatusOK,"验证通过","OK"}
		c.JSON(http.StatusOK,res)
	})
	r.Run()
}

解析模板

解析模板html渲染
main.go

package main
import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func main() {
	r := gin.Default()
	// 模板解析
	r.LoadHTMLFiles("templates/index.html")
	r.GET("/", func(c *gin.Context){
		// 模板渲染
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "Welcome Gin",
		})
	})
	r.Run()
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ .title }}
</body>
</html>

静态资源

静态文件与静态文件夹用法
main.go

package main
import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main() {
    r := gin.Default()
    //只加载html资源
    r.LoadHTMLFiles("templates/index.html")
    //静态资源的路径是以/static开头的,寻找static目录下文件
    //如果静态资源的路径是以/web开头的,寻找web目录下文件
    r.Static("/static", "./static")
    //r.StaticFS("/static", http.Dir("./static"))
    //r.StaticFile("/favicon.ico", "./favicon.ico")
    r.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{
            "title": "Welcome Gin",
        })
    })
    r.Run()
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ .title }}
</body>
</html>

后记

喜欢的话可以三连,后续继续更新其他内容,帮忙推一推,感谢观看!
再次祝大家五一劳动节快乐!!!

举报

相关推荐

0 条评论