igin

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2023 License: Apache-2.0 Imports: 24 Imported by: 0

README

igin

I like to use the gin framework

Documentation

Index

Constants

View Source
const (
	// KB represents the size of a kilobyte.
	KB float64 = 1024
	// MB represents the size of a megabyte.
	MB float64 = 1024 * KB
	// GB represents the size of a gigabyte.
	GB float64 = 1024 * MB
	// TB represents the size of a terabyte.
	TB float64 = 1024 * GB
	// PB represents the size of a petabyte.
	PB float64 = 1024 * TB
)
View Source
const (
	HeaderAccept         = "Accept"
	HeaderAcceptEncoding = "Accept-Encoding"
	// HeaderAllow is the name of the "Allow" header field used to list the set of methods
	// advertised as supported by the target resource. Returning an Allow header is mandatory
	// for status 405 (method not found) and useful for the OPTIONS method in responses.
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderRetryAfter          = "Retry-After"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-Ip"
	HeaderXRequestID          = "X-Request-Id"
	HeaderXCorrelationID      = "X-Correlation-Id"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"
	HeaderCacheControl        = "Cache-Control"
	HeaderConnection          = "Connection"
	HeaderUserAgent           = "User-Agent"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"

	// PROPFIND Method can be used on collection and property resources.
	PROPFIND = "PROPFIND"
	// REPORT Method can be used to get information about a resource, see rfc 3253
	REPORT                               = "REPORT"
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
	MIMEEventStream                      = "text/event-stream"
)

Headers

View Source
const (
	TranslatorLocaleEN = "en"
	TranslatorLocaleZH = "zh"
)

Variables

View Source
var (
	Translator   *translator
	UtTranslator ut.Translator
)
View Source
var (

	// BusinessCodeOK represents the business code for success.
	BusinessCodeOK = 0
	// BusinessMsgOk represents the business message for success.
	BusinessMsgOk = "ok"
	// BusinessCodeError represents the business code for error.
	BusinessCodeError = -1
)

Functions

func Abs

func Abs(path string) string

Abs Returns the fully resolved path, even if the path does not exist.

``` fsx.Abs("./does/not/exist") ``` If the code above was run within `/home/user`, the result would be `/home/user/does/not/exist`.

func AddStatusError

func AddStatusError(c *gin.Context, err error, codes ...int)

AddStatusError 向gin.error中追加错误

func ByteSize

func ByteSize(path string) (int64, error)

ByteSize returns the number of bytes (size) of a file/directory.

func Clean

func Clean(path string)

Clean will ensure the specified directory exists. If the directory already exists, all of contents are deleted. If the directory does not exist, it is automatically created.

func ContextIResponse

func ContextIResponse(c *gin.Context, response IResponse, statusRuleFuns ...IResponseStatusRuleFun)

func Copy

func Copy(source string, dest string, ignoreErrors ...bool) error

Copy a file/directory

func DefaultTranslator

func DefaultTranslator() *translator

func Exists

func Exists(path string) bool

Exists is a helper method to quickly determine whether a directory or file exists.

func FormatSize

func FormatSize(bytesize int64, sigfig ...int) string

FormatSize returns a nicely formatted representation of a number of bytes, such as `3.14MB`

func IsDirectory

func IsDirectory(path string) bool

IsDirectory determines whether the specified path represents a directory.

func IsExecutable

func IsExecutable(path string) bool

IsExecutable determines whether the file/directory is executable for the active system user.

func IsFile

func IsFile(path string) bool

IsFile determines whether the specified path represents a file.

func IsReadable

func IsReadable(path string) bool

IsReadable determines whether the file/directory is readable for the active system user.

func IsSymlink(path string) bool

IsSymlink determines whether the path is a symbolic link.

func IsWritable

func IsWritable(path string) bool

IsWritable determines whether the file/directory is writable for the active system user.

func JsonBaseResponse

func JsonBaseResponse(c *gin.Context, v any)

JsonBaseResponse writes v into w with http.StatusOK.

func JsonError

func JsonError(ctx *gin.Context, err error, codes ...int)

func JsonErrorString

func JsonErrorString(ctx *gin.Context, err string, codes ...int)

func JsonSuccess

func JsonSuccess(ctx *gin.Context, data any, messages ...string)

func LastModified

func LastModified(path string) (time.Time, error)

LastModified identies the last time the path was modified.

func List

func List(directory string, recursive bool, ignore ...string) ([]string, error)

List Generate a list of path names for the given directory. Optionally provide a list of ignored paths, using [glob](https://en.wikipedia.org/wiki/Glob_%28programming%29) syntax.

func ListDirectories

func ListDirectories(directory string, recursive bool, ignore ...string) ([]string, error)

ListDirectories provides absolute paths of directories only, ignoring files.

func ListFiles

func ListFiles(directory string, recursive bool, ignore ...string) ([]string, error)

ListFiles provides absolute paths of files only, ignoring directories.

func Mkdir

func Mkdir(path string) string

Mkdir is the equivalent of [mkdir -p](https://en.wikipedia.org/wiki/Mkdir) It will generate the full directory path if it does not already exist.

func Move

func Move(source string, dest string, ignoreErrors ...bool) error

Move a file/directory to another location

func NewTranslator

func NewTranslator(supportedLocales []locales.Translator, localeRegisterDefaultTranslations LocaleRegisterDefaultTranslations) *translator

func ReadFile

func ReadFile(path string) ([]byte, error)

func ReadTextFile

func ReadTextFile(path string) (string, error)

ReadTextFile reads a text file and converts results from bytes to a string.

func Size

func Size(path string, sigfig ...int) (string, error)

Size returns a "pretty" version of the size, such as "3.12MB"

func Symlink(target string, name string) error

Symlink creates a symbolic link. This just runs `os.Symlink()`.

func Touch

func Touch(path string, flags ...any) string

Touch Similar to the touch command on *nix, where the file or directory will be created if it does not already exist. Returns the absolute path. The optional second boolean argument will force the method to treat the path as a file instead of a directory (useful when the filename has no extension). An optional 3rd boolean argument will force the method to treat the path as a directory even if a file extension is present.

For example: `fsx.Touch("./path/to/archive.old", false, true)`

Normally, any file path with an extension is determined to be a file. However; the second argument (`false`) instructs the command to **not** force a file. The third argument (`true`) instructs the command to **treat the path like a directory**.

func WriteFile

func WriteFile(path string, content string) (int, error)

func WriteTextFile

func WriteTextFile(path string, content string, args ...any) error

WriteTextFile writes text to a file (automatically converts string to a byte array). If the path does not exist, it will be created automatically. This is the equivalent of using the Touch() method first, then writing text content to the file.

It is also possible to pass a third argument, a custom permission. By default, os.ModePerm is used.

func XmlBaseResponse

func XmlBaseResponse(c *gin.Context, v any)

XmlBaseResponse writes v into w with http.StatusOK.

Types

type BaseResponse

type BaseResponse[T any] struct {
	// Code represents the business code, not the http status code.
	Code int `json:"code" xml:"code"`
	// Msg represents the business message, if Code = BusinessCodeOK,
	// and Msg is empty, then the Msg will be set to BusinessMsgOk.
	Msg string `json:"msg" xml:"msg"`
	// Data represents the business data.
	Data T `json:"data,omitempty" xml:"data,omitempty"`
}

type Engine

type Engine struct {
	*gin.Engine
}

func Default

func Default() *Engine

func New

func New() *Engine

func NewEngine

func NewEngine(engine *gin.Engine) *Engine

func (*Engine) BindingValidatorEngine

func (e *Engine) BindingValidatorEngine(locale string, translators ...*translator)

func (*Engine) Controller

func (e *Engine) Controller(controllers ...IController)

func (*Engine) Plugin

func (e *Engine) Plugin(Plugins ...IPlugin)

func (*Engine) PrefixController

func (e *Engine) PrefixController(prefix string, controllers ...IController)

func (*Engine) SetFuncMaps

func (e *Engine) SetFuncMaps(funcMaps ...template.FuncMap) *Engine

type GinContext

type GinContext struct {
	*gin.Context
}

func Context

func Context(c *gin.Context) *GinContext

Context 重新初始化Context

func (*GinContext) All added in v0.1.2

func (c *GinContext) All() GinContextInput

func (*GinContext) Form

func (c *GinContext) Form() url.Values

Form 获取所有参数

func (*GinContext) Header

func (c *GinContext) Header() http.Header

Header 获取 Header 参数

func (*GinContext) Host

func (c *GinContext) Host() string

Host 请求的host

func (*GinContext) IsDelete

func (c *GinContext) IsDelete() bool

IsDelete 是否为DELTE请求

func (*GinContext) IsGet

func (c *GinContext) IsGet() bool

IsGet 是否为GET请求

func (*GinContext) IsHead

func (c *GinContext) IsHead() bool

IsHead 是否为HEAD请求

func (*GinContext) IsOptions

func (c *GinContext) IsOptions() bool

IsOptions 是否为OPTIONS请求

func (*GinContext) IsPatch

func (c *GinContext) IsPatch() bool

IsPatch 是否为PATCH请求

func (*GinContext) IsPost

func (c *GinContext) IsPost() bool

IsPost 是否为POST请求

func (*GinContext) IsPut

func (c *GinContext) IsPut() bool

IsPut 是否为PUT请求

func (*GinContext) Path

func (c *GinContext) Path() string

Path 请求的路径(不附带querystring)

func (*GinContext) PostForm

func (c *GinContext) PostForm() url.Values

PostForm 获取 PostForm 参数

func (*GinContext) URI

func (c *GinContext) URI() string

URI unescape后的uri

type GinContextInput added in v0.1.2

type GinContextInput struct {
	Method   string      `json:"method"`
	Host     string      `json:"host"`
	Form     url.Values  `json:"form"`
	PostForm url.Values  `json:"post_form"`
	Query    url.Values  `json:"query"`
	Header   http.Header `json:"header"`
}

type IController

type IController interface {
	Prefix() string
	Routes(g gin.IRoutes)
}

type IPlugin

type IPlugin interface {
	Register(group *gin.RouterGroup)
	RouterPath() string
}

type IResponse

type IResponse interface {
	//WithStatusCode 携带状态码
	WithStatusCode(statusCode int)
	//StatusCode 响应状态码
	StatusCode() int
	//Abort 是否抛出异常
	Abort() bool
	//Render 渲染数据
	Render() render.Render
}

IResponse 响应状态码根据你传入的状态码走

type IResponseStatusRuleFun

type IResponseStatusRuleFun func(c *gin.Context, response IResponse) int

type JsonResponse

type JsonResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data"`
	Error   error  `json:"-"`
}

func (*JsonResponse) Abort

func (j *JsonResponse) Abort() bool

Abort 是否抛出异常

func (*JsonResponse) Render

func (j *JsonResponse) Render() render.Render

Render 渲染数据

func (*JsonResponse) SetErr

func (j *JsonResponse) SetErr(err error)

func (*JsonResponse) StatusCode

func (j *JsonResponse) StatusCode() int

StatusCode 响应状态码

func (*JsonResponse) WithMessage

func (j *JsonResponse) WithMessage(message string)

WithMessage 携带错误消息信息

func (*JsonResponse) WithStatusCode

func (j *JsonResponse) WithStatusCode(code int)

WithStatusCode 携带状态码

type LocaleRegisterDefaultTranslations

type LocaleRegisterDefaultTranslations func(locale string, v *validator.Validate, UtTranslator ut.Translator)

type ValidateError

type ValidateError struct {
	Key     string `json:"key"`
	Message string `json:"message"`
}

func (*ValidateError) Error

func (v *ValidateError) Error() string

type ValidateErrors

type ValidateErrors []*ValidateError

func (ValidateErrors) Error

func (v ValidateErrors) Error() string

func (ValidateErrors) Errors

func (v ValidateErrors) Errors() []string

Jump to

Keyboard shortcuts

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