gin http服务使用

目标

  • 演示get post put delete patch head options方法
  • 演示路由分组
  • 演示路由重定向
  • 显示静态资源
  • 演示cookie使用
  • 自定义服务配置

新建gin_http

package main

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

func test1(c *gin.Context)  {
	c.String(200, "test1")
}
func test2(c *gin.Context)  {
	c.String(200, "test2")
}
func test3(c *gin.Context)  {
	c.String(200, "test3")
}
func cookie(c *gin.Context)  {
	// 读取 Cookie
	cookie, err := c.Cookie("gin_cookie")

	if err != nil {
		cookie = "NotSet"
		// 设置 Cookie
		c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
	}

	fmt.Printf("Cookie value: %s \n", cookie)
}


func main() {
	router := gin.Default()
	//演示静态文件
	router.Static("/assets", "./assets")
	router.StaticFile("/favicon.ico", "./resources/favicon.ico")

	//演示get post put delete patch head options方法
	router.GET("/get", test1)
	router.POST("/post", test1)
	router.PUT("/put", test1)
	router.DELETE("/delete", test1)
	router.PATCH("/patch", test1)
	router.HEAD("/head", test1)
	router.OPTIONS("/options", test1)

	//演示分组
	v1 := router.Group("/v1")
	{
		v1.POST("/login", test1)
		v1.POST("/submit", test2)
		v1.POST("/read", test3)
	}

	v2 := router.Group("/v2")
	{
		v2.POST("/login", test1)
		v2.POST("/submit", test2)
		v2.POST("/read", test3)
	}

	//演示重定向
	// 路由重定向
	router.GET("/redirect", func(c *gin.Context) {
		c.Request.URL.Path = "/test2"
		router.HandleContext(c)
	})
	//演示cookie
	router.GET("/cookie", cookie)
	//自定义http服务
	s := &http.Server{
		Addr:           ":8080",
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	s.ListenAndServe()
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×