Gin 框架 -十二-: 更多 HTTP 服務使用
1. 靜態文件服務
1.1 代碼
package main
import "github.com/gin-gonic/gin"
func main() {
engine := gin.Default()
// 靜態圖片
engine.Static("/img","./public/img")
// 靜態文件
engine.StaticFile("/favicon.ico","./public/favicon.ico")
// 啓動服務
_ = engine.Run()
}
1.2 目錄結構
1.3 請求示例
# 請求圖片
http://127.0.0.1:8080/img/b.jpg
http://127.0.0.1:8080/img/c.jpg
# 請求文件
http://127.0.0.1:8080/favicon.ico
2. 重定向
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
engine := gin.Default()
// 重定向到外部(百度)
engine.GET("/baidu", func(context *gin.Context) {
context.Redirect(http.StatusMovedPermanently,"http://www.baidu.com")
})
// 路由重定向(第一種)
engine.GET("/route", func(context *gin.Context) {
context.Request.URL.Path = "/baidu"
engine.HandleContext(context)
})
// 路由重定向(第二種)
engine.GET("/pos", func(context *gin.Context) {
context.Redirect(http.StatusTemporaryRedirect,"/get")
})
engine.GET("/get", func(context *gin.Context) {
context.JSON(http.StatusOK,gin.H{"msg":"success"})
})
// 啓動服務
_ = engine.Run()
}
3. 修改 HTTP 配置
3.1 默認啓動 HTTP 服務
func main() {
engine := gin.Default()
// 註冊路由
engine.GET("/", func(context *gin.Context) {
// todo
})
// 啓動服務
_ = engine.Run()
}
3.2 啓動自定義 HTTP 服務
可以直接使用 http.ListenAndServe()
啓動服務,具體配置如下:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func main() {
engine := gin.Default()
// 自定義配置HTTP服務
serverConfig := &http.Server{
Addr: ":8080", //ip和端口號
Handler: engine,//調用的處理器,如爲nil會調用http.DefaultServeMux
ReadTimeout: time.Second,//計算從成功建立連接到request body(或header)完全被讀取的時間
WriteTimeout: time.Second,//計算從request body(或header)讀取結束到 response write結束的時間
MaxHeaderBytes: 1 << 20,//請求頭的最大長度,如爲0則用DefaultMaxHeaderBytes
}
// 註冊路由
engine.GET("/test", func(context *gin.Context) {
context.JSON(200,gin.H{"msg":"success"})
})
// 使用http.ListenAndServe啓動服務
_ = serverConfig.ListenAndServe()
}
4. 運行多個服務
package main
import (
"golang.org/x/sync/errgroup"
"log"
"net/http"
"github.com/gin-gonic/gin"
"time"
)
// 通過sync/errgroup來管理多個服務
var (
g errgroup.Group
)
// 服務1
func serverOne() http.Handler {
engine := gin.Default()
engine.GET("/server1", func(context *gin.Context) {
context.JSON(200,gin.H{"msg":"server1"})
})
return engine
}
// 服務2
func serverTwo() http.Handler {
engine := gin.Default()
engine.GET("/server2", func(context *gin.Context) {
context.JSON(200,gin.H{"msg":"server2"})
})
return engine
}
func main() {
// 服務1的配置信息
s1 := &http.Server{
Addr: ":8080",
Handler: serverOne(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
// 服務2的配置信息
s2 := &http.Server{
Addr: ":8081",
Handler: serverTwo(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
// 啓動服務
g.Go(func() error {
return s1.ListenAndServe()
})
g.Go(func() error {
return s2.ListenAndServe()
})
if err := g.Wait();err != nil {
log.Fatal(err)
}
}
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/UZnK0CMk4TDhySAloSpLWw