当前位置: 首页 > 工具软件 > rustful > 使用案例 >

gin rustful http路由示例

阎懿轩
2023-12-01

工程目录:

jack-centos:test jack$ tree
.
├── go.mod
├── go.sum
├── main.go
└── test

0 directories, 4 files
jack-centos:test jack$

main.go:

package main
  
import (   
        "fmt"

        "github.com/gin-gonic/gin"
)


type my_context struct {
        *gin.Context
}

//@router /hi get
func (c *my_context) hi() {
        fmt.Println("hi")
}

//@router /hello get
func (c *my_context) hello() {
        fmt.Println("hello")
}

func main() {
        var router = gin.New()
        router.GET("/hi", func(c *gin.Context) {
                obj := my_context{c}
                obj.hi()
        })
        router.GET("/hello", func(c *gin.Context) {
                obj := my_context{c}
                obj.hello()
        })

        router.Run(":8080")
}```

编译运行:
```shell
jack-centos:test jack$ go build
jack-centos:test jack$ ./test 
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /hi                       --> main.main.func1 (1 handlers)
[GIN-debug] GET    /hello                    --> main.main.func2 (1 handlers)
[GIN-debug] Listening and serving HTTP on :8080

测试,在本机另外一个终端输入以下命令:

curl http://127.0.0.1:8080/hi

curl http://127.0.0.1:8080/hello
 类似资料: