Gin框架学习(七)

本文介绍了使用Gin框架结合restgate中间件实现安全认证,详细展示了设置验证和代理的过程。同时,讲解了如何在Gin中解析模板和提供静态资源,包括模板渲染和静态文件的加载。适合已经有一定Gin基础的读者进阶学习。
摘要由CSDN通过智能技术生成

学习思维导图

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>

后记

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

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北岛末巷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值