Created
December 2, 2025 23:16
-
-
Save ringmaster/0607af4a3f472af1187f696b37a6bf2b to your computer and use it in GitHub Desktop.
As simple http server with Gin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import ( | |
| "github.com/gin-gonic/gin" | |
| "github.com/gin-contrib/sessions" | |
| "github.com/gin-contrib/sessions/cookie" | |
| ) | |
| func main() { | |
| r := gin.Default() | |
| store := cookie.NewStore([]byte("secret")) | |
| r.Use(sessions.Sessions("mysession", store)) | |
| r.POST("/login", func(c *gin.Context) { | |
| // You would authenticate the submitted user/password here | |
| session := sessions.Default(c) | |
| session.Set("user", "username") // Set user session | |
| session.Save() | |
| c.JSON(200, gin.H{"message": "Logged in"}) | |
| }) | |
| r.GET("/protected", func(c *gin.Context) { | |
| session := sessions.Default(c) | |
| user := session.Get("user") | |
| if user == nil { | |
| c.JSON(401, gin.H{"message": "Unauthorized"}) | |
| return | |
| } | |
| c.JSON(200, gin.H{"message": "Welcome!", "user": user}) | |
| }) | |
| r.Run() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment