ginKit

package
v1.30.16 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2023 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package ginKit

参考: 使用gin搭建api后台系统之cookie与session https://mp.weixin.qq.com/s/nSu4ZQ9lStvGFNnuC2WKnA

Package ginKit

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

Package ginKit 路由相关

Package ginKit 静态资源相关

Index

Constants

This section is empty.

Variables

View Source
var SafeParamCapture = &paramCapture{
	safe: true,
}

SafeParamCapture 安全的,如果满足以下条件则必须使用此实例:请求转发、请求转发前会从POST中取参数、不会覆盖请求参数

View Source
var UnsafeParamCapture = &paramCapture{
	safe: false,
}

UnsafeParamCapture 默认的,不安全的

Functions

func AddHeader

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

func AttachCommonMiddlewares

func AttachCommonMiddlewares(engine *gin.Engine, middlewareConfig *MiddlewareConfig, recoveryMiddleware gin.HandlerFunc) error

AttachCommonMiddlewares 绑定一些常用的中间件.

func DelCookie

func DelCookie()

DelCookie 删除cookie

func DelHeader

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

func FaviconByDefault

func FaviconByDefault(group IGroup) error

func GetBoolParam

func GetBoolParam(ctx *gin.Context, key string, def bool) bool

func GetClientIp

func GetClientIp(ctx *gin.Context) string

GetClientIp 获取客户端的ip.

PS: 为了更加准确的获取客户端ip,可以同时使用 Context.ClientIP() 和 Engine.TrustedPlatform (此外还需配置代理),详见参考.

参考: gin框架中设置信任代理IP并获取远程客户端IP

https://www.cnblogs.com/mayanan/p/15703234.html

gin获取用户请求IP

https://blog.csdn.net/weixin_45867397/article/details/122849424

func GetCookie

func GetCookie(ctx *gin.Context, name string) (string, error)

GetCookie 读取cookie

PS: 如果不存在与 name 对应的cookie,将返回error(== http.ErrNoCookie).

func GetFloat32Param

func GetFloat32Param(ctx *gin.Context, key string, def float32) float32

func GetFloat64Param

func GetFloat64Param(ctx *gin.Context, key string, def float64) float64

func GetFormFile

func GetFormFile(ctx *gin.Context, key string) (*multipart.FileHeader, error)

func GetFormFileContent

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

func GetHeader

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

func GetIntParam

func GetIntParam(ctx *gin.Context, key string, def int) int

func GetParam

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

func GetParamFromGet

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

func GetParamFromPost

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

func GetRequestRoute

func GetRequestRoute(ctx *gin.Context) string

GetRequestRoute 获取请求的路由.

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 Initialize

func Initialize(colorful bool)

Initialize 初始化gin的配置.

func LoadHtmlFiles

func LoadHtmlFiles(engine IEngine, filePaths ...string)

LoadHtmlFiles 加载(多个)html文件

func LoadHtmlGlob

func LoadHtmlGlob(engine IEngine, pattern string)

func MustSetUp added in v1.3.11

func MustSetUp(config *Config, recoveryMiddleware gin.HandlerFunc, businessLogic func(engine *gin.Engine) error)

func NewCorsMiddleware

func NewCorsMiddleware(origins []string) gin.HandlerFunc

NewCorsMiddleware 新建一个cors中间件.

@param origins origin白名单,可以为nil

func NewEngine

func NewEngine() *gin.Engine

NewEngine

@param recovery 可以为nil,将采用默认值 gin.Recovery()

func NewOpenCorsMiddleware

func NewOpenCorsMiddleware() gin.HandlerFunc

NewOpenCorsMiddleware 新建一个开放的(任意origin都通过)cors中间件.

func NoRoute

func NoRoute(engine IEngine, handlers ...gin.HandlerFunc)

NoRoute 404

func NoRouteByDefault

func NoRouteByDefault(engine IEngine) error

NoRouteByDefault 使用自带的404页面

func OnDebugChanged

func OnDebugChanged()

OnDebugChanged debug发生了改变,进行相应处理

func RegisterHandlersToRoute

func RegisterHandlersToRoute(group IGroup, route string, methods []string, handlers ...gin.HandlerFunc)

RegisterHandlersToRoute 将多个相同的处理器,注册到1个路由

@param methods nil => 接收所有类型method的请求. e.g. http.MethodGet、http.MethodPost

func RegisterHandlersToRoutes

func RegisterHandlersToRoutes(group IGroup, routes []string, methods []string, handlers ...gin.HandlerFunc)

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

func RespondError

func RespondError(ctx *gin.Context, httpStatusCode 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 RespondJson

func RespondJson(ctx *gin.Context, statusCode int, h gin.H)

RespondJson 响应json字符串.

@param h gin.H is a shortcut for map[string]interface{}

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 RespondText

func RespondText(ctx *gin.Context, statusCode int, format string, args ...interface{})

RespondText 响应文本.

@param args 用于替换 传参format 中的格式占位符(%s、%d...)

func SetCacheControlNoCache

func SetCacheControlNoCache(ctx *gin.Context)

SetCacheControlNoCache 实际上是有缓存的)浏览器对请求回来的response做缓存,但是每次在向客户端(浏览器)提供响应数据时,缓存都要向服务器评估缓存响应的有效性。

PS: 详见"Web.docx".

func SetCacheControlNoStore

func SetCacheControlNoStore(ctx *gin.Context)

SetCacheControlNoStore 禁止一切缓存.

PS: 详见"Web.docx".

func SetCookie

func SetCookie(ctx *gin.Context, name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie cookie

@param name cookie的键 @param value cookie的值 @param maxAge cookie的有效时长(单位为秒;超时即会失效) @param path cookie所在的目录(可以为"",会被"/"替换) @param domain 所在域,表示我们的 cookie 作用范围,里面可以是localhost也可以是你的域名,看自己情况(可以为"",此时响应头中Set-Cookie将不会带有domain信息,前端自行生成与当前页面对应的) @param secure 是否只能通过https访问?true: 只能通过https访问 @param httpOnly cookie是否可以通过js代码进行操作?true: 不能被js进行操作

func SetHeader

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

func SetHttpStatusCode

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

SetHttpStatusCode 设置http状态码

func StaticDir

func StaticDir(group IGroup, relativePath, dirPath string, listDirectory bool)

StaticDir 静态资源(目录)

@param relativePath 路由 @param dirPath 静态资源所在的目录(相对路径 || 绝对路径)

func StaticFile

func StaticFile(group IGroup, relativePath, filePath string)

StaticFile 静态资源(单个文件)

func WrapToHandlerFunc

func WrapToHandlerFunc(handler Handler) gin.HandlerFunc

WrapToHandlerFunc Handler 类型 => gin.HandlerFunc 类型

Types

type Config added in v1.3.11

type Config struct {
	Host string `json:"host,optional"`
	Port int    `json:"port,default=-1,range=[-1:65535]"`
	/*
		日志的颜色(默认true)
		true: 	强制设置日志颜色
		false: 	禁止日志颜色
	*/
	Colorful   bool              `json:"colorful,default=true"`
	Middleware *MiddlewareConfig `json:"middleware,optional"`
	SSL        *SslConfig        `json:"ssl,optional"`
}

func (*Config) Check added in v1.30.16

func (config *Config) Check() error

Check 先简单验证下配置.

type CorsConfig

type CorsConfig struct {
	Origins []string `json:"origins,optional"`
}

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

type Handler

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

type IEngine

type IEngine interface {
	LoadHTMLFiles(filePaths ...string)

	LoadHTMLGlob(pattern string)

	NoRoute(handlers ...gin.HandlerFunc)
}

type IGroup

type IGroup interface {
	Handle(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes

	Any(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes

	StaticFile(relativePath, filepath string) gin.IRoutes

	StaticFS(relativePath string, fs http.FileSystem) gin.IRoutes

	Static(relativePath, root string) gin.IRoutes
}

type MiddlewareConfig

type MiddlewareConfig struct {
	Gzip          bool                                 `json:"gzip,default=false"`
	XFrameOptions string                               `json:"xFrameOptions,optional"`
	Cors          *CorsConfig                          `json:"cors,optional"`
	Referer       []*refererKit.RefererVerifierBuilder `json:"referer,optional"`
}

type ResponsePackage

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

	// 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 added in v1.30.16

type SslConfig struct {
	CertFile string `json:"certFile,optional"`
	KeyFile  string `json:"keyFile,optional"`
	Port     int    `json:"port,default=-1,range=[-1:65535]"`
}

Jump to

Keyboard shortcuts

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