Resolve [GIN-debug] redirecting request 307 and [GIN-debug] redirecting request 301 and allow cross-domain requests

Today, when I was using the app to debug the backend interface I wrote, I encountered the following error:

[GIN-debug] redirecting request 307: /douyin/user/login --> /douyin/user/login?username=wxy&password=123456

My routing logic is as follows:

func NewRouter() *gin.Engine {
    
    
	r := gin.Default()
	v1 := r.Group("/douyin")
	{
    
    
		v2 := v1.Group("/user")
		{
    
    
			v2.POST("/register", http.RegisterHandler)
			v2.POST("/login", http.LoginHandler)
			v2.GET("/", http.UserInfoHandler)
		}
	}
	return r

}

The problem is that the route you registered does not match the actual requested route. For example, if your registered route is /douyin/user/login, but the actual route accessed is /douyin/user/login/, this error will occur. However, this error will not occur when I use postman or apifox for personal testing, and this error did occur when I used app debugging.

When I add part "/", the problem is solved.

func NewRouter() *gin.Engine {
    
    
	r := gin.Default()
	v1 := r.Group("/douyin")
	{
    
    
		v2 := v1.Group("/user")
		{
    
    
			v2.POST("/register/", http.RegisterHandler)
			v2.POST("/login/", http.LoginHandler)
			v2.GET("/", http.UserInfoHandler)
		}
	}
	return r

}

I used it here Group, pay more attention to whether your routes are less /or more /.

Then soon I encountered this error again:

[GIN-debug] redirecting request 301: /douyin/feed/ --> /douyin/feed/?latest_time=1692417925203

func NewRouter() *gin.Engine {
    
    
	r := gin.Default()
	v1 := r.Group("/douyin")
	{
    
    
		v2 := v1.Group("/user")
		{
    
    
			v2.POST("/register/", http.RegisterHandler)
			v2.POST("/login/", http.LoginHandler)
			v2.GET("/", http.UserInfoHandler)
		}

		v1.GET("/feed/", http.FeedHandler)

		v2 = v1.Group("/publish")
		{
    
    
			//v2.POST("/action/", http.PublishHandler)
			v2.GET("/list/", http.PublishListHandler)
		}

	}
	return r

}

If the current route cannot be matched, but a handler exists for a path with (without) a trailing slash, automatic redirection is enabled. For example, if /foo/ is requested, but the route only exists for /foo, then the client will be redirected to /foo with an HTTP status code of 301 for GET requests and 307 for all other request methods.

So the reason was that some of the routes I added had extra "/"s. After I deleted them, the problem was solved.

func NewRouter() *gin.Engine {
    
    
	r := gin.Default()
	v1 := r.Group("/douyin")
	{
    
    
		v2 := v1.Group("/user")
		{
    
    
			v2.POST("/register/", http.RegisterHandler)
			v2.POST("/login/", http.LoginHandler)
			v2.GET("/", http.UserInfoHandler)
		}

		v1.GET("/feed", http.FeedHandler)

		v2 = v1.Group("/publish")
		{
    
    
			//v2.POST("/action/", http.PublishHandler)
			v2.GET("/list/", http.PublishListHandler)
		}

	}
	return r

}

It is recommended here to allow cross-domain requests, which can save some trouble.

First, we will introduce the use of the community’s https://github.com/gin-contrib/cors library to solve cross-domain problems under the front-end and back-end separation architecture with one line of code.

package router

import (
	"ByteRhythm/app/gateway/http"
	"ByteRhythm/app/gateway/middleware"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func NewRouter() *gin.Engine {
    
    
	r := gin.Default()
	r.Use(cors.Default())
	r.Use(middleware.JWT())

	v1 := r.Group("/douyin")
	{
    
    
		v1.GET("/feed", http.FeedHandler)

		v2 := v1.Group("/user")
		{
    
    
			v2.POST("/register/", http.RegisterHandler)
			v2.POST("/login/", http.LoginHandler)
			v2.GET("/", http.UserInfoHandler)
		}

		v2 = v1.Group("/publish")
		{
    
    
			v2.POST("/action/", http.PublishHandler)
			v2.GET("/list/", http.PublishListHandler)
		}

	}
	return r

}

Of course, you can also customize cross-domain middleware:

//cors.go
package middleware

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// Cors 跨域配置
func Cors() gin.HandlerFunc {
    
    
	return func(c *gin.Context) {
    
    
		method := c.Request.Method               // 请求方法
		origin := c.Request.Header.Get("Origin") // 请求头部
		var headerKeys []string                  // 声明请求头keys
		for k := range c.Request.Header {
    
    
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ", ")
		if headerStr != "" {
    
    
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
    
    
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}
		if origin != "" {
    
    
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Origin", "*")                                       // 这是允许访问所有域
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") // 服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
			//  header的类型
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			// 允许跨域设置                                                                                                      可以返回其他子段
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
			c.Header("Access-Control-Max-Age", "172800")                                                                                                                                                           // 缓存请求信息 单位为秒
			c.Header("Access-Control-Allow-Credentials", "false")                                                                                                                                                  //  跨域请求是否需要带cookie信息 默认设置为true
			c.Set("content-type", "application/json")                                                                                                                                                              // 设置返回格式是json
		}
		// 放行所有OPTIONS方法
		if method == "OPTIONS" {
    
    
			c.JSON(http.StatusOK, "Options Request!")
		}
		// 处理请求
		c.Next() //  处理请求
	}
}

The corresponding routing logic is as follows:

package router

import (
	"ByteRhythm/app/gateway/http"
	"ByteRhythm/app/gateway/middleware"

	"github.com/gin-gonic/gin"
)

func NewRouter() *gin.Engine {
    
    
	r := gin.Default()
	//允许跨域请求
	r.Use(middleware.Cors())
	v1 := r.Group("/douyin")
	{
    
    
		v2 := v1.Group("/user")
		{
    
    
			v2.POST("/register/", http.RegisterHandler)
			v2.POST("/login/", http.LoginHandler)
			v2.GET("/", http.UserInfoHandler)
		}

		v1.GET("/feed", http.FeedHandler)

		v2 = v1.Group("/publish")
		{
    
    
			//v2.POST("/action/", http.PublishHandler)
			v2.GET("/list/", http.PublishListHandler)
		}

	}
	return r
}

Guess you like

Origin blog.csdn.net/m0_63230155/article/details/132372280