If both http.handler-based middleware and Gin middleware are used, what is the order of request processing?

Here is the code:

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"github.com/alexedwards/scs/v2"
)

var sessionManager *scs.SessionManager

func main() {
	sessionManager = scs.New()
	sessionManager.Lifetime = 24 * time.Hour

	router := gin.Default()

	router.Use(getSessionInMiddleware())

	router.GET("/put", putHandler)
	router.GET("/get", getHandler)

	http.ListenAndServe(":4000", sessionManager.LoadAndSave(router))
}

func getSessionInMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		uid := sessionManager.GetString(c.Request.Context(), "uid")
		fmt.Printf("%s\n", uid)
		c.Next()
	}
}

func putHandler(c *gin.Context) {
	sessionManager.Put(c.Request.Context(), "uid", "42")
}

func getHandler(c *gin.Context) {
	uid := sessionManager.GetString(c.Request.Context(), "uid")
	c.String(http.StatusOK, uid)
}

I think this approach is not elegant enough. Is there a better way to implement this functionality? Specifically, using both Gin and SCS together while utilizing LoadAndSave from SCS.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.