gin相关操作--一起学习921190764

gin官方文档

https://gin-gonic.com/docs/quickstart/

1. 安装

go get -u github.com/gin-gonic/gin
https://github.com/gin-gonic/gin

简单入门

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func pong(c *gin.Context) {
	//c.JSON(http.StatusOK, gin.H{
	//	"message": "pong",
	//})
	//第二种
	c.JSON(http.StatusOK, map[string]string{
		"message": "pong",
	})
}
func main() {
	//实例化一个gin的server对象
	r := gin.Default()

	r.GET("/ping", pong)
	r.Run(":8084") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
//restful 的开发中
	router.GET("/someGet", getting)
	router.POST("/somePost", posting)
	router.PUT("/somePut", putting)
	router.DELETE("/someDelete", deleting)
	router.PATCH("/somePatch", patching)
	router.HEAD("/someHead", head)
	router.OPTIONS("/someOptions", options)

1. 路由分组

func main() {
router := gin.Default()
// Simple group: v1
v1 := router.Group("/v1")
{
	v1.POST("/login", loginEndpoint)
	v1.POST("/submit", submitEndpoint)
	v1.POST("/read", readEndpoint)
}
// Simple group: v2
v2 := router.Group("/v2")
{
	v2.POST("/login", loginEndpoint)
	v2.POST("/submit", submitEndpoint)
	v2.POST("/read", readEndpoint)
}
router.Run(":8082")
}

2. 带参数的url

package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
		"message": "pong",
		})
	})
	r.GET("/user/:name/:action/", func(c *gin.Context) {
	name := c.Param("name")
	action := c.Param("action")
	c.String(http.StatusOK, "%s is %s", name, action)
	})
	r.GET("/user/:name/*action", func(c *gin.Context) {
	name := c.Param("name")
	action := c.Param("action")
	c.String(http.StatusOK, "%s is %s", name, action)
	})

r.Run(":8082")
}

案例源码

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	router := gin.Default()

	goodsGroup := router.Group("/goods")
	//不需要依附于任何函数体
	{
		goodsGroup.GET("/list", goodsList)

		//goodsGroup.GET("/1", goodsDetail) //获取商品id为1的详细信息
		//带参的url
		//goodsGroup.GET("/:id/:action", goodsDetail) //获取商品id为1的详细信息
		goodsGroup.GET("/:id/*action", goodsDetail) //获取商品id为1的详细信息 带*就会把id后面全部的路径全部取出来
		goodsGroup.POST("/add", createGoods)
	}
	router.Run(":8082")
}

func createGoods(context *gin.Context) {

}

func goodsDetail(context *gin.Context) {
	id := context.Param("id")
	action := context.Param("action")
	context.JSON(http.StatusOK, gin.H{
		"id":     id,
		"action": action,
	})
}

func goodsList(context *gin.Context) {
	context.JSON(http.StatusOK, gin.H{
		"name": "goodlist",
	})
}

3. 获取路由分组的参数

package main
import "github.com/gin-gonic/gin"
type Person struct {
	ID string `uri:"id" binding:"required,uuid"`
	Name string `uri:"name" binding:"required"`
}
func main() {
	route := gin.Default()
	route.GET("/:name/:id", func(c *gin.Context) {
		var person Person
		if err := c.ShouldBindUri(&person); err != nil {
		c.JSON(400, gin.H{"msg": err})
		return
	}
	c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
	})
	route.Run(":8088")
}

案例代码

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// Person 这是来约束参数是什么类型
type Person struct {
	//Id   string `uri:"id" binding:"required,uuid"` //这里必须是uuid http://127.0.0.1:8083/bobby/6e4e2015-a5c2-9279-42a6-6b70478276bc
	Id   int    `uri:"id" binding:"required"`
	Name string `uri:"name" binding:"required"`
}

func main() {

	router := gin.Default()
	router.GET("/:name/:id", func(context *gin.Context) {
		var person Person
		if err := context.ShouldBindUri(&person); err != nil {
			context.Status(404)
		}
		context.JSON(http.StatusOK, gin.H{
			"name": person.Name,
			"id":   person.Id,
		})
	})

	router.Run(":8083")
}

1. 获取get参数

func main() {
router := gin.Default()
// 匹配的url格式: /welcome?firstname=Jane&lastname=Doe
router.GET("/welcome", func(c *gin.Context) {
	firstname := c.DefaultQuery("firstname", "Guest")
	lastname := c.Query("lastname") // 是 c.Request.URL.Query().Get("lastname
	c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
	})
	router.Run(":8080")
}

2. 获取post参数

func main() {
	router := gin.Default()
	router.POST("/form_post", func(c *gin.Context) {
	message := c.PostForm("message")
	nick := c.DefaultPostForm("nick", "anonymous") // 此⽅法可以设置默认值
		c.JSON(200, gin.H{
		"status": "posted",
		"message": message,
		"nick": nick,
		})
	})
	router.Run(":8080")
}

3. get、post混合

POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
name=manu&message=this_is_great
func main() {
	router := gin.Default()
	router.POST("/post", func(c *gin.Context) {
		id := c.Query("id")
		page := c.DefaultQuery("page", "0")
		name := c.PostForm("name")
		message := c.PostForm("message")
		fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, mes
		})
	router.Run(":8080")
}

在这里插入图片描述
在这里插入图片描述

案例源码

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	router := gin.Default()

	//GET请求获取参数
	router.GET("/welcome", welcome)

	//POST获取参数
	router.POST("/form_post", formPost)

	//get和post请求混合使用
	router.POST("/post", getPost)

	router.Run(":8083")
}

func getPost(context *gin.Context) {
	id := context.Query("id")
	page := context.DefaultQuery("page", "0")
	name := context.PostForm("name")
	message := context.DefaultPostForm("message", "信息")
	context.JSON(http.StatusOK, gin.H{
		"id":      id,
		"page":    page,
		"name":    name,
		"message": message,
	})
}

// http://127.0.0.1:8083/form_post 然后在body写入参数
func formPost(context *gin.Context) {
	message := context.PostForm("message")
	nick := context.DefaultPostForm("nick", "anonymous")
	context.JSON(http.StatusOK, gin.H{
		"message": message,
		"nick":    nick,
	})
}

// http://127.0.0.1:8083/welcome
// 如果什么都不写取默认值 为bobby 和chengpeng
// http://127.0.0.1:8083/welcome?firstname=chengpeng2&lastname=llAS
// 如果这种写法 得到的就是chengpeng2 和llAS
func welcome(context *gin.Context) {
	firstName := context.DefaultQuery("firstname", "bobby")
	lastName := context.DefaultQuery("lastname", "chengpeng")
	context.JSON(http.StatusOK, gin.H{
		"first_name": firstName,
		"last_name":  lastName,
	})
}

1. 输出json和protobuf

新建user.proto文件

syntax = "proto3";
option go_package = ".;proto";
message Teacher {
 string name = 1;
 repeated string course = 2;
}

protoc --go_out=. --go-grpc_out=. .\user.proto

package main
import (
"github.com/gin-gonic/gin"
"net/http"
"start/gin_t/proto"
)
func main() {
	r := gin.Default()
	// gin.H is a shortcut for map[string]interface{}
	r.GET("/someJSON", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})
	r.GET("/moreJSON", func(c *gin.Context) {
		// You also can use a struct
		var msg struct {
		Name string `json:"user"` //转义
		Message string
		Number int
		}
		msg.Name = "Lena"
		msg.Message = "hey"
		msg.Number = 123
		// Note that msg.Name becomes "user" in the JSON
		// Will output : {"user": "Lena", "Message": "hey", "Number": 123}
		c.JSON(http.StatusOK, msg)
	})
	r.GET("/someProtoBuf", func(c *gin.Context) {
		courses := []string{"python", "django", "go"}
		data:&proto.Teacher{
		Name: "bobby",
		Course: courses,
	}
	// Note that data becomes binary data in the response
	// Will output protoexample.Test protobuf serialized data
	c.ProtoBuf(http.StatusOK, data)
	})
	// Listen and serve on 0.0.0.0:8080
	r.Run(":8083")
}

2. PureJSON

通常情况下,JSON会将特殊的HTML字符替换为对应的unicode字符,比如 < 替换为 \u003c ,如果想原样输出html,则使用PureJSON

func main() {
	r := gin.Default()
	// Serves unicode entities
	r.GET("/json", func(c *gin.Context) {
	c.JSON(200, gin.H{
	"html": "<b>Hello, world!</b>",
	})
	})
	// Serves literal characters
	r.GET("/purejson", func(c *gin.Context) {
	c.PureJSON(200, gin.H{
	"html": "<b>Hello, world!</b>",
	})
	})
	// listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}

源码案例

package main

import (
	proto1 "GormStart/gin_start/ch05/proto"
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	router := gin.Default()

	//JSON
	router.GET("/moreJSON", moreJSON)
	//proto
	router.GET("/someProtoBuf", returnProto)

	router.Run(":8083")
}

func returnProto(context *gin.Context) {
	course := []string{"python", "go", "微服务"}
	user := &proto1.Teacher{
		Name:   "bobby",
		Course: course,
	}

	context.ProtoBuf(http.StatusOK, user)

}

//	{
//	   "user": "bobby",
//	   "Message": "这是测试一个json",
//	   "Number": 20
//	}
//
// http://127.0.0.1:8083/moreJSON
func moreJSON(context *gin.Context) {
	var msg struct {
		Name    string `json:"user"`
		Message string
		Number  int
	}

	msg.Name = "bobby"
	msg.Message = "这是测试一个json"
	msg.Number = 20

	context.JSON(http.StatusOK, msg)
}

客户端反解码

package main

import (
	proto1 "GormStart/gin_start/ch05/proto"
	"fmt"
	"google.golang.org/protobuf/proto"
	"io/ioutil"
	"net/http"
)

func main() {
	resp, _ := http.Get("http://127.0.0.1:8083/someProtoBuf")
	bytes, _ := ioutil.ReadAll(resp.Body)
	var res proto1.Teacher
	_ = proto.Unmarshal(bytes, &res)
	fmt.Println(res.Name, res.Course)
}

1. 表单的基本验证

若要将请求主体绑定到结构体中,请使用模型绑定,目前支持JSON、XML、YAML和标准表单值(foo=bar&boo=baz)的绑定。
Gin使用 go-playground/validator和https://github.com/go-playground/validator 验证参数,查看完整文档(https://pkg.go.dev/github.com/go-playground/validator/v10)。
需要在绑定的字段上设置tag,比如,绑定格式为json,需要这样设置 json:“fieldname” 。此外,Gin还提供了两套绑定方法:
Must bind

  • Methods - Bind , BindJSON , BindXML , BindQuery , BindYAML
    Behavior - 这些方法底层使用 MustBindWith ,如果存在绑定错误,请求将被以下指令中c.AbortWithError(400,err).SetType(ErrorTypeBind) ,响应状态代码会被设置为400,请求头 Content-Type 被设置为 text/plain;charset=utf-8 。注意,如果你试图在此之后设置响应代码,将会发出一个警告 [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422 ,如果你希望更好地控制行为,请使用 ShouldBind 相关的方法

Should bind

  • Methods - ShouldBind(动态决定JSON,XML等等) , ShouldBindJSON , ShouldBindXML ,ShouldBindQuery , ShouldBi ndYAML
  • Behavior - 这些方法底层使用 ShouldBindWith ,如果存在绑定错误,则返回错误,开发人员 可以正确处理请求和错误。
    当我们使用绑定方法时,Gin会根据Content-Type推断出使用哪种绑定器,如果你确定你绑定的是什么,你可以使用 MustBindWith 或者 BindingWith 。
    你还可以给字段指定特定规则的修饰符,如果一个字段用 binding:“required” 修饰,并且在绑定时该字段的值为空,那么将返回一个错误。

validator支持中文==>国际化

go语言实现翻译解释器

"github.com/gin-gonic/gin/binding"
"github.com/go-playground/locales/en"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
en_translations "github.com/go-playground/validator/v10/translations/en"
zh_translations "github.com/go-playground/validator/v10/translations/zh"
	
var trans ut.Translator

// InitTrans 翻译
func InitTrans(locale string) (err error) {
	//修改gin框架中的validator引擎属性,实现定制
	//Engine返回为StructValidator实现提供动力的底层验证器引擎。
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		zhT := zh.New() //中文翻译器
		enT := en.New() //英文翻译器
		// 第一个参数是备用(fallback)的语言环境  // 后面的参数是应该支持的语言环境(支持多个)
		uni := ut.New(enT, zhT, enT) //后面可以重复放
		// locale 通常取决于 http 请求头的 'Accept-Language'
		//根据参数取翻译器实例
		// 也可以使用 uni.FindTranslator(...) 传入多个locale进行查找
		trans, ok = uni.GetTranslator(locale) //拿到Translator
		if !ok {
			return fmt.Errorf("uni.GetTranslator(%s)", locale)
		}
		// 注册翻译器
		switch locale {
		case "en":
			en_translations.RegisterDefaultTranslations(v, trans) //使用英文的注册器
		case "zh":
			zh_translations.RegisterDefaultTranslations(v, trans) //使用中文注册器
		default:
			en_translations.RegisterDefaultTranslations(v, trans)
		}

		return
	}
	return
}

案例整体源码

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"net/http"
	"reflect"
	"strings"
)

// LoginForm 绑定为json
type LoginForm struct {
	//form json xml
	User     string `form:"user" json:"user" xml:"user" binding:"required,min=3,max=10"` //required必填最短长度
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

// SignUpForm 注册
type SignUpForm struct {
	Age        uint8  `json:"age" binding:"gte=1,lte=130"`
	Name       string `json:"name" binding:"required,min=3"`
	Email      string `json:"email" binding:"required,email"` //email是否是合法的格式
	Password   string `json:"password" binding:"required"`
	RePassword string `json:"re_password" binding:"required,eqfield=Password"` //跨字段验证 eqfield指定上面的字段和它相等
}

var trans ut.Translator

// InitTrans 翻译
func InitTrans(locale string) (err error) {
	//修改gin框架中的validator引擎属性,实现定制
	//Engine返回为StructValidator实现提供动力的底层验证器引擎。
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		//注册一个获取json的tag的自定义方法
		v.RegisterTagNameFunc(func(field reflect.StructField) string {
			//name1 := strings.SplitN(field.Tag.Get("json"), ",", 2)
			//fmt.Println("chengpeng", name1)
			//a := field.Tag.Get("form")
			//fmt.Println("chengpeng", a)

			name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
			if name == "_" {
				return ""
			}
			return name
		})
		zhT := zh.New() //中文翻译器
		enT := en.New() //英文翻译器
		// 第一个参数是备用(fallback)的语言环境  // 后面的参数是应该支持的语言环境(支持多个)
		uni := ut.New(enT, zhT, enT) //后面可以重复放
		// locale 通常取决于 http 请求头的 'Accept-Language'
		//根据参数取翻译器实例
		// 也可以使用 uni.FindTranslator(...) 传入多个locale进行查找
		trans, ok = uni.GetTranslator(locale) //拿到Translator
		if !ok {
			return fmt.Errorf("uni.GetTranslator(%s)", locale)
		}
		// 注册翻译器
		switch locale {
		case "en":
			en_translations.RegisterDefaultTranslations(v, trans) //使用英文的注册器
		case "zh":
			zh_translations.RegisterDefaultTranslations(v, trans) //使用中文注册器
		default:
			en_translations.RegisterDefaultTranslations(v, trans)
		}

		return
	}
	return
}

//	"msg": {	"LoginForm.user": "user长度必须至少为3个字符" }
//
// 去掉LoginForm
func removeTopStruct(fileds map[string]string) map[string]string {
	rsp := map[string]string{}

	for filed, err := range fileds {
		//要查找的字符串.的位置strings.Index(filed, ".")
		rsp[filed[strings.Index(filed, ".")+1:]] = err
	}
	return rsp
}

func main() {

	err := InitTrans("zh")
	if err != nil {
		fmt.Println("获取翻译器错误")
		return
	}

	router := gin.Default()
	router.POST("/loginJSON", func(context *gin.Context) {
		var loginForm LoginForm
		//你应该这样 获取参数
		err := context.ShouldBind(&loginForm)
		if err != nil {
			errs, ok := err.(validator.ValidationErrors) //转换为FieldError
			if !ok {
				context.JSON(http.StatusOK, gin.H{
					"msg": err.Error(),
				})
			}
			//fmt.Println(err.Error())
			context.JSON(http.StatusBadRequest, gin.H{
				//"msg": err.Error(),
				//"msg": errs.Translate(trans),
				"msg": removeTopStruct(errs.Translate(trans)),
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"msg": "登录成功",
		})
	})

	router.POST("/signup", func(context *gin.Context) {
		var signUpForm SignUpForm
		//你应该这样 获取参数
		err := context.ShouldBind(&signUpForm)

		if err != nil {
			errs, ok := err.(validator.ValidationErrors) //转换为FieldError
			//不能转换成功
			if !ok {
				context.JSON(http.StatusOK, gin.H{
					"msg": err.Error(),
				})
			}
			context.JSON(http.StatusBadRequest, gin.H{
				//"msg": err.Error(),
				//"msg": errs.Translate(trans),
				"msg": removeTopStruct(errs.Translate(trans)),
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"msg": "注册成功",
		})
	})
	_ = router.Run(":8083")

}

中间件==>自定义gin中间件

是一类能够为一种或多种应用程序合作互通、资源共享,同时还能够为该应用程序提供相关的服务的软件。中间件是一类软件统称,而非一种软件;中间件不仅仅实现互连,还要实现应用之间的互操作。
中间件与操作系统和数据库共同构成基础软件三大支柱,是一种应用于分布式系统的基础软件,位于应用与操作系统、数据库之间,为上层应用软件提供开发、运行和集成的平台。中间件解决了异构网络环境下软件互联和互操作等共性问题,并提供标准接口、协议,为应用软件间共享资源提供了可复用的“标准件”。

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// MyLogger 自定义中间件
func MyLogger() gin.HandlerFunc {

	return func(context *gin.Context) {
		now := time.Now()
		// 设置变量到Context的key中,可以通过Get()取
		context.Set("example", "123456")
		//让原本该执行的逻辑继续执行
		context.Next()

		//把开始的时间给我去计算时长
		end := time.Since(now)
		//拿到状态信息   // 中间件执行完后续的一些事情
		status := context.Writer.Status()
		//[GIN-debug] Listening and serving HTTP on :8083
		//耗时:%!V(time.Duration=610500)
		//状态 200
		fmt.Printf("耗时:%V\n", end)
		fmt.Println("状态", status)
	}
}

func main() {
	router := gin.Default()

	router.Use(MyLogger())

	router.GET("/ping", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})

	router.Run(":8083")
}

//func main() {
//	//engine.Use(Logger(), Recovery()) 默认使用这两个中间件
//	//router := gin.Default()
//	router := gin.New()
//	//使用logger中间件和recovery(恢复)中间件 全局使用
//	router.Use(gin.Logger(), gin.Recovery())
//
//	//某一组url 这样配置这个中间件只有这样开始的时候,这个url才会影响
//	authrized := router.Group("/goods")
//	authrized.Use(AuthRequired)
//
//}
//
 AuthRequired 中间件
//func AuthRequired(context *gin.Context) {
//
//}

终止中间件后续的逻辑的执行

//如果你想不执行后面的逻辑
context.Abort()

为什么连return都阻止不了后续逻辑的执行?

那是因为Use或者GET等等里面有一个HandlersChain的切片(type HandlersChain []HandlerFunc)添加到切片中去,如果使用return只是返回这个函数,并不会结束全部的接口。使用Next函数,index只是跳转到下个函数里面,如果使用Abort他会把index放到切片最后,那么全部都会结束。

案例源码

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// MyLogger 自定义中间件
func MyLogger() gin.HandlerFunc {

	return func(context *gin.Context) {
		now := time.Now()
		// 设置变量到Context的key中,可以通过Get()取
		context.Set("example", "123456")

		//让原本该执行的逻辑继续执行
		context.Next()

		//把开始的时间给我去计算时长
		end := time.Since(now)
		//拿到状态信息   // 中间件执行完后续的一些事情
		status := context.Writer.Status()

		fmt.Printf("耗时:%V\n", end)
		fmt.Println("状态", status)
	}
}

func TokenRequired() gin.HandlerFunc {
	return func(context *gin.Context) {
		var token string

		//token放到了Header里面
		for k, v := range context.Request.Header {
			if k == "X-Token" {
				token = v[0]
				fmt.Println("chengpeng", token)
			} else {
				fmt.Println(k, v)
			}
			//fmt.Println(k, v, token)
		}

		if token != "bobby" {
			context.JSON(http.StatusUnauthorized, gin.H{
				"msg": "未登录",
			})
			//return结束不了
			//return
			//如果你想不执行后面的逻辑
			context.Abort()
		}
		context.Next()
	}
}

func main() {
	router := gin.Default()

	//router.Use(MyLogger())

	router.Use(TokenRequired())
	router.GET("/ping", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})

	router.Run(":8083")
}

//func main() {
//	//engine.Use(Logger(), Recovery()) 默认使用这两个中间件
//	//router := gin.Default()
//	router := gin.New()
//	//使用logger中间件和recovery(恢复)中间件 全局使用
//	router.Use(gin.Logger(), gin.Recovery())
//
//	//某一组url 这样配置这个中间件只有这样开始的时候,这个url才会影响
//	authrized := router.Group("/goods")
//	authrized.Use(AuthRequired)
//
//}
//
 AuthRequired 中间件
//func AuthRequired(context *gin.Context) {
//
//}

gin返回html

官方地址:https://golang.org/pkg/html/template/
翻 译 : https://colobu.com/2019/11/05/Golang-Templates-Cheatsheet/#if/else_%E8%AF%AD%E5%8F%A5

1. 设置静态文件路径

package main
import (
 "net/http"
 "github.com/gin-gonic/gin"
)
func main() {
	 // 创建⼀个默认的路由引擎
	 r := gin.Default()
	 // 配置模板
	 r.LoadHTMLGlob("templates/**/*")
	 //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html
	 // 配置静态⽂件夹路径 第⼀个参数是api,第⼆个是⽂件夹路径
	 r.StaticFS("/static", http.Dir("./static"))
	 // GET:请求⽅式;/hello:请求的路径
	 // 当客户端以GET⽅法请求/hello路径时,会执⾏后⾯的匿名函数
	 r.GET("/posts/index", func(c *gin.Context) {
		 // c.JSON:返回JSON格式的数据
		 c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
		 "title": "posts/index",
		 })
	 })
	 r.GET("gets/login", func(c *gin.Context) {
		 c.HTML(http.StatusOK, "posts/login.tmpl", gin.H{
		 "title": "gets/login",
		 })
	 })
	 // 启动HTTP服务,默认在0.0.0.0:8080启动服务
	 r.Run()
}

2. index.html内容

<html>
 <h1>
 {{ .title }}
 </h1>
</html>

3. templates/posts/index.tmpl

{{ define "posts/index.tmpl" }}
<html><h1>
 {{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}

4. templates/users/index.tmpl

{{ define "users/index.tmpl" }}
<html><h1>
 {{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}

案例源码

{{define "goods/list.html"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>商品名称</title>
    </head>
    <body>
        <h1>商品列表页</h1>
    </body>
    </html>
{{end}}
{{define "users/list.html"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>用户列表页</title>
    </head>
    <body>
        <h1>用户列表页</h1>
    </body>
    </html>
{{end}}

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

在这里插入图片描述
优雅退出: https://gin-gonic.com/zh-cn/docs/examples/graceful-restart-or-stop/

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	//优雅退出,当我们关闭程序的时候,应该做的后续处理
	//微服务 启动之前或者启动之后会做一件事,将当前的服务的ip地址和端口号注册到注册中心
	//我们当前的服务停止了以后并没有告知注册中心
	router := gin.Default()

	router.GET("/", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"msg": "pong",
		})
	})

	go func() {
		router.Run(":8083") //启动以后会一直停在这里
	}()

	//如果想要接收到信号 kill -9 强杀命令
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	//处理后续的逻辑
	fmt.Println("关闭server中...")
	fmt.Println("注销服务...")
}

设置静态文件

router.Static("/static", "./static")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/169814.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Redis高级特性和应用(发布 订阅、Stream)

目录 发布和订阅 操作命令 发布消息 订阅消息 查询订阅情况 查看活跃的频道 查看频道订阅数 使用场景和缺点 Redis Stream Stream总述 常用操作命令 生产端 消费端 单消费者 消费组 创建消费组 消息消费 在Redis中实现消息队列 基于pub/sub 基于Stream Re…

Three.js相机模拟

有没有想过如何在 3D Web 应用程序中模拟物理相机? 在这篇博文中,我将向你展示如何使用 Three.js和 OpenCV 来完成此操作。 我们将从模拟针孔相机模型开始,然后添加真实的镜头畸变。 具体来说,我们将仔细研究 OpenCV 的两个失真模型,并使用后处理着色器复制它们。 拥有逼…

MySQL 备份和恢复

目录 一.MySQL数据库的备份的分类 1.1.数据备份的重要性 1.2.数据库备份的分类和备份策略 1.3.常见的备份方法 二.MySQL完全备份 2.1.什么是完全备份 2.2.完全备份的优缺点 2.3.实现物理冷备份与恢复 1&#xff09;实现流程 2&#xff09;前置准备 3&#xff09;实现…

nodejs微信小程序 +python+PHP+图书销售管理系统的设计与实现-网上书店-图书商城-计算机毕业设计

目 录 摘 要 I ABSTRACT II 目 录 II 第1章 绪论 1 1.1背景及意义 1 1.2 国内外研究概况 1 1.3 研究的内容 1 第2章 相关技术 3 2.1 nodejs简介 4 2.2 express框架介绍 6 2.4 MySQL数据库 4 第3章 系统分析 5 3.1 需求分析 5 3.2 系统可行性分析 5 3.2.1技术可行性&#xff1a;…

俄罗斯方块游戏制作

创建包和文件夹 1.创建小方块类 package eluosifangkuai; import java.awt.image.BufferedImage; import java.util.Objects;/*** author xiaoZhao* date 2022/5/7* describe* 小方块类* 方法&#xff1a; 左移、右移、下落*/ public class Cell {// 行private int row;//…

线上bug-接口速度慢

&#x1f47d;System.out.println(“&#x1f44b;&#x1f3fc;嗨&#xff0c;大家好&#xff0c;我是代码不会敲的小符&#xff0c;双非大四&#xff0c;Java实习中…”); &#x1f4da;System.out.println(“&#x1f388;如果文章中有错误的地方&#xff0c;恳请大家指正&a…

【opencv】debug报错HEAP CORRUPTION DETECTED

运行至第一句涉及矩阵运算的代码&#xff08;如cv::multiply&#xff09;时报错 HEAP CORRUPTION DETECTED: after Normal block (#45034) at 0x000001BDC586F0E0. CRT detected that the application wrote to memory after end of heap buffer.release下不会报错&#xff0…

go语言学习-go环境安装

1、安装Go 1.1 下载安装 go官网 找对应电脑的版本进行安装即可。 点击安装包&#xff0c;直接下一步下一步即可&#xff0c;安装目录可以自行设置一下。 1.2 验证 windows通过cmd验证。 linux或者mac可以通过自带终端执行测试。 2、配置环境变量 2.1 windows 找到系统…

PostgreSQL数据库结合内网穿透实现公网远程连接

文章目录 前言1. 安装postgreSQL2. 本地连接postgreSQL3. Windows 安装 cpolar4. 配置postgreSQL公网地址5. 公网postgreSQL访问6. 固定连接公网地址7. postgreSQL固定地址连接测试 前言 PostgreSQL是一个功能非常强大的关系型数据库管理系统&#xff08;RDBMS&#xff09;,下…

axios的原理及实现一个简易版axios

面试官&#xff1a;你了解axios的原理吗&#xff1f;有看过它的源码吗&#xff1f; 一、axios的使用 关于axios的基本使用&#xff0c;上篇文章已经有所涉及&#xff0c;这里再稍微回顾下&#xff1a; 发送请求 import axios from axios;axios(config) // 直接传入配置 axio…

8 Redis与Lua

LUA脚本语言是C开发的&#xff0c;类似存储过程,是为了实现完整的原子性操作&#xff0c;可以用来补充redis弱事务的缺点. 1、LUA脚本的好处 2、Lua脚本限流实战 支持分布式 import org.springframework.core.io.ClassPathResource; import org.springframework.data.redis…

C练习题_14

一、单项选择题&#xff08;本大题共 20小题&#xff0c;每小题 2分&#xff0c;共 40分。在每小题给出的四个备选项中&#xff0c;选出一个正确的答案&#xff0c;并将所选项前的字母填写在答题纸的相应位置上。) 以下叙述不正确的是&#xff08;&#xff09; A.一个C源程序可…

桥接模式学习

目录 背景过程总结 背景 现在要解决源码阶段的继承关系&#xff0c;无法在运行时改变从父类继承的实现。这里用的是手机品牌还有手机中的app&#xff0c;这种问题如何进行解决呢。这就要引入一个模式&#xff1a;桥接模式 过程 1、原则&#xff1a;合成/复用原则 &#xff1…

(二)汇编语句组成

一个完整的 RISC-V 汇编程序有多条 语句&#xff08;statement&#xff09; 组成。 一条典型的 RISC-V 汇编 语句 由 3 部分组成&#xff1a; 1.标签 List item label&#xff08;标签&#xff09;: 标签是标识程序位置的记号。通常定义一个名称然后加上":"后缀。…

python连接hive报错:TypeError: can‘t concat str to bytes

目录 一、完整报错 二、解决 三、 其他报错 一、完整报错 Traceback (most recent call last): File "D:/Gitlab/my_world/hive2csv.py", line 18, in <module> conn hive.Connection(hosthost, portport, usernameusername, passwordpassword, data…

微机原理_14

一、单项选择题(本大题共15小题,每小题3分,共45分。在每小题给出的四个备选项中,选出一个正确的答案。&#xff09; 1,下面寻址方式的操作数不在存储器中的是(&#xff09; A. 堆栈寻址 B. 寄存器间址 C.寄存器寻址 D. 直接寻址 2,条件转移指令JNE的条件是(&#xff09; A. CF…

Linux入门必备指令

Linux学习之路起始篇——Linux基本指令 文章目录 Linux学习之路起始篇——Linux基本指令**一、ls指令****二、pwd命令****三、cd命令****四、touch指令****五、mkdir命令****六、rm命令****七、man 命令****八、cp命令****九、mv命令****10、cat 指令****十一、tac命令** 前言&…

基于AVR单片机的便携式心电监测设备设计与实现

基于AVR单片机的便携式心电监测设备是一种常用的医疗设备&#xff0c;用于随时监测和记录人体的心电信号。本文将介绍便携式心电监测设备的设计原理和实现步骤&#xff0c;并提供相应的代码示例。 1. 设计概述 便携式心电监测设备是一种小巧、方便携带的设备&#xff0c;能够…

【LSTM】北京pm2.5 天气预测--pytorch版本,有代码可以跑通-LSTM回归问题,工程落地一网打尽

文章目录 前言1. 知识理解1.1 核心理解1.2 原理1.2.1 图解LSTM1.2.1 分词1.2.1 英语的词表示1.2.2 中文的词表示1.2.3 构建词表 2. 工程代码2.1 数据预处理2.2 数据集&模型构建2.3 模型训练2.4 保持模型&加载模型&预测 前言 LSTM 少分析原理&#xff0c;更强调工程…

复杂数据统计与R语言程序设计实验一

1.下载并安装R语言软件&#xff0c;熟悉基本操作的命令及操作界面&#xff0c;掌握软件的使用方法&#xff08;提供学号加姓名的截图&#xff09;。 2.下载并安装Rstudio&#xff0c; &#xff08;提供运行代码及运行结果的截图&#xff09;。 3.下载并安装R包DT&#xff0c;…
最新文章