Help us shape the future of Go! Take the 2026 Go Developer Survey

httpserver

package
v1.1.45 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 18, 2024 License: GPL-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const HealthUrl = "/health"
View Source
const RequestIdName = "RequestId"

Variables

View Source
var EmptyHandler = new(emptyHandler)
View Source
var GlobalMiddlewareAddRequestId = func(requestIdField string) Middleware {
	return func(ctx *Ctx, next func(*Ctx)) {

		ctx.SetRequestId(utils.NewRequestId())

		next(ctx)
	}
}

GlobalMiddlewareAddRequestId 添加requestId

View Source
var GlobalMiddlewareCorsMiddleware = func(domainWhites []string) Middleware {
	return func(ctx *Ctx, next func(*Ctx)) {
		allow := false

		if origin := ctx.request.Header.Get("Origin"); origin != "" {
			if domainWhites == nil {
				allow = true
			} else {
				for _, white := range domainWhites {
					if white == origin {
						allow = true
						break
					}
				}
			}
			if allow {
				ctx.writer.Header().Set("Access-Control-Allow-Origin", origin)
			}
		}
		ctx.writer.Header().Set("Access-Control-Allow-Credentials", "true")
		ctx.writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		ctx.writer.Header().Set("Access-Control-Allow-Headers", "Content-type,Authorization,x-requested-with,Request-Service")

		next(ctx)
	}
}

GlobalMiddlewareCorsMiddleware 跨域资源请求

View Source
var GlobalMiddlewareQPSLimiter = func(r rate.Limit, b int) Middleware {
	limiter := rate.NewLimiter(r, b)
	return func(ctx *Ctx, next func(ctx *Ctx)) {
		if !limiter.Allow() {
			ctx.writer.WriteHeader(http.StatusNoContent)
			return
		}

		next(ctx)
	}
}

GlobalMiddlewareQPSLimiter qps限流

View Source
var WithOpsAcceptOptions = func(accept bool) ServerOps {
	return func(server *HttpServer) {
		server.config.acceptOptions = accept
	}
}
View Source
var WithOpsHealthCheck = func(add bool, health string) ServerOps {
	return func(server *HttpServer) {
		server.config.healthCheck = add
		server.config.healthPath = health
	}
}
View Source
var WithOpsRequestId = func(requestIdField string) ServerOps {
	return func(server *HttpServer) {
		server.config.requestId = requestIdField != ""
		server.config.requestIdField = requestIdField
	}
}

Functions

func EmptyHandle added in v1.1.35

func EmptyHandle(ctx *Ctx)

EmptyHandle 空处理

func GinHandle added in v1.1.35

func GinHandle(f func(ctx *Ctx)) func(c *gin.Context)

GinHandle 支持转换为gin框架的hanler

func GinHealthF added in v1.1.42

func GinHealthF(ctx *gin.Context)

GinHealthF 健康检查处理方法

func HealthF added in v1.1.42

func HealthF(ctx *Ctx)

HealthF 健康检查func

func PProfHandler added in v1.1.42

func PProfHandler(next http.HandlerFunc) http.HandlerFunc

func PProfRegRouter added in v1.1.35

func PProfRegRouter(ro interface{})

PProfRegRouter pprof-注册路由 查看内存占用分析: go tool pprof -alloc_space "127.0.0.1:8888/debug/pprof/heap?seconds=30"

Types

type Ctx

type Ctx struct {
	IHttpResponse
	// contains filtered or unexported fields
}

func NewCtx

func NewCtx(writer http.ResponseWriter, request *http.Request) *Ctx

func (*Ctx) Authorization added in v1.1.7

func (ctx *Ctx) Authorization() string

func (*Ctx) Context

func (ctx *Ctx) Context() context.Context

func (*Ctx) Form

func (ctx *Ctx) Form() url.Values

func (*Ctx) FormJson

func (ctx *Ctx) FormJson(stc interface{}) error

func (*Ctx) FormMultipart added in v1.1.9

func (ctx *Ctx) FormMultipart() (map[string][]string, map[string][]*multipart.FileHeader, error)

func (*Ctx) Gin added in v1.1.35

func (ctx *Ctx) Gin() *gin.Context

func (*Ctx) Header

func (ctx *Ctx) Header() http.Header

func (*Ctx) Param

func (ctx *Ctx) Param(name string) string

func (*Ctx) Request

func (ctx *Ctx) Request() *http.Request

func (*Ctx) Reset added in v1.1.35

func (ctx *Ctx) Reset(writer http.ResponseWriter, request *http.Request)

func (*Ctx) SetParam added in v1.1.43

func (ctx *Ctx) SetParam(kv ...string)

func (*Ctx) SetResponseHandler

func (ctx *Ctx) SetResponseHandler(response IHttpResponse)

func (*Ctx) Value

func (ctx *Ctx) Value(key interface{}) interface{}

func (*Ctx) WithValue

func (ctx *Ctx) WithValue(key, val interface{})

func (*Ctx) Write

func (ctx *Ctx) Write(resp []byte) (int, error)

func (*Ctx) WriteHeader

func (ctx *Ctx) WriteHeader(code int)

func (*Ctx) WriteStr

func (ctx *Ctx) WriteStr(resp string) (int, error)

func (*Ctx) Writer

func (ctx *Ctx) Writer() http.ResponseWriter

type HttpForwardHandler

type HttpForwardHandler struct {
	// contains filtered or unexported fields
}

转发http的handler

func NewHttpForwardHandler

func NewHttpForwardHandler(forward string, timeout time.Duration) *HttpForwardHandler

func (*HttpForwardHandler) AddForwardRule

func (h *HttpForwardHandler) AddForwardRule(rule map[string]string)

func (*HttpForwardHandler) ServeHTTP

func (h *HttpForwardHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type HttpResponse

type HttpResponse struct {
	// contains filtered or unexported fields
}

func (*HttpResponse) GetCode

func (resp *HttpResponse) GetCode() int64

func (*HttpResponse) GetData

func (resp *HttpResponse) GetData() interface{}

func (*HttpResponse) GetMsg

func (resp *HttpResponse) GetMsg() string

func (*HttpResponse) GetRequestId added in v1.1.8

func (resp *HttpResponse) GetRequestId() string

func (*HttpResponse) Response

func (resp *HttpResponse) Response(params ...interface{})

func (*HttpResponse) SetCode

func (resp *HttpResponse) SetCode(code int64)

func (*HttpResponse) SetData

func (resp *HttpResponse) SetData(data interface{})

func (*HttpResponse) SetMsg

func (resp *HttpResponse) SetMsg(msg string)

func (*HttpResponse) SetRequestId added in v1.1.8

func (resp *HttpResponse) SetRequestId(requestId string)

type HttpResponseData

type HttpResponseData struct {
	Code      int64       `json:"code"`
	Data      interface{} `json:"data"`
	Msg       string      `json:"message"`
	RequestId string      `json:"requestId"`
}

func (*HttpResponseData) Encode

func (d *HttpResponseData) Encode() []byte

type HttpRouteFunc

type HttpRouteFunc = func(ctx *Ctx)

type HttpServer

type HttpServer struct {
	log.InvokeLog
	// contains filtered or unexported fields
}

func NewHttpServer

func NewHttpServer(name string, addr string, ops ...ServerOps) (*HttpServer, error)

func (*HttpServer) Name

func (s *HttpServer) Name() string

func (*HttpServer) RouteAll added in v1.1.36

func (s *HttpServer) RouteAll(path string, f HttpRouteFunc, middleware []Middleware) *HttpServer

func (*HttpServer) RouteDelete

func (s *HttpServer) RouteDelete(path string, f HttpRouteFunc, middleware []Middleware) *HttpServer

func (*HttpServer) RouteFiles

func (s *HttpServer) RouteFiles(path string, f http.FileSystem) *HttpServer

func (*HttpServer) RouteFromGin added in v1.1.42

func (s *HttpServer) RouteFromGin(r *gin.Engine) *HttpServer

RouteFromGin 从gin进行路由配置

func (*HttpServer) RouteGet

func (s *HttpServer) RouteGet(path string, f HttpRouteFunc, middleware []Middleware) *HttpServer

func (*HttpServer) RouteHandler

func (s *HttpServer) RouteHandler(method, path string, f http.Handler, middleware []Middleware) *HttpServer

func (*HttpServer) RouteOptions

func (s *HttpServer) RouteOptions(path string, f HttpRouteFunc, middleware []Middleware) *HttpServer

func (*HttpServer) RoutePost

func (s *HttpServer) RoutePost(path string, f HttpRouteFunc, middleware []Middleware) *HttpServer

func (*HttpServer) RoutePut

func (s *HttpServer) RoutePut(path string, f HttpRouteFunc, middleware []Middleware) *HttpServer

func (*HttpServer) RouteToGin added in v1.1.42

func (s *HttpServer) RouteToGin(engine *gin.Engine) *HttpServer

RouteToGin 路由配置copy至gin

func (*HttpServer) Router

func (s *HttpServer) Router() *httprouter.Router

func (*HttpServer) Run

func (s *HttpServer) Run() error

func (*HttpServer) Stop

func (s *HttpServer) Stop() error

type IHttpResponse

type IHttpResponse interface {
	SetCode(code int64)
	SetMsg(msg string)
	SetData(data interface{})
	SetRequestId(string)

	GetCode() int64
	GetMsg() string
	GetData() interface{}
	GetRequestId() string

	Response(...interface{})
}

func NewHttpResponse

func NewHttpResponse(writer http.ResponseWriter) IHttpResponse

type Middleware

type Middleware func(ctx *Ctx, next func(ctx *Ctx))
var DefaultResponseMiddleware Middleware = func(ctx *Ctx, next func(*Ctx)) {
	ctx.SetResponseHandler(NewHttpResponse(ctx.Writer()))
	next(ctx)
}

DefaultResponseMiddleware response

var GlobalMiddlewareOptionRequest Middleware = func(ctx *Ctx, next func(*Ctx)) {
	if ctx.request.Method == "OPTIONS" {
		ctx.writer.WriteHeader(http.StatusNoContent)
		return
	}
	next(ctx)
}

GlobalMiddlewareOptionRequest OPTION请求过滤

var GlobalMiddlewarePanic Middleware = func(ctx *Ctx, next func(*Ctx)) {
	defer func() {
		if err := recover(); err != nil {
			debug.PrintStack()
			fmt.Printf("panic:%s\n", err)
			ctx.WriteHeader(http.StatusInternalServerError)
			ctx.SetMsg(fmt.Sprintf("panic:%s", err))
			ctx.Response()
			return
		}
	}()
	next(ctx)
}

GlobalMiddlewarePanic panic处理

type Router

type Router struct {
	Path         string
	Method       string
	RouteHandler HttpRouteFunc
	Middleware   []Middleware

	HttpHandler http.Handler
}

type ServerConfig

type ServerConfig struct {
	// contains filtered or unexported fields
}

type ServerOps

type ServerOps = func(*HttpServer)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL