ginKit

package
v3.0.81 Latest Latest
Warning

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

Go to latest
Published: May 23, 2024 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Overview

Package ginKit

TODO: 响应文件或文件流,目前一律用no-cache,在此种情况下会有问题:一个网址对应复数的图片(可以参考Web.docx).

Index

Constants

This section is empty.

Variables

View Source
var NewGzipMiddleware func(level int, options ...gzip.Option) gin.HandlerFunc = gzip.Gzip

NewGzipMiddleware

缺陷: github.com/gin-contrib/gzip v1.0.0 不支持设置minContentLength.

PS: (1) 涉及多个服务(请求转发)的场景下,(a) 最外层的务使用gzip压缩;

(b) 内层的服务不使用gzip压缩.

(2) Gzip通常不建议用来压缩图片.

View Source
var (
	RequestTooLargeError = errorKit.Newf("HTTP request too large")
)

Functions

func AddResponseHeader

func AddResponseHeader(ctx *gin.Context, key, value string)

AddResponseHeader (响应头)

func BindHandlersToRoute

func BindHandlersToRoute(group gin.IRoutes, route string, methods []string, handlers ...gin.HandlerFunc)

BindHandlersToRoute

适用场景: 1个路由,n个Method.

@param methods nil => 接收所有类型method的请求. e.g. http.MethodGet、http.MethodPost @param handlers 其中的元素不能为nil!!!

func BindHandlersToRoutes

func BindHandlersToRoutes(group gin.IRoutes, routes []string, methods []string, handlers ...gin.HandlerFunc)

BindHandlersToRoutes 将相同的多个处理器,注册到多个路由.

func DefaultFavicon

func DefaultFavicon(engine *gin.Engine)

func DefaultNoMethod

func DefaultNoMethod(engine *gin.Engine)

func DefaultNoRouteHtml

func DefaultNoRouteHtml(engine *gin.Engine) error

DefaultNoRouteHtml 使用自带的404页面.

func DelResponseHeader

func DelResponseHeader(ctx *gin.Context, key string)

DelResponseHeader (响应头)删除响应头.

func GetClientIp

func GetClientIp(ctx *gin.Context) string

GetClientIp 获取客户端IP地址(客户端的真实IP地址,但结果并不总是可靠的).

PS: (1) ClientIP 方法首先检查 HTTP 请求头中的 X-Forwarded-For 和 X-Real-Ip 字段。如果这些字段存在,则 ClientIP() 会返回其中的值作为客户端的真实 IP 地址。

如果这些字段不存在,则 ClientIP() 会返回与 RemoteIP() 相同的结果。

(2) ctx.ClientIP() VS ctx.RemoteIP():

(2.1) 当客户端直接连接到服务器时,RemoteIP 和 ClientIP 方法返回的结果相同;
(2.2) 当客户端通过代理服务器连接时,	(a) RemoteIP() 返回代理服务器的 IP 地址;
						 		(b) ClientIP() 尝试从 HTTP 请求头中获取客户端的真实 IP 地址.

(3) 想要更加精确地获取客户端的真实 IP 地址,可以,通过 Engine.TrustedPlatform 和 Engine.SetTrustedProxies(),参考同目录下的 _info.md.

总结:

在使用Gin框架时,如果您希望获取客户端的真实 IP 地址,应该使用 ClientIP() 而不是 RemoteIP()。但是,请注意,由于客户端可以伪造 HTTP 请求头中的 X-Forwarded-For 和 X-Real-Ip 字段,因此 ClientIP 方法返回的结果并不总是可靠的。在某些情况下,您可能需要使用其他方法来验证客户端的真实 IP 地址。

func GetRemoteIP

func GetRemoteIP(ctx *gin.Context) string

GetRemoteIP 获取客户端IP地址(客户端的远程IP地址).

e.g. 当客户端通过代理服务器连接时,RemoteIP() 返回代理服务器的 IP 地址

func GetRequestHeader

func GetRequestHeader(ctx *gin.Context, key string) string

GetRequestHeader (请求头)

func GetUserAgent

func GetUserAgent(ctx *gin.Context) string

GetUserAgent (请求头)获取http请求头中"User Agent"的值.

参考: https://www.sunzhongwei.com/golang-gin-for-user-agent-in-http-request-header-value

e.g. Chrome浏览器: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Safari浏览器: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15

func LoadHTMLFiles

func LoadHTMLFiles(engine *gin.Engine, filePaths ...string)

LoadHTMLFiles 加载(多个)html文件.

PS: 搭配 gin.Context.HTML() 使用.

func LoadHTMLGlob

func LoadHTMLGlob(engine *gin.Engine, pattern string)

LoadHTMLGlob

PS: 搭配 gin.Context.HTML() 使用.

func MustSetUp

func MustSetUp(config *Config, businessLogic func(engine *gin.Engine) error, options ...GinOption)

func NewCorsMiddleware

func NewCorsMiddleware(origins []string) gin.HandlerFunc

NewCorsMiddleware 新建一个cors中间件(自带对 OPTIONS请求 的处理).

「Go框架」 Gin 怎么实现允许前端跨域请求?

https://mp.weixin.qq.com/s/2eJUJKJ3Xu5jOYXAfknqtA

@param origins (0) 可以为nil

(1) origin白名单
(2) 支持wildcard(*)
(3) len(origins) == 0,则通配(请求的origin是什么就允许什么)

e.g.

传参: []string{"https://*.github.com", "https://api.*", "http://*", "https://facebook.com", "*.golang.org"}

func NewEngine

func NewEngine() *gin.Engine

func NewGzipMiddleware1 deprecated added in v3.0.41

func NewGzipMiddleware1(level int, minContentLength int64) gin.HandlerFunc

NewGzipMiddleware1

Deprecated: github.com/nanmu42/gzip 可能会截断长json(github.com/gin-contrib/gzip 则不会),导致前端解析失败.

PS: (1) 涉及多个服务(请求转发)的场景下,(a) 最外层的务使用gzip压缩;

(b) 内层的服务不使用gzip压缩.

(2) Gzip通常不建议用来压缩图片.

@param level 压缩级别 @param minContentLength (1) 触发gzip的最小内容长度

(2) 单位: byte
(3) 必须 > 0

func NewGzipMiddleware2 added in v3.0.73

func NewGzipMiddleware2(level, minLength int) (middleware gin.HandlerFunc, err error)

NewGzipMiddleware2

@param minLength 等效于 Nginx 的 gzip_min_length 配置项

func NewOptionsMiddleware deprecated

func NewOptionsMiddleware() gin.HandlerFunc

NewOptionsMiddleware

Deprecated: NewCorsMiddleware 已经自带对 OPTIONS请求 的处理了.

PS: (1) 就算 NoRoute || NoMethod,也会走到中间件.

func NewSizeLimiterMiddleware

func NewSizeLimiterMiddleware(limit int64) (gin.HandlerFunc, error)

NewSizeLimiterMiddleware 参考了echo中的 middleware.BodyLimit()

@param limit 	(1) 单位: MiB
				(2) 必须 > 0

func NewSizeLimiterMiddleware1

func NewSizeLimiterMiddleware1(limit int64) gin.HandlerFunc

NewSizeLimiterMiddleware1

gin-contrib/size

https://github.com/gin-contrib/size

func NewStaticMiddleware added in v3.0.42

func NewStaticMiddleware(urlPrefix string, dirPath string, indexes bool) (gin.HandlerFunc, error)

NewStaticMiddleware

PS: (1) 可以与已绑定的路由冲突且优先级高; (2) 适用场景: 静态资源与已绑定路由冲突的情况(如果不冲突的话,建议使用 StaticDir).

@param root 目录路径 @param indexes 是否列出目录信息(安全考虑的话,建议传参false)

func NewStaticMiddlewareWithEmbedFolder added in v3.0.42

func NewStaticMiddlewareWithEmbedFolder(urlPrefix string, fsEmbed embed.FS, targetPath string) gin.HandlerFunc

func ObtainBoolParam

func ObtainBoolParam(ctx *gin.Context, key string) (bool, error)

func ObtainFloat32Param

func ObtainFloat32Param(ctx *gin.Context, key string) (float32, error)

func ObtainFloat64Param

func ObtainFloat64Param(ctx *gin.Context, key string) (float64, error)

func ObtainFormFileContent

func ObtainFormFileContent(ctx *gin.Context, key string) ([]byte, string, error)

ObtainFormFileContent form请求,根据 传参key 获取文件的字节流.(单文件上传)

@return 文件内容 + 文件名 + 错误

func ObtainGetParam

func ObtainGetParam(ctx *gin.Context, key string) string

ObtainGetParam 获取 GET 请求的参数(从url获取).

PS: (1) 原生方法的用法更加丰富! (2) 不需要额外手动解码.

func ObtainInt32Param

func ObtainInt32Param(ctx *gin.Context, key string) (int32, error)

func ObtainInt64Param

func ObtainInt64Param(ctx *gin.Context, key string) (int64, error)

func ObtainIntParam

func ObtainIntParam(ctx *gin.Context, key string) (int, error)

func ObtainParam

func ObtainParam(ctx *gin.Context, key string) string

ObtainParam 获取请求参数.

PS: (1) 优先级(从左到右): GET、POST; (2) 不需要额外手动解码.

func ObtainPostParam

func ObtainPostParam(ctx *gin.Context, key string) string

ObtainPostParam 获取 POST 请求的参数.

PS: (1) 原生方法的用法更加丰富! (2) 不需要额外手动解码; (3) 请求的Content-Type, (a) 支持: multipart/form-data、x-www-form-urlencoded(即application/x-www-form-urlencoded)

(b) 不支持: application/json

func RespondError

func RespondError(ctx *gin.Context, statusCode int, err error)

func RespondFile

func RespondFile(ctx *gin.Context, httpStatusCode int, path, name string)

RespondFile

PS: (1) 支持的浏览器: ie、Edge、Safari、Chrome、Firefox; (2) 按照实际的业务,自行判断是否和 ginKit.SetCacheControlNoCache() 或 ginKit.SetCacheControlNoStore() 组合使用,或者不设置 "Cache-Control".

@param name 文件名(如果为"",将自动从传参path中获取)

func RespondFileContent

func RespondFileContent(ctx *gin.Context, httpStatusCode int, name, contentType string, data []byte)

RespondFileContent 响应文件流([]byte)给客户端.

PS: (1) 支持的浏览器: ie、Edge、Safari、Chrome、Firefox; (2) 按照实际的业务,自行判断是否和 ginKit.SetCacheControlNoCache() 或 ginKit.SetCacheControlNoStore() 组合使用,或者不设置 "Cache-Control".

@param name 可以为"" @param contentType 可以为"",将会使用默认值

func RespondFileFromFS

func RespondFileFromFS(ctx *gin.Context, httpStatusCode int, filePath string, fs http.FileSystem)

RespondFileFromFS

PS: (1) 支持的浏览器: ie、Edge、Safari、Chrome、Firefox; (2) 按照实际的业务,自行判断是否和 ginKit.SetCacheControlNoCache() 或 ginKit.SetCacheControlNoStore() 组合使用,或者不设置 "Cache-Control".

func RespondHtml

func RespondHtml(ctx *gin.Context, httpStatusCode int, htmlData []byte)

RespondHtml 响应html([]byte形式)给前端.

PS: (1) 只能是单纯的html文件,就算有js和css也只能内嵌,不能从外部导入; (2) 无法进行渲染(ctx.HTML()可以进行渲染); (3) 可以搭配 go-bindata 一起使用.

func RespondIcon

func RespondIcon(ctx *gin.Context, httpStatusCode int, iconData []byte)

func RespondPackage

func RespondPackage(ctx *gin.Context, pack *ResponsePackage)

RespondPackage

PS: 优先顺序(从高到低):文本(包括json)、 文件(路径)、文件(内容)、错误(error)

@param pack 可以为nil,此时:状态码为200,响应内容为空(不存在请求转发的情况).

func RespondPackageOrError

func RespondPackageOrError(ctx *gin.Context, pack *ResponsePackage, err error)

func RespondPanic

func RespondPanic(ctx *gin.Context, err any)

func RespondPdfContentToPrint

func RespondPdfContentToPrint(ctx *gin.Context, httpStatusCode int, pdfContent []byte)

RespondPdfContentToPrint 会触发浏览器端的打印.

PS: (1) 不要传文件名 (2) contentType为"application/pdf"

func SetHTMLTemplate added in v3.0.42

func SetHTMLTemplate(engine *gin.Engine, templ *template.Template)

SetHTMLTemplate

PS: (1) 搭配 gin.Context.HTML() 使用. (2) 参考: https://mp.weixin.qq.com/s/07YhlR3fFIbRPrvT6HUqng

func SetHttpStatusCode

func SetHttpStatusCode(ctx *gin.Context, statusCode int)

SetHttpStatusCode (响应头)设置http状态码

func SetResponseHeader

func SetResponseHeader(ctx *gin.Context, key, value string)

SetResponseHeader (响应头)

func SetUp

func SetUp(config *Config, businessLogic func(engine *gin.Engine) error, options ...GinOption) error

SetUp

PS: 正常执行的情况下,此方法会阻塞调用的协程.

@param config 不能为nil(否则将返回error) @param businessLogic 业务逻辑,可以在其中进行 路由绑定 等操作...(可以为nil,但不推荐这么干)

func StaticDir

func StaticDir(group gin.IRoutes, relativePath, root string, listDirectory bool) error

StaticDir 静态资源(目录)

PS: 适用场景: 静态资源与已绑定路由不冲突的情况(如果冲突的话,建议使用 NewStaticMiddleware).

@param relativePath 路由 @param root 相对路径(对于项目的根目录(working directory),而非main()所在的目录(虽然他们常常是同一个)) || 绝对路径 @param listDirectory 是否列出目录下的文件,true: 当目录下不存 index.html 文件时,会列出该目录下的所有文件(正式环境不推荐,因为不安全)

func StaticFS added in v3.0.42

func StaticFS(group gin.IRoutes, relativePath string, httpFs http.FileSystem) error

func StaticFile

func StaticFile(group gin.IRoutes, relativePath, filePath string) error

StaticFile 静态资源(单个文件)

@param relativePath 路由 @param filePath 相对路径(对于项目的根目录(working directory),而非main()所在的目录(虽然他们常常是同一个)) || 绝对路径

func WrapToHandlerFunc

func WrapToHandlerFunc(handler Handler) gin.HandlerFunc

WrapToHandlerFunc Handler 类型 => gin.HandlerFunc 类型

@param handler 不能为nil

Types

type Config

type Config struct {
	Mode     string `json:"mode" yaml:"mode" validate:"omitempty,oneof=debug release test"`
	HostName string `json:"hostName" yaml:"hostName" validate:"omitempty,hostname|ipv4"`
	// Port
	/*
		0(默认): 不使用 http port
	*/
	Port         int  `json:"port" yaml:"port" validate:"port|eq=0,necsfield=SSL.Port"`
	DisableColor bool `json:"disableColor" yaml:"disableColor"`
	Pprof        bool `json:"pprof" yaml:"pprof"`

	SSL        SslConfig        `json:"ssl" yaml:"ssl"`
	Middleware MiddlewareConfig `json:"middleware" yaml:"middleware"`
}

type CorsConfig

type CorsConfig struct {
	Access  bool     `json:"access" yaml:"access"`
	Origins []string `json:"origins" yaml:"origins" validate:"unique,dive,required"`
}

CorsConfig cors(跨源资源共享)的配置

type GinOption

type GinOption func(opts *ginOptions)

func WithDefaultFavicon

func WithDefaultFavicon(defaultFavicon bool) GinOption

func WithDefaultNoMethod

func WithDefaultNoMethod(defaultNoMethod bool) GinOption

func WithDefaultNoRouteHtml

func WithDefaultNoRouteHtml(defaultNoRouteHtml bool) GinOption

func WithDefaultOptionsMiddleware

func WithDefaultOptionsMiddleware(defaultOptionsMiddleware bool) GinOption

func WithRecoveryMiddleware

func WithRecoveryMiddleware(recoveryMiddleware gin.HandlerFunc) GinOption

func WithServiceInfo

func WithServiceInfo(serviceInfo string) GinOption

type GzipConfig added in v3.0.41

type GzipConfig struct {
	Level int `json:"level" yaml:"level" validate:"min=-1,max=9"`

	ExcludedExtensions   []string `json:"excludedExtensions" yaml:"excludedExtensions"`
	ExcludedPaths        []string `json:"excludedPaths" yaml:"excludedPaths"`
	ExcludedPathsRegexps []string `json:"excludedPathsRegexps" yaml:"excludedPathsRegexps"`
}

type Handler

type Handler func(ctx *gin.Context) (*ResponsePackage, error)

type MiddlewareConfig

type MiddlewareConfig struct {
	BodyLimit int64 `json:"bodyLimit" yaml:"bodyLimit"`

	Gzip *GzipConfig `json:"gzip" yaml:"gzip"`

	Cors CorsConfig `json:"cors" yaml:"cors"`

	RateLimiter *RateLimiterConfig `json:"rateLimiter" yaml:"rateLimiter"`

	ResponseHeaders map[string]string `json:"responseHeaders" yaml:"responseHeaders" mapstructure:"responseHeaders"`
}

type RateLimiterConfig

type RateLimiterConfig struct {
	R int `json:"r" yaml:"r" validate:"gt=0"`
	B int `json:"b" yaml:"b" validate:"gt=0,gtecsfield=R"`
}

RateLimiterConfig 限流器(令牌桶算法)的配置

type ResponsePackage

type ResponsePackage struct {
	// StatusCode http状态码(默认200,即 http.StatusOK)
	StatusCode int

	// Object json对象(不为nil的情况下,序列化为json并响应给前端)
	Object interface{}

	// Text 响应字符串(也可以是json)
	Text string

	// FilePath 响应文件的路径
	FilePath string
	// FileContent 响应文件的内容
	FileContent []byte
	// ContentType 响应文件内容的类型(需要与 FileContent 搭配使用)
	ContentType string
	// FileName 文件名
	/*
		PS: 使用 FilePath 的情况下, FileName 是可选的,为空的话会自己从 FilePath 中截取
	*/
	FileName string

	Error error
}

type SslConfig

type SslConfig struct {
	// Port
	/*
		0(默认): 不使用 https port
	*/
	Port     int    `json:"port" yaml:"port" validate:"port|eq=0"`
	CertFile string `json:"certFile" yaml:"certFile" validate:"file_unless=Port 0"`
	KeyFile  string `json:"keyFile" yaml:"keyFile" validate:"file_unless=Port 0"`
}

Jump to

Keyboard shortcuts

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