Go Gin框架中的路由组特性及其区别解析_gin 路由组
    		       		warning:
    		            这篇文章距离上次修改已过448天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)
 
// 定义一个简单的API结构体
type API struct{}
 
// 实现一个简单的GET方法
func (api *API) Get(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"message": "Hello, World!"})
}
 
func main() {
    router := gin.Default()
 
    // 创建一个组,并将API的Get方法作为路由处理器
    v1 := router.Group("/v1")
    {
        api := &API{}
        v1.GET("/hello", api.Get)
    }
 
    // 启动服务器
    if err := router.Run(":8080"); err != nil {
        fmt.Printf("服务器启动失败: %v\n", err)
    }
}这段代码定义了一个简单的API结构体和一个GET方法,并在主函数中创建了一个Gin路由组/v1,将API的GET方法作为该路由组下/hello路径的GET请求处理器。服务启动后,访问http://localhost:8080/v1/hello将返回JSON格式的响应。
评论已关闭