直接找 Go 的 Framework (本身 Go 就內鍵了 Web Service 了)
只要幾個步驟就好了
下載 gin (要 import 它)
go get -u -v github.com/gin-gonic/gin
編輯程式 vi gin.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() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") //r.Run(":8181") // 預設為 8080 port,如果已有服務在跑,可以這麼換 port }
啟動程式
go run gin.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] Environment variable PORT is undefined. Using port :8080 by default [GIN-debug] Listening and serving HTTP on :8080 [GIN] 2020/01/31 - 14:30:24 |[90;43m 404 [0m| 0s | ::1 |[97;44m GET [0m /robots.txt [GIN] 2020/01/31 - 14:30:24 |[90;43m 404 [0m| 0s | ::1 |[97;44m GET [0m / [GIN] 2020/01/31 - 14:30:24 |[90;43m 404 [0m| 0s | ::1 |[97;44m GET [0m /favicon.ico [GIN] 2020/01/31 - 14:30:30 |[90;43m 404 [0m| 0s | ::1 |[97;44m GET [0m /
綁定服務 (Listen Port)
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME gin 198954 root 3u IPv6 21922906 0t0 TCP *:8080 (LISTEN)
瀏覽 http://localhost:8080/ping 會回應
{message: "pong"}
單純 http://localhost:8080/ 就會 404 page not found
留言