Skip to content
Myr

main.go

This file

Path

examples/basic/main.go

65 lines · 1.3 KiB · Go

Last changed by

chore: add some annotations (#1544)田欧before adoptiond510595

History of this file

Take it

1package main23import (4	"net/http"56	"github.com/gin-gonic/gin"7)89var db = make(map[string]string)1011func setupRouter() *gin.Engine {12	// Disable Console Color13	// gin.DisableConsoleColor()14	r := gin.Default()1516	// Ping test17	r.GET("/ping", func(c *gin.Context) {18		c.String(http.StatusOK, "pong")19	})2021	// Get user value22	r.GET("/user/:name", func(c *gin.Context) {23		user := c.Params.ByName("name")24		value, ok := db[user]25		if ok {26			c.JSON(http.StatusOK, gin.H{"user": user, "value": value})27		} else {28			c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})29		}30	})3132	// Authorized group (uses gin.BasicAuth() middleware)33	// Same than:34	// authorized := r.Group("/")35	// authorized.Use(gin.BasicAuth(gin.Credentials{36	//	  "foo":  "bar",37	//	  "manu": "123",38	//}))39	authorized := r.Group("/", gin.BasicAuth(gin.Accounts{40		"foo":  "bar", // user:foo password:bar41		"manu": "123", // user:manu password:12342	}))4344	authorized.POST("admin", func(c *gin.Context) {45		user := c.MustGet(gin.AuthUserKey).(string)4647		// Parse JSON48		var json struct {49			Value string `json:"value" binding:"required"`50		}5152		if c.Bind(&json) == nil {53			db[user] = json.Value54			c.JSON(http.StatusOK, gin.H{"status": "ok"})55		}56	})5758	return r59}6061func main() {62	r := setupRouter()63	// Listen and Server in 0.0.0.0:808064	r.Run(":8080")65}