https

package
v0.0.0-...-f7071d6 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: MIT Imports: 20 Imported by: 0

README

项目概述

这是一个基于 Gin 框架构建的 HTTP API 服务器包,提供了完整的 Web 服务器功能,包括路由管理、中间件支持、CSRF 防护、日志记录等功能。

核心组件与功能

1. 服务器配置与启动

  • 使用 New() 函数创建服务器实例,支持多种配置选项
  • 主要配置项包括端口、TLS 设置、超时时间、keep-alive 等
  • 通过 Serve() 方法启动服务器,支持优雅关闭
server := https.New([]https.Option{
    https.Port(8080),
    https.TLSOpen(false),
})
server.Serve()

2. 路由与中间件管理

  • 支持注册路由和中间件
  • 中间件支持优先级设置,可以控制执行顺序
  • 内置了追踪(trace)和响应日志(responded)中间件

3. CSRF 防护机制

  • 提供 SetupVerifyCSRFToken 中间件实现 CSRF 防护
  • 验证来源(origin/referer)和 token 一致性
  • 支持客户端信息(DTV)验证和加密传输

4. 响应处理

  • 统一的响应格式管理
  • 支持多种响应类型(JSON、JSONP、HTML 等)
  • 自动集成错误处理和日志记录

5. 日志系统

  • 自动记录 HTTP 访问日志
  • 包含请求时间、状态码、路径、客户端 IP 等信息
  • 支持自定义日志字段和回调函数

6. 生命周期管理

  • 支持启动前、关闭后等各个生命周期阶段的回调函数
  • 提供初始化(init)和清理(defer)函数注册机制
  • 实现优雅停机(graceful shutdown)

主要特性

  1. 模块化设计: 功能分离清晰,易于扩展和维护
  2. 安全性: 内建 CSRF 防护机制
  3. 可观测性: 完善的日志记录和追踪支持
  4. 灵活性: 丰富的配置选项和扩展点
  5. 生产就绪: 支持 TLS、超时控制、优雅关闭等生产环境必需功能

使用场景

适用于构建 RESTful API 服务、Web 后台服务等需要 HTTP 接口的应用程序。

Documentation

Index

Constants

View Source
const (
	DidLength                 = 32
	CSRFTokenCookieName       = "X-Song-Csrf-Token"
	CSRFTokenHeaderName       = "X-Song-Csrf-Token"
	CSRFTokenExpireHeaderName = "X-Song-Csrf-Token-Expire"
	ClientRequestIdHeaderName = "X-Song-Request-Id"
	ClientDidHeaderName       = "X-Song-Did"
	ClientCTHeaderName        = "X-Song-Ct"
	ClientCVHeaderName        = "X-Song-Cv"
)
View Source
const (
	ClientInfoContextKey = "X-Song-Client-Info"
)

Variables

This section is empty.

Functions

func GetClientInfo

func GetClientInfo(ctx *gin.Context) (res *cljent.ClientInfo)

GetClientInfo 获取客户端信息

func Middleware

func Middleware(handle internal.MiddlewareHandleFunc, priorities ...int) internal.Middleware

Middleware 返回可自定义优先级的中间件 可自定义优先级,默认优先级999(priorities仅取第一个作为中间件优先级)

func New

func New(opts []Option) *internal.Server

New return a new HTTP Server @Param opts []Option the option of http server

func OnExit

func OnExit(fn func()) internal.Option

func OnResponded

func OnResponded(fn func(ctx context.Context, data *RequestResponseData)) internal.Option

OnResponded 请求响应完成后执行(请求日志已记录)

func OnShutdown

func OnShutdown(fn func()) internal.Option

func OnStart

func OnStart(fn func()) internal.Option

func OnStartFail

func OnStartFail(fn func(error)) internal.Option

func Response

func Response(ctx *gin.Context, data any, err error, opts ...internal.ResponseOption)

Response 请求响应。 @Param data any 响应数据 @param err error 请求错误。成功时,nil或者级别低于warning的错误;失败时,不为nil且级别高于warning的错误 @Param opts []inetrnal.ResponseOption 自定义响应选项,可覆盖默认根据err和data设定的选项

func ResponseError

func ResponseError(ctx *gin.Context, err error, opts ...internal.ResponseOption)

ResponseError 请求失败(发生错误或异常)时的响应 @param err error 请求错误。成功时,nil或者级别低于warning的错误;失败时,不为nil且级别高于warning的错误 @Param opts []inetrnal.ResponseOption 自定义响应选项,可覆盖默认根据data设定的选项

func ResponseOptionCode

func ResponseOptionCode(code int64) internal.ResponseOption

func ResponseOptionData

func ResponseOptionData(data any) internal.ResponseOption

func ResponseOptionMsg

func ResponseOptionMsg(msg string) internal.ResponseOption

func ResponseOptionTypeAsciiJSON

func ResponseOptionTypeAsciiJSON() internal.ResponseOption

func ResponseOptionTypeHTML

func ResponseOptionTypeHTML() internal.ResponseOption

func ResponseOptionTypeJSON

func ResponseOptionTypeJSON() internal.ResponseOption

func ResponseOptionTypeJSONP

func ResponseOptionTypeJSONP() internal.ResponseOption

func ResponseOptionTypeStream

func ResponseOptionTypeStream() internal.ResponseOption

func ResponseSuccess

func ResponseSuccess(ctx *gin.Context, data any, opts ...internal.ResponseOption)

ResponseSuccess 请求成功时的响应 @param data any 响应数据 @Param opts []inetrnal.ResponseOption 自定义响应选项,可覆盖默认根据data设定的选项

func ResponseWithStatus

func ResponseWithStatus(ctx *gin.Context, status int, opts ...internal.ResponseOption)

ResponseWithStatus 自定义http status响应,默认JSON格式

func SetupVerifyCSRFToken

func SetupVerifyCSRFToken(eng *gin.Engine, opts ...CSRFOption) gin.HandlerFunc

SetupVerifyCSRFToken 设置&校验CSRF-Token

func WrapEngineMiddleware

func WrapEngineMiddleware(handle gin.HandlerFunc, priorities ...int) internal.Middleware

Types

type CSRFConfig

type CSRFConfig struct {
	Crypter            *crypto.AESGCMCrypter
	Verify             func(ctx *gin.Context) bool
	Erlog              erlogs.ErLogInterface
	Methods            []string
	Origins            []string
	RefererPrefixs     []string
	CookieKey          string
	HeaderKey          string
	HeaderExpireKey    string
	HeaderRequestIdKey string
	HeaderDidKey       string
	HeaderCTKey        string
	HeaderCVKey        string
	Path               string
	Domain             string
	Secure             bool
	HttpOnly           bool
	MaxAge             int
	SameSite           int64
}

type CSRFOption

type CSRFOption struct {
	Apply func(c *CSRFConfig)
}

func CSRFOptionCookieKey

func CSRFOptionCookieKey(s string) CSRFOption

func CSRFOptionCookiePath

func CSRFOptionCookiePath(s string) CSRFOption

func CSRFOptionCrypter

func CSRFOptionCrypter(crypter *crypto.AESGCMCrypter) CSRFOption

func CSRFOptionDomain

func CSRFOptionDomain(s string) CSRFOption

func CSRFOptionErLog

func CSRFOptionErLog(e erlogs.ErLogInterface) CSRFOption

func CSRFOptionHeaderCTKey

func CSRFOptionHeaderCTKey(s string) CSRFOption

func CSRFOptionHeaderCVKey

func CSRFOptionHeaderCVKey(s string) CSRFOption

func CSRFOptionHeaderDidKey

func CSRFOptionHeaderDidKey(s string) CSRFOption

func CSRFOptionHeaderExpireKey

func CSRFOptionHeaderExpireKey(s string) CSRFOption

func CSRFOptionHeaderKey

func CSRFOptionHeaderKey(s string) CSRFOption

func CSRFOptionHeaderRequestIdKey

func CSRFOptionHeaderRequestIdKey(s string) CSRFOption

func CSRFOptionMaxAge

func CSRFOptionMaxAge(i int) CSRFOption

func CSRFOptionMethods

func CSRFOptionMethods(ss ...string) CSRFOption

func CSRFOptionOrigins

func CSRFOptionOrigins(ss ...string) CSRFOption

func CSRFOptionRefererPrefixs

func CSRFOptionRefererPrefixs(ss ...string) CSRFOption

func CSRFOptionVerify

func CSRFOptionVerify(f func(ctx *gin.Context) bool) CSRFOption

type ContextResponse

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

func WithContext

func WithContext(ctx *gin.Context) *ContextResponse

func (*ContextResponse) Response

func (r *ContextResponse) Response(data any, err error, opts ...internal.ResponseOption)

Response 请求响应。 @Param data any 响应数据 @param err error 请求错误。成功时,nil或者级别低于warning的错误;失败时,不为nil且级别高于warning的错误 @Param opts []inetrnal.ResponseOption 自定义响应选项,可覆盖默认根据err和data设定的选项

func (*ContextResponse) ResponseError

func (r *ContextResponse) ResponseError(err error, opts ...internal.ResponseOption)

ResponseError 请求失败(发生错误或异常)时的响应 @param err error 请求错误。成功时,nil或者级别低于warning的错误;失败时,不为nil且级别高于warning的错误 @Param opts []inetrnal.ResponseOption 自定义响应选项,可覆盖默认根据data设定的选项

func (*ContextResponse) ResponseSuccess

func (r *ContextResponse) ResponseSuccess(data any, opts ...internal.ResponseOption)

ResponseSuccess 请求成功时的响应 @param data any 响应数据 @Param opts []inetrnal.ResponseOption 自定义响应选项,可覆盖默认根据data设定的选项

func (*ContextResponse) ResponseWithStatus

func (r *ContextResponse) ResponseWithStatus(status int, opts ...internal.ResponseOption)

ResponseWithStatus 自定义http status响应,默认JSON格式

type Option

type Option = internal.Option

func Defers

func Defers(defers ...internal.Defer) Option

func HammerTime

func HammerTime(s string) Option

func IdleTimeout

func IdleTimeout(s string) Option

func Inits

func Inits(inits ...internal.Init) Option

func KeepAlive

func KeepAlive(b bool) Option

func LoggerHeaderKeys

func LoggerHeaderKeys(keys ...string) Option

func Middlewares

func Middlewares(middlewares ...internal.Middleware) Option

Middlewares 注册中间件

func Port

func Port(i int) Option

Port 设置http server端口

func ReadHeaderTimeout

func ReadHeaderTimeout(s string) Option

func ReadTimeout

func ReadTimeout(s string) Option

func Routes

func Routes(routes ...internal.Route) Option

func TLSKeyCert

func TLSKeyCert(s string) Option

TLSKeyCert 设置https TLS cert file path

func TLSKeyFile

func TLSKeyFile(s string) Option

TLSKeyFile 设置https TLS key file path

func TLSOpen

func TLSOpen(b bool) Option

TLSOpen 是否开启https

func WriteTimeout

func WriteTimeout(s string) Option

type PriorityMiddleware

type PriorityMiddleware = internal.Middleware

type RequestResponseData

type RequestResponseData = internal.RequestResponseData

type Route

type Route = internal.Route

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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