1 Star 1 Fork 0

ysc/yu

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server_gin.go 4.55 KB
一键复制 编辑 原始数据 按行查看 历史
ysc 提交于 2022-07-30 22:26 . update echo gin server
package yu
import (
"compress/gzip"
"context"
"encoding/json"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// GinServer 包含gin的http server
type GinServer struct {
Name string
Server *http.Server
Engine *gin.Engine
}
// NewGinServer 创建GinServer
func NewGinServer(name, addr, mod string) *GinServer {
gin.SetMode(mod)
gs := &GinServer{
Name: name,
Server: &http.Server{Addr: addr},
Engine: gin.New(),
}
gs.Engine.Use(gin.Recovery(), gin.ErrorLogger())
gs.Server.Handler = gs.Engine
return gs
}
// OnStart 实现ServerInterface接口
func (s *GinServer) OnStart() bool {
Logf("%s gin server start at %s", s.Info(), s.Server.Addr)
if err := s.Server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
LogErr(err, "ListenAndServe")
}
return true
}
// OnStop 实现ServerInterface接口
func (s *GinServer) OnStop() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := s.Server.Shutdown(ctx); err != nil {
LogErr(err, "Shutdown")
}
}
// Info 实现ServerInterface接口
func (s *GinServer) Info() string {
return s.Name
}
// Health 健康检查接口,需要的话设置
func (s *GinServer) Health() {
s.Engine.GET("health", func(c *gin.Context) { s.JsonOK(c, "yes") })
}
// Promethous 启动Promethous监听
func (s *GinServer) Promethous(name, pass string) {
InitPrometheus("YU", s.Name)
s.Engine.GET("metrics", s.BasicAuth(name, pass), s.PromethousHandler())
}
// Group 创建gin.RouterGroup
func (s *GinServer) Group(path string, handlers ...gin.HandlerFunc) *gin.RouterGroup {
return s.Engine.Group(path, handlers...)
}
// JSON 发送JSON
func (s *GinServer) JSON(c *gin.Context, data any) {
c.Writer.Header().Set("Content-Type", "application/json;charset=utf-8")
if err := json.NewEncoder(c.Writer).Encode(data); err != nil {
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
return
}
}
// GzipJSON gzip压缩发送JSON
func (s *GinServer) GzipJSON(c *gin.Context, data any) {
c.Writer.Header().Set("Content-Type", "application/json;charset=utf-8")
c.Writer.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(c.Writer)
defer gz.Close()
if err := json.NewEncoder(gz).Encode(data); err != nil {
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
return
}
}
// JsonOK 反馈OK
func (s *GinServer) JsonOK(c *gin.Context, data any) {
s.JSON(c, RespOK(data))
}
// JsonErr 反馈Err
func (s *GinServer) JsonErr(c *gin.Context, err error) {
s.JSON(c, RespErr(err))
}
// JsonMsg 反馈发生错误信息
func (s *GinServer) JsonMsg(c *gin.Context, msg string) {
s.JSON(c, RespMsg(CodeErr, msg))
}
// NoCache 设置请求头为无缓存
func (s *GinServer) NoCache() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate")
c.Next()
}
}
// BasicAuth 设置BasicAuth认证
func (s *GinServer) BasicAuth(username, password string) gin.HandlerFunc {
return func(c *gin.Context) {
if u, p, ok := c.Request.BasicAuth(); ok && u == username && p == password {
c.Next()
return
}
c.Writer.Header().Set("WWW-Authenticate", `Basic realm="Authorization Required"`)
http.Error(c.Writer, "unauthorized", http.StatusUnauthorized)
log.Println("[ERR] - unauthorized")
c.Abort()
}
}
// LogControl 控制gin是否输出log
func (s *GinServer) LogControl(trace bool, skip []string) gin.HandlerFunc {
logger := gin.LoggerWithConfig(gin.LoggerConfig{SkipPaths: skip})
return func(c *gin.Context) {
if !trace {
c.Next()
return
}
logger(c)
}
}
// CORS 设置跨域
func (s *GinServer) CORS(acceptedOrigin, AcceptedMethods, AcceptedHeaders, MaxAge string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", acceptedOrigin)
if AcceptedMethods != "" {
c.Writer.Header().Set("Access-Control-Allow-Methods", AcceptedMethods)
}
if AcceptedHeaders != "" {
c.Writer.Header().Set("Access-Control-Allow-Headers", AcceptedHeaders)
}
if MaxAge != "" {
c.Writer.Header().Set("Access-Control-Max-Age", MaxAge)
}
if c.Request.Method != "OPTIONS" {
c.Next()
}
}
}
// PromethousHandler 启动promethous http监听
func (s *GinServer) PromethousHandler() gin.HandlerFunc {
return func(c *gin.Context) {
promhttp.Handler().ServeHTTP(c.Writer, c.Request)
}
}
// PromeMetrics prometheus metrics 中间件
func (s *GinServer) PromeMetrics() gin.HandlerFunc {
return func(c *gin.Context) {
defer PromeTrace(c.Request.URL.Path)()
c.Next()
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/yscsky/yu.git
git@gitee.com:yscsky/yu.git
yscsky
yu
yu
v0.2.0

搜索帮助