再介紹很多的go的http及資料庫的概念後,我們終於要進入我們的重頭戲了- Gin 琴酒
一起來喝一杯酒吧!
先來看看基本應用,並跟者複習以往的知識
套件基本應用: Go的DRY藝術 - 使用套件
step 1 先建立資料夾
mkdir gin-project-test
cd gin-project-test
step 2 建立 main.go
touch main.go
// main.go
package main
func main() {
}
step 3 建立module
go mod init com.example.ginproject           
step 4 裝gin
go get -u github.com/gin-gonic/gin
step 5 簡單使用gin
// main.go
package main
import (
	"net/http"
	"github.com/gin-gonic/gin"
)
func handlePin(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "pong",
	})
}
func main() {
	r := gin.Default()
	r.GET("/ping", handlePin)
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
step 6 run
go run main.go
此時可以看到
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
故,可以打開postman並輸入 http://localhost:8080/ping
就可以看到
{
    "message": "pong"
}
為什麼我們會在前幾天會先介紹 net/http 呢,因為 net/http 是go網頁的根基,
Day 21 Go X Http
| 功能/步驟 | Gin 框架 | net/http 套件 | 
|---|---|---|
| 引入套件 | import "github.com/gin-gonic/gin" | import "net/http" | 
| 初始化 | r := gin.Default() | mux := http.NewServeMux() | 
| 路由與處理函數 | r.GET("/ping", handlePin) | mux.HandleFunc("/ping", handlePing) | 
| 啟動伺服器 | r.Run() | http.ListenAndServe(":8080", mux) | 
| 處理函數的參數 | (c *gin.Context) | (w http.ResponseWriter, r *http.Request) | 
| 回應 JSON | c.JSON(http.StatusOK, gin.H{"message": "pong"}) | json.NewEncoder(w).Encode(map[string]string{"message": "pong"}) | 
下面是使用 net/http 的等效程式碼:
package main
import (
	"encoding/json"
	"net/http"
)
func handlePing(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]string{"message": "pong"})
}
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/ping", handlePing)
	http.ListenAndServe(":8080", mux)
}
這兩個範例的主要區別在於 Gin 提供了一個更高級和更方便的 API 來處理 HTTP 請求和回應。例如,你可以看到在處理 JSON 回應時,Gin 提供了一個非常簡單的方法 c.JSON(),而在 net/http 中,你需要手動設置內容類型、狀態碼,並使用 json.NewEncoder() 來編碼 JSON。
不論是使用 Gin 框架還是標準的 net/http 套件,基本的工作流程和結構是相似的
使用 Gin:
使用 net/http:
這裡有很多初學者的坑,如果還沒看過之前的文章也歡迎閱讀
gin.Context Day 3 Go怎麼傳值,先讀懂指標-2
:= Day 1 先搞清楚簡化到極致的變數宣告
前面鋪陳非常久的基本觀念,希望對讀者有助益