go get -u github.com/gin-gonic/gin go package main import "github.com/gin-gonic/gin" func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello, Gin framework!", }) }) } go run main.go go package main import ( \t"net/http" \t"github.com/gin-gonic/gin" ) type Todo struct { \tID string `json:"id"` \tTitle string `json:"title"` \tStatus string `json:"status"` } var todos []Todo func main() { \trouter := gin.Default() \trouter.GET("/todos", func(c *gin.Context) { \t\tc.JSON(http.StatusOK, todos) \t}) \trouter.POST("/todos", func(c *gin.Context) { \t\tvar todo Todo \t\tif err := c.ShouldBindJSON(&todo); err != nil { \t\t\tc.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) \t\t\treturn \t\t} \t\ttodos = append(todos, todo) \t\tc.JSON(http.StatusCreated, todo) \t}) \trouter.PUT("/todos/:id", func(c *gin.Context) { \t\tid := c.Param("id") \t\tvar todo Todo \t\tif err := c.ShouldBindJSON(&todo); err != nil { \t\t\tc.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) \t\t\treturn \t\t} \t\tfor index, t := range todos { \t\t\tif t.ID == id { \t\t\t\ttodos[index] = todo \t\t\t\tbreak \t\t\t} \t\t} \t\tc.JSON(http.StatusOK, todo) \t}) \trouter.DELETE("/todos/:id", func(c *gin.Context) { \t\tid := c.Param("id") \t\tfor index, todo := range todos { \t\t\tif todo.ID == id { \t\t\t\ttodos = append(todos[:index], todos[index+1:]...) \t\t\t\tbreak \t\t\t} \t\t} \t\tc.Status(http.StatusOK) \t}) \trouter.Run() } go package main import "github.com/gin-gonic/gin" func main() { \trouter := gin.Default() \tv1 := router.Group("/v1") \t{ \t\tv1.GET("/users", func(c *gin.Context) { \t\t\tc.JSON(200, gin.H{ \t\t\t\t"message": "List of users", \t\t\t}) \t\t}) \t\tv1.GET("/products", func(c *gin.Context) { \t\t\tc.JSON(200, gin.H{ \t\t\t\t"message": "List of products", \t\t\t}) \t\t}) \t} \tv2 := router.Group("/v2") \t{ \t\tv2.GET("/users", func(c *gin.Context) { \t\t\tc.JSON(200, gin.H{ \t\t\t\t"message": "List of users (v2)", \t\t\t}) \t\t}) \t\tv2.GET("/products", func(c *gin.Context) { \t\t\tc.JSON(200, gin.H{ \t\t\t\t"message": "List of products (v2)", \t\t\t}) \t\t}) \t} \trouter.Run() }


上一篇:
下一篇:
切换中文