一、GIN概述
官方:Gin 是一個用 Go (Golang) 編寫的 web 框架。 它是一個類似於 martini 但擁有更好效能的 API 框架,由於 httprouter,速度提高了近 40 倍
二、Gin框架搭建
建立你的專案根目錄並進入,如為 go-gin-demo
執行命令安裝 gin
go get -u github.com/gin-gonic/gin
拷貝一個初始模板到你的專案裡
curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go
go run main.go
報錯 模組找不到main.go:6:2: cannot find module providing package github.com/gin-gonic/gin: working directory is not part of a module
執行連個命令修正
go-gin-demo 貌似可以隨意取個人喜歡和專案名一樣
或者可以改成類似github.com/gin-gonic/gin 的路徑go mod init go-gin-demo go mod edit -require github.com/gin-gonic/gin@latest
執行 go run main.go 正常啟動 預設8080 如果佔用需要改為其他埠本人9090
[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 :9090
測試響應,新建一個視窗
curl 127.0.0.1:9090/ping #響應 pong curl 127.0.0.1:9090/user/:peter #響應 {"status":"no value","user":":peter"}
至此,Gin 框架已經搭建好了!
本作品採用《CC 協議》,轉載必須註明作者和本文連結