参考ページ
Quick start
インストール
mkdir gin_work && cd gin_work
go mod init gin_work
go get -u github.com/gin-gonic/gin
サンプル
example.go
package main
import "github.com/gin-gonic/gin"
func main() {
rr := gin.Default()
rr.GET("/ping", func(cc *gin.Context) {
cc.JSON(200, gin.H{
"message": "pong",
})
})
rr.Run()
}
サーバーの実行
go run example.go
http://localhost:8080/ping にアクセスする
curl http://localhost:8080/ping
http :8080/ping
Parameter を使うサンプル
parameters.go
package main
import "github.com/gin-gonic/gin"
import "net/http"
func main() {
router := gin.Default()
// This handler will match /user/john but will not match /user/ or /user
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// However, this one will match /user/john/ and also /user/john/send
// If no other routers match /user/john, it will redirect to /user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
// For each matched request Context will hold the route definition
router.POST("/user/:name/*action", func(c *gin.Context) {
// c.FullPath() == "/user/:name/*action" // true
})
router.Run(":8080")
}
サーバーの実行
go run parameters.go
クライアントからアクセス
curl http://localhost:8080/user/john
curl http://localhost:8080/user/john/send
$ http :8080/user/john
HTTP/1.1 200 OK
Content-Length: 10
Content-Type: text/plain; charset=utf-8
Date: Tue, 23 May 2023 06:33:17 GMT
Hello john
$ http :8080/user/john/send
HTTP/1.1 200 OK
Content-Length: 13
Content-Type: text/plain; charset=utf-8
Date: Tue, 23 May 2023 06:33:07 GMT
john is /send
確認したバージョン
$ go version
go version go1.20.3 linux/amd64