sgin

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2024 License: MIT Imports: 19 Imported by: 0

README

sgin

这是一个 gin 的魔改版本,旨在让其更加简单。

sgin 拥有一个可选的默认配置。

r := sgin.New(sgin.Config{
    Mode: gin.DebugMode, // 默认值
    ErrorHandler: func(c *sgin.Ctx, err error) { // 默认错误处理
        var e *Error
        code := StatusInternalServerError
    
        if errors.As(err, &e) && e.Code > 0 { // 如果是 *Error
            code = e.Code
        } else if stc := c.StatusCode(); stc != 200 && stc != 0 {
            code = stc
        }
    
        return c.Status(code).Send(err.Error())
    }
})

r.Run(":8080")

处理方法

sgin 主要修改了原生处理函数,处理函数的签名变成了:func(*sgin.Ctx[, T]) T | (int, T) | (T, error)

接收请求参数

其中跟在 *sgin.Ctx 后面的 T 是可选的,它接收来自请求传递的数据。例如请求 index?name=p1&age=10 ,这会将查询参数绑定到结构体 p 中。

r.Get("/index", func(c *sgin.Ctx, p struct{
    Name string `form:"name"`
    Age  int    `form:"age"`
}) {
    // p => {"p1", 10}
})

接收 JSON 参数,只需将标签改为 json (xml 同理):

r.Get("/index", func(c *sgin.Ctx, p struct{
    Name string `json:"name"`
    Age  int    `json:"age"`
}) {
    // p => {"p1", 10}
})
返回响应

要返回响应数据,你可以使用 c.Send(),或在处理函数中定义返回值(稍后介绍)。

r.Get("/index", func(c *sgin.Ctx) {
    c.Sned("Very OK")
})

Send(any, format ...string) 方法会自动根据请求头 Accept 返回对应格式的数据,也可以手动指定。

Send() 细节:

  • 如果发送数字,将被仅当做状态码返回。
  • 如果发送 stringerror 将返回原字符串或 error.Error()
  • 将格式传递给 format 参数,将返回对应类型的数据。例如 c.Send(map[string]any{}, sgin.FormatJSON)
  • 如果你有状态码和错误一起返回:c.Send(sgin.NewError(statusCode, msg))
  • 当然你可以先设置状态码后发送你的数据:c.Status(200).Send(...)

除了可以使用 Send() 返回响应数据外,还可以将其定义为处理函数的返回值,返回值类型可以为:

  • T: 任意响应体;
  • (int, T): 状态码和任意响应体;
  • (T, error): 响应体和错误。

注意,T 是任意类型,通常为 int, error, string, Any,处理函数的返回值类型和使用 Send() 返回的数据基本是一致的。

r.Get("/index", func(c *sgin.Ctx) int {
    return 401 // 只返回状态码
})

r.Get("/index", func(c *sgin.Ctx) error {
    return errors.New("error") // 在不指定错误状态码的情况下,状态码默认为 500。
})

r.Get("/index", func(c *sgin.Ctx) (r sgin.Response) {
    return r.OK() // 返回任意响应
})

r.Get("/index", func(c *sgin.Ctx) (r *map[string]any, error) {
    return nil, errors.new("test error") // 返回响应或错误
})

r.Get("/index", func(c *sgin.Ctx) (int, map[string]any) {
    return nil, map[string]any{"msg": "test"} // 返回状态码和响应
})

Api

Ctx
  • Args() map[string]any:返回请求参数集合,无论是 GET、POST 还是 JSON 等请求;
  • ArgInt(key string, e ...string) 等:将请求参数转为对应的类型;
  • Send(any, format ...string) 发送响应。
  • SendHTML(string, any)HTML 模板作为响应发送。
  • Locals(key string, ...any) any:设置或将值存储到上下文。
  • Header(key string, ...any) any:设置或写入响应头。此外 sgin 定义了许多枚举来帮助你快速找到某个请求头,例如要获取内容类型:Header(sgin.HeaderContentType)
  • Status(int) *Ctx:设置响应状态码;
  • StatusCode() int:获取响应状态码;
  • Method() string:获取请求方法;
  • Path(full ...bool) string:返回部分或全部请求路径;
  • IP() string:返回远程客户端 IP,如果是本机则返回 127.0.0.1;
  • ... 其他来自 gin.Context 的方法。

Documentation

Index

Constants

View Source
const (
	FormatXML      = "XML"
	FormatJSON     = "JSON"
	FormatString   = "String"
	FormatUpload   = "Upload"
	FormatDownload = "Download"
)
View Source
const (
	MIMETextXML         = "text/xml"
	MIMETextHTML        = "text/html"
	MIMETextPlain       = "text/plain"
	MIMETextJavaScript  = "text/javascript"
	MIMEApplicationXML  = "application/xml"
	MIMEApplicationJSON = "application/json"
	MIMEApplicationForm = "application/x-www-form-urlencoded"
	MIMEOctetStream     = "application/octet-stream"
	MIMEMultipartForm   = "multipart/form-data"

	MIMETextXMLCharsetUTF8         = "text/xml; charset=utf-8"
	MIMETextHTMLCharsetUTF8        = "text/html; charset=utf-8"
	MIMETextPlainCharsetUTF8       = "text/plain; charset=utf-8"
	MIMETextJavaScriptCharsetUTF8  = "text/javascript; charset=utf-8"
	MIMEApplicationXMLCharsetUTF8  = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	StatusContinue           = 100 // RFC 9110, 15.2.1
	StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                          = 200 // RFC 9110, 15.3.1
	StatusCreated                     = 201 // RFC 9110, 15.3.2
	StatusAccepted                    = 202 // RFC 9110, 15.3.3
	StatusNonAuthoritativeInformation = 203 // RFC 9110, 15.3.4
	StatusNoContent                   = 204 // RFC 9110, 15.3.5
	StatusResetContent                = 205 // RFC 9110, 15.3.6
	StatusPartialContent              = 206 // RFC 9110, 15.3.7
	StatusMultiStatus                 = 207 // RFC 4918, 11.1
	StatusAlreadyReported             = 208 // RFC 5842, 7.1
	StatusIMUsed                      = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices   = 300 // RFC 9110, 15.4.1
	StatusMovedPermanently  = 301 // RFC 9110, 15.4.2
	StatusFound             = 302 // RFC 9110, 15.4.3
	StatusSeeOther          = 303 // RFC 9110, 15.4.4
	StatusNotModified       = 304 // RFC 9110, 15.4.5
	StatusUseProxy          = 305 // RFC 9110, 15.4.6
	StatusSwitchProxy       = 306 // RFC 9110, 15.4.7 (Unused)
	StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
	StatusPermanentRedirect = 308 // RFC 9110, 15.4.9

	StatusBadRequest                   = 400 // RFC 9110, 15.5.1
	StatusUnauthorized                 = 401 // RFC 9110, 15.5.2
	StatusPaymentRequired              = 402 // RFC 9110, 15.5.3
	StatusForbidden                    = 403 // RFC 9110, 15.5.4
	StatusNotFound                     = 404 // RFC 9110, 15.5.5
	StatusMethodNotAllowed             = 405 // RFC 9110, 15.5.6
	StatusNotAcceptable                = 406 // RFC 9110, 15.5.7
	StatusProxyAuthRequired            = 407 // RFC 9110, 15.5.8
	StatusRequestTimeout               = 408 // RFC 9110, 15.5.9
	StatusConflict                     = 409 // RFC 9110, 15.5.10
	StatusGone                         = 410 // RFC 9110, 15.5.11
	StatusLengthRequired               = 411 // RFC 9110, 15.5.12
	StatusPreconditionFailed           = 412 // RFC 9110, 15.5.13
	StatusRequestEntityTooLarge        = 413 // RFC 9110, 15.5.14
	StatusRequestURITooLong            = 414 // RFC 9110, 15.5.15
	StatusUnsupportedMediaType         = 415 // RFC 9110, 15.5.16
	StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
	StatusExpectationFailed            = 417 // RFC 9110, 15.5.18
	StatusTeapot                       = 418 // RFC 9110, 15.5.19 (Unused)
	StatusMisdirectedRequest           = 421 // RFC 9110, 15.5.20
	StatusUnprocessableEntity          = 422 // RFC 9110, 15.5.21
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusTooEarly                     = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired              = 426 // RFC 9110, 15.5.22
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 9110, 15.6.1
	StatusNotImplemented                = 501 // RFC 9110, 15.6.2
	StatusBadGateway                    = 502 // RFC 9110, 15.6.3
	StatusServiceUnavailable            = 503 // RFC 9110, 15.6.4
	StatusGatewayTimeout                = 504 // RFC 9110, 15.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 9110, 15.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes were copied from net/http with the following updates: - Rename StatusNonAuthoritativeInfo to StatusNonAuthoritativeInformation - Add StatusSwitchProxy (306) NOTE: Keep this list in sync with statusMessage

View Source
const (
	HeaderAuthorization                   = "Authorization"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderAge                             = "Age"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderExpires                         = "Expires"
	HeaderPragma                          = "Pragma"
	HeaderWarning                         = "Warning"
	HeaderAcceptCH                        = "Accept-CH"
	HeaderAcceptCHLifetime                = "Accept-CH-Lifetime"
	HeaderContentDPR                      = "Content-DPR"
	HeaderDPR                             = "DPR"
	HeaderEarlyData                       = "Early-Data"
	HeaderSaveData                        = "Save-Data"
	HeaderViewportWidth                   = "Viewport-Width"
	HeaderWidth                           = "Width"
	HeaderETag                            = "ETag"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderLastModified                    = "Last-Modified"
	HeaderVary                            = "Vary"
	HeaderConnection                      = "Connection"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderCookie                          = "Cookie"
	HeaderExpect                          = "Expect"
	HeaderMaxForwards                     = "Max-Forwards"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderOrigin                          = "Origin"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies   = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                             = "DNT"
	HeaderTk                              = "Tk"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentType                     = "Content-Type"
	HeaderForwarded                       = "Forwarded"
	HeaderVia                             = "Via"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      = "X-Url-Scheme"
	HeaderLocation                        = "Location"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderUserAgent                       = "User-Agent"
	HeaderAllow                           = "Allow"
	HeaderServer                          = "Server"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderContentRange                    = "Content-Range"
	HeaderIfRange                         = "If-Range"
	HeaderRange                           = "Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderPermissionsPolicy               = "Permissions-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderLastEventID                     = "Last-Event-ID"
	HeaderNEL                             = "NEL"
	HeaderPingFrom                        = "Ping-From"
	HeaderPingTo                          = "Ping-To"
	HeaderReportTo                        = "Report-To"
	HeaderTE                              = "TE"
	HeaderTrailer                         = "Trailer"
	HeaderTransferEncoding                = "Transfer-Encoding"
	HeaderSecWebSocketAccept              = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions          = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey                 = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol            = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion             = "Sec-WebSocket-Version"
	HeaderAcceptPatch                     = "Accept-Patch"
	HeaderAcceptPushPolicy                = "Accept-Push-Policy"
	HeaderAcceptSignature                 = "Accept-Signature"
	HeaderAltSvc                          = "Alt-Svc"
	HeaderDate                            = "Date"
	HeaderIndex                           = "Index"
	HeaderLargeAllocation                 = "Large-Allocation"
	HeaderLink                            = "Link"
	HeaderPushPolicy                      = "Push-Policy"
	HeaderRetryAfter                      = "Retry-After"
	HeaderServerTiming                    = "Server-Timing"
	HeaderSignature                       = "Signature"
	HeaderSignedHeaders                   = "Signed-Headers"
	HeaderSourceMap                       = "SourceMap"
	HeaderUpgrade                         = "Upgrade"
	HeaderXDNSPrefetchControl             = "X-DNS-Prefetch-Control"
	HeaderXPingback                       = "X-Pingback"
	HeaderXRequestID                      = "X-Request-ID"
	HeaderXRequestedWith                  = "X-Requested-With"
	HeaderXRobotsTag                      = "X-Robots-Tag"
	HeaderXUACompatible                   = "X-UA-Compatible"
)

HTTP Headers were copied from net/http.

Variables

View Source
var (
	ErrBadRequest                   = NewError(StatusBadRequest)                   // 400
	ErrUnauthorized                 = NewError(StatusUnauthorized)                 // 401
	ErrPaymentRequired              = NewError(StatusPaymentRequired)              // 402
	ErrForbidden                    = NewError(StatusForbidden)                    // 403
	ErrNotFound                     = NewError(StatusNotFound)                     // 404
	ErrMethodNotAllowed             = NewError(StatusMethodNotAllowed)             // 405
	ErrNotAcceptable                = NewError(StatusNotAcceptable)                // 406
	ErrProxyAuthRequired            = NewError(StatusProxyAuthRequired)            // 407
	ErrRequestTimeout               = NewError(StatusRequestTimeout)               // 408
	ErrConflict                     = NewError(StatusConflict)                     // 409
	ErrGone                         = NewError(StatusGone)                         // 410
	ErrLengthRequired               = NewError(StatusLengthRequired)               // 411
	ErrPreconditionFailed           = NewError(StatusPreconditionFailed)           // 412
	ErrRequestEntityTooLarge        = NewError(StatusRequestEntityTooLarge)        // 413
	ErrRequestURITooLong            = NewError(StatusRequestURITooLong)            // 414
	ErrUnsupportedMediaType         = NewError(StatusUnsupportedMediaType)         // 415
	ErrRequestedRangeNotSatisfiable = NewError(StatusRequestedRangeNotSatisfiable) // 416
	ErrExpectationFailed            = NewError(StatusExpectationFailed)            // 417
	ErrTeapot                       = NewError(StatusTeapot)                       // 418
	ErrMisdirectedRequest           = NewError(StatusMisdirectedRequest)           // 421
	ErrUnprocessableEntity          = NewError(StatusUnprocessableEntity)          // 422
	ErrLocked                       = NewError(StatusLocked)                       // 423
	ErrFailedDependency             = NewError(StatusFailedDependency)             // 424
	ErrTooEarly                     = NewError(StatusTooEarly)                     // 425
	ErrUpgradeRequired              = NewError(StatusUpgradeRequired)              // 426
	ErrPreconditionRequired         = NewError(StatusPreconditionRequired)         // 428
	ErrTooManyRequests              = NewError(StatusTooManyRequests)              // 429
	ErrRequestHeaderFieldsTooLarge  = NewError(StatusRequestHeaderFieldsTooLarge)  // 431
	ErrUnavailableForLegalReasons   = NewError(StatusUnavailableForLegalReasons)   // 451

	ErrInternalServerError           = NewError(StatusInternalServerError)           // 500
	ErrNotImplemented                = NewError(StatusNotImplemented)                // 501
	ErrBadGateway                    = NewError(StatusBadGateway)                    // 502
	ErrServiceUnavailable            = NewError(StatusServiceUnavailable)            // 503
	ErrGatewayTimeout                = NewError(StatusGatewayTimeout)                // 504
	ErrHTTPVersionNotSupported       = NewError(StatusHTTPVersionNotSupported)       // 505
	ErrVariantAlsoNegotiates         = NewError(StatusVariantAlsoNegotiates)         // 506
	ErrInsufficientStorage           = NewError(StatusInsufficientStorage)           // 507
	ErrLoopDetected                  = NewError(StatusLoopDetected)                  // 508
	ErrNotExtended                   = NewError(StatusNotExtended)                   // 510
	ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // 511
)

Errors

Functions

func DefaultErrorHandler

func DefaultErrorHandler(c *Ctx, err error) error

DefaultErrorHandler 该进程从处理程序返回错误

Types

type Config

type Config struct {
	Mode           string // gin.DebugMode | gin.ReleaseMode | gin.TestMode
	TrustedProxies []string
	Recovery       func(*Ctx, string)
	ErrorHandler   func(*Ctx, error) error
}

type Ctx

type Ctx struct {
	Request *http.Request
	Writer  gin.ResponseWriter
	Params  gin.Params
	Keys    map[string]any
	// contains filtered or unexported fields
}

func (*Ctx) Arg

func (c *Ctx) Arg(key string, or ...string) string

func (*Ctx) ArgBool

func (c *Ctx) ArgBool(key string) bool

func (*Ctx) ArgFloat64

func (c *Ctx) ArgFloat64(key string, or ...float64) float64

func (*Ctx) ArgInt

func (c *Ctx) ArgInt(key string, or ...int) int

func (*Ctx) ArgInt64

func (c *Ctx) ArgInt64(key string, or ...int64) int64

func (*Ctx) Args

func (c *Ctx) Args() (args map[string]any)

func (*Ctx) Cookie

func (c *Ctx) Cookie(name string) (string, error)

func (*Ctx) Header

func (c *Ctx) Header(key string, value ...string) string

Header 获取 HTTP 请求头的值,如果不存在则返回可选的默认值。

func (*Ctx) IP

func (c *Ctx) IP() (ip string)

func (*Ctx) Locals

func (c *Ctx) Locals(key string, value ...any) any

Locals 设置或将值存储到上下文

func (*Ctx) Method

func (c *Ctx) Method() string

func (*Ctx) Next

func (c *Ctx) Next() error

func (*Ctx) Param

func (c *Ctx) Param(key string) string

func (*Ctx) Path

func (c *Ctx) Path(full ...bool) string

func (*Ctx) RawBody

func (c *Ctx) RawBody() (body []byte)

func (*Ctx) SaveFile

func (c *Ctx) SaveFile(file *multipart.FileHeader, dst string) error

func (*Ctx) Send

func (c *Ctx) Send(body any, format ...string) error

func (*Ctx) SendHTML

func (c *Ctx) SendHTML(name string, data any) error

func (*Ctx) SetCookie

func (c *Ctx) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

func (*Ctx) SetHeader

func (c *Ctx) SetHeader(key string, value string)

func (*Ctx) Status

func (c *Ctx) Status(code int) *Ctx

func (*Ctx) StatusCode

func (c *Ctx) StatusCode() int

type Engine

type Engine struct {
	Route
	// contains filtered or unexported fields
}

func New

func New(config ...Config) *Engine

func (*Engine) Handler

func (e *Engine) Handler() http.Handler

func (*Engine) Routes

func (e *Engine) Routes() gin.RoutesInfo

func (*Engine) Run

func (e *Engine) Run(addr ...string) (err error)

func (*Engine) RunServeTLS

func (e *Engine) RunServeTLS(listener net.Listener, certFile string, keyFile string) (err error)

func (*Engine) RunServer

func (e *Engine) RunServer(listener net.Listener) (err error)

func (*Engine) RunTLS

func (e *Engine) RunTLS(addr, certFile, keyFile string) (err error)

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Error represents an error that occurred while handling a request.

func NewError

func NewError(code int, message ...string) *Error

NewError creates a new Error instance with an optional message

func (*Error) Error

func (e *Error) Error() string

type Handler

type Handler any // func(*Ctx[, T]) -> T | (int, T) | (T, error)

type Response

type Response struct {
	Event   string `json:"event"`
	Status  int    `json:"status"`
	Code    int    `json:"code"`
	Count   int    `json:"count"`
	Message string `json:"msg"`
	Data    any    `json:"data"`
}

func (*Response) SetCode

func (r *Response) SetCode(code any) *Response

SetCode 设置 code

func (*Response) SetData

func (r *Response) SetData(data any) *Response

SetData 设置数据

func (*Response) SetEvent

func (r *Response) SetEvent(event string) *Response

SetEvent 设置事件

func (*Response) SetFailData

func (r *Response) SetFailData(data any) *Response

SetFailData 设置失败数据

func (*Response) SetMessage

func (r *Response) SetMessage(msg any) *Response

SetMessage 设置消息

func (*Response) SetStatus

func (r *Response) SetStatus(status any, code ...any) *Response

SetStatus 设置 status, code

type Route

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

func (*Route) GET

func (r *Route) GET(path string, handlers ...Handler) Router

func (*Route) Group

func (r *Route) Group(path string, handlers ...Handler) Router

func (*Route) Handle

func (r *Route) Handle(method string, path string, handlers ...Handler) Router

func (*Route) POST

func (r *Route) POST(path string, handlers ...Handler) Router

func (*Route) Static

func (r *Route) Static(path, root string) Router

func (*Route) Use

func (r *Route) Use(args ...Handler) Router

type Router

type Router interface {
	Use(args ...Handler) Router
	GET(path string, handlers ...Handler) Router
	POST(path string, handlers ...Handler) Router
	Group(path string, handlers ...Handler) Router
	Handle(method, path string, handlers ...Handler) Router
	Static(path, root string) Router
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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