package middleware import ( "encoding/base64" "net/http" "strings" "github.com/gin-gonic/gin" ) // SetFlash sets a flash message cookie that will be consumed on the next render. func SetFlash(c *gin.Context, flashType, message string) { // Encode as "type:message" in base64 to avoid cookie value issues value := base64.StdEncoding.EncodeToString([]byte(flashType + ":" + message)) http.SetCookie(c.Writer, &http.Cookie{ Name: "flash", Value: value, Path: "/", MaxAge: 60, HttpOnly: true, SameSite: http.SameSiteLaxMode, }) } // GetFlash reads and clears the flash message cookie. func GetFlash(r *http.Request, w http.ResponseWriter) (flashType, message string) { cookie, err := r.Cookie("flash") if err != nil || cookie.Value == "" { return "", "" } // Clear the cookie http.SetCookie(w, &http.Cookie{ Name: "flash", Path: "/", MaxAge: -1, }) data, err := base64.StdEncoding.DecodeString(cookie.Value) if err != nil { return "", "" } parts := strings.SplitN(string(data), ":", 2) if len(parts) != 2 { return "", "" } return parts[0], parts[1] }