直接找 Go 的 Framework (本身 Go 就內鍵了 Web Service 了)

找了目前星星數較多的 gin 來測試

只要幾個步驟就好了

下載 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 | 404 | 0s | ::1 | GET  /robots.txt
[GIN] 2020/01/31 - 14:30:24 | 404 | 0s | ::1 | GET  /
[GIN] 2020/01/31 - 14:30:24 | 404 | 0s | ::1 | GET  /favicon.ico
[GIN] 2020/01/31 - 14:30:30 | 404 | 0s | ::1 | GET  /

綁定服務 (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

Related posts 相關文章
安裝 golang
More...
GO語言將成為Linux內建開發語言
More...

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。