[root@zsx src]# mkdir ginquickstart
[root@zsx src]# cd ginquickstart/
[root@zsx ginquickstart]# go mod init ginquickstart
go: creating new go.mod: module ginquickstart
[root@zsx ginquickstart]# curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go
[root@zsx ginquickstart]# go mod tidy
// 根据实际情况修改启动端口,这里修改为8085
// 修改main.go
func main() {
r := setupRouter()
// Listen and Server in 0.0.0.0:8080
r.Run(":8085")
}
[root@zsx ginquickstart]# go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[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 /ping --> main.setupRouter.func1 (3 handlers)
[GIN-debug] GET /user/:name --> main.setupRouter.func2 (3 handlers)
[GIN-debug] POST /admin --> main.setupRouter.func3 (4 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8085
[root@zsx ~]# curl http://localhost:8085/ping
pong
[root@zsx ~]# curl http://localhost:8085/user/tom
{"status":"no value","user":"tom"}
[root@zsx ~]# curl -X POST http://localhost:8085/admin -H 'authorization: Basic Zm9vOmJhcg==' -H 'content-type: application/json' -d '{"value":"bar"}'
{"status":"ok"}
停掉 main.go
,编写一个文件 example.go
:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run(":8085") // 监听并在 0.0.0.0:8085 上启动服务
}
重新启动项目:
[root@zsx ginquickstart]# go run example.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[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 /ping --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8085
访问:
[root@zsx ~]# curl http://localhost:8085/ping
{"message":"pong"}