同样可以在gin 框架上包装一个自己的http server,例如像我下面这样封装,本质上是用gin.Engine 替代了原生http框架的http.ServeMux
package main
import (
"context"
"github.com/gin-gonic/gin"
"net/http"
)
type HttpServer struct {
mux *gin.Engine
*http.Server
}
func NewHttpServer(addr string) *HttpServer {
mux := gin.New()
server := &http.Server{Addr: addr, Handler: mux}
s := &HttpServer{mux: mux, Server: server}
s.mux.GET("/hello", func(c *gin.Context) {
c.Writer.Write([]byte("OK"))
})
return s
}
func (h *HttpServer) Start() {
go func() {
err := h.ListenAndServe()
if err != nil {
panic(err)
}
}()
}
func (h *HttpServer) Close() {
h.Shutdown(context.TODO())
}
func main() {
ch := make(chan int)
h := NewHttpServer(":8080")
h.Start()
<-ch
}