core

package module
v2.0.26 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2024 License: MIT Imports: 52 Imported by: 0

README

Core web framework v2.0

Core is used for rapid development of enterprise application in Go, including RESTful APIs, web apps and backend services.

It is inspired by Tornado, Sinatra and Koa(node.js). Core has some Go-specific features such as interfaces and struct embedding.

  • auto register router
  • koa(node.js) develop style
  • simple light framework

example/work

auto register router mode


example/work > 

     > handler > handler.go

     > models  > models.go
    
     > main.go
    
     > config.yaml

handler.go file
// define handler
type Handler struct {
	core.Handler // must extends core.Handler
}

// Put create user
// put /
//
// {
//     "user": "username",
//     "password": "password"
// }
// route: PUT / > main.Handler.Put
func (Handler) Put(c core.Ctx) {
	form := models.User{}
    // read put post body data
	if err := c.ReadBody(&form); err != nil {
		c.ToJSON(nil, err)
		return
	}
	c.ToJSON(form, form.Save())
}

// GetParam get some param
// 
// get param id planA
// @param: uid.UID userId
// route: GET /detail/:param > main.Handler.GetDetailParam
func (Handler) GetDetailParam(c core.Ctx) {
    // get param
	uid, err := c.ParamsUid("param")
	if err != nil {
		c.ToJSON(nil, err)
		return
	}
	c.ToJSON(models.UserById(uid))
}

// Get_id get id param
// 
// get param id planB
// @id: uid.UID userID
// route: GET /:id > main.Handler.Get_id
func (Handler) Get_id(c core.Ctx) {
    // get uri path id
	uid, err := c.ParamsUid("id")
	if err != nil {
		c.ToJSON(nil, err)
		return
	}
	c.ToJSON(models.UserById(uid))
}


// Get get user list
// get /
//
// route: GET / > main.Handler.Get
func (Handler) Get(c core.Ctx) {
	c.ToJSON(models.UserPage())
}

func init() {
    // auto register handler
	core.RegHandle(new(Handler))
}
models.go file
type User struct {
	core.Model
	User     string `json:"user" gorm:"size:32"`
	Password string `json:"password" gorm:"size:96"`
}

func (m *User) Save() error {
	return DB.Save(m).Error
}

func UserById(id uid.UID) (user User, err error) {
	err = DB.First(&user, "id = ?", id).Error
	return
}

func UserPage() (any, error) {
	result := make([]User, 0)
	err := core.Find(&result)
	return result, err
}

func InitDB() {
	DB = core.Conn()
	DB.AutoMigrate(&User{})
}

var (
	DB *core.DB
)

main.go
func main() {
	app := core.New(core.LoadConfigFile("config.yaml"))
	models.InitDB()
	app.Listen()
}
config.yaml
debug: true
network: tcp4
listen: 8080
restful:
    data: data
    status: success
    message: msg

prefork: false

database:
    type: sqlite3
    dsn: dat

rust-client test file

@baseURL = http://localhost:8080
@contentType = application/json

### add user
PUT {{baseURL}} HTTP/1.1
Content-Type: {{contentType}}

{
    "user": "x",
    "password": "x"
}

### get user
GET {{baseURL}}/SYMFRZ4O65T9

### get user list
GET {{baseURL}}

register user test

@baseURL = http://localhost:8080
@contentType = application/json

### add user
PUT {{baseURL}} HTTP/1.1
Content-Type: {{contentType}}

{
    "user": "x",
    "password": "x"
}

Response

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Request-Id: ZO6I1Y8F0PTJ
Date: Sun, 06 Aug 2023 14:26:17 GMT
Content-Length: 166
Connection: close

{
  "data": {
    "id": "SYMFRZ4O65T9",
    "created_at": "0001-01-01T00:00:00Z",
    "updated_at": "2023-08-06T22:26:17.440943+08:00",
    "user": "x",
    "password": "x"
  },
  "msg": "ok",
  "success": true
}

get user by id

### get user
GET {{baseURL}}/SYMFRZ4O65T9
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Request-Id: 4M5J3HZA6LSK
Date: Sun, 06 Aug 2023 14:23:27 GMT
Content-Length: 178
Connection: close

{
  "data": {
    "id": "SYMFRZ4O65T9",
    "created_at": "2023-08-06T21:53:08.206575+08:00",
    "updated_at": "2023-08-06T22:21:18.325284+08:00",
    "user": "x",
    "password": "x"
  },
  "msg": "ok",
  "success": true
}

get user list

### get user list
GET {{baseURL}}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Request-Id: BL6ALTKQTLZB
Date: Sun, 06 Aug 2023 14:24:01 GMT
Content-Length: 326
Connection: close

{
  "data": [
    {
      "id": "05HG0DIM522N",
      "created_at": "2023-08-06T21:49:34.735412+08:00",
      "updated_at": "2023-08-06T21:49:34.735412+08:00",
      "user": "xs",
      "password": "xs"
    },
    {
      "id": "SYMFRZ4O65T9",
      "created_at": "2023-08-06T21:53:08.206575+08:00",
      "updated_at": "2023-08-06T22:21:18.325284+08:00",
      "user": "x",
      "password": "x"
    }
  ],
  "msg": "ok",
  "success": true
}

Documentation

Index

Constants

View Source
const (
	MIMETextXML         = "text/xml"
	MIMETextHTML        = "text/html"
	MIMETextPlain       = "text/plain"
	MIMETextJavaScript  = "text/javascript"
	MIMEApplicationXML  = "application/xml"
	MIMEApplicationJSON = "application/json"
	// Deprecated: use MIMETextJavaScript instead
	MIMEApplicationJavaScript = "application/javascript"
	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"
	// Deprecated: use MIMETextJavaScriptCharsetUTF8 instead
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	CharsetUTF8    = "utf-8"
	CharsetGBK     = "gbk"
	CharsetGB2312  = "gb2312"
	CharsetGB18030 = "gb18030"
)
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 https://github.com/nginx/nginx/blob/67d2a9541826ecd5db97d604f23460210fd3e517/conf/mime.types 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.

View Source
const (
	DefaultDateFormat     = "2006-01-02"
	DefaultDateTimeFormat = "2006-01-02 15:04"
)
View Source
const (
	ConstraintInt             = "int"
	ConstraintBool            = "bool"
	ConstraintFloat           = "float"
	ConstraintAlpha           = "alpha"
	ConstraintGUID            = "guid"
	ConstraintMinLen          = "minLen"
	ConstraintMaxLen          = "maxLen"
	ConstraintLen             = "len"
	ConstraintBetweenLen      = "betweenLen"
	ConstraintMinLenLower     = "minlen"
	ConstraintMaxLenLower     = "maxlen"
	ConstraintBetweenLenLower = "betweenlen"
	ConstraintMin             = "min"
	ConstraintMax             = "max"
	ConstraintRange           = "range"
	ConstraintDatetime        = "datetime"
	ConstraintRegex           = "regex"
)

Route Constraints

View Source
const CoreHeader = `` /* 185-byte string literal not displayed */
View Source
const VERSION = "v2.0.0"

Variables

View Source
var (
	MethodUse     = Methods[METHOD_USE]
	MethodGet     = Methods[METHOD_GET]
	MethodPost    = Methods[METHOD_POST]
	MethodHead    = Methods[METHOD_HEAD]
	MethodPut     = Methods[METHOD_PUT]
	MethodDelete  = Methods[METHOD_DELETE]
	MethodOptions = Methods[METHOD_OPTIONS]
	MethodConnect = Methods[METHOD_CONNECT]
	MethodTrace   = Methods[METHOD_TRACE]
	MethodPatch   = Methods[METHOD_PATCH]
)
View Source
var (
	ErrDataTypeNotSupport       = errors.New("dataType does not support")
	ErrNoConfig                 = errors.New("field global configuration not found")
	ErrLayoutCalledUnexpectedly = errors.New("layout called unexpectedly")
)
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

View Source
var DefaultErrorWriter io.Writer = os.Stderr

DefaultErrorWriter is the default io.Writer used by Gin to debug errors

View Source
var (
	DefaultOutput = io.Discard
)
View Source
var (
	Methods = []string{
		"GET",
		"POST",
		"HEAD",
		"PUT",
		"DELETE",
		"OPTIONS",
		"CONNECT",
		"TRACE",
		"PATCH",
		"USE",
	}
)
View Source
var UuidNil = UUID{uuid.Nil}

Functions

func Contains

func Contains[S ~[]E, E comparable](s S, v E) bool

func D

func D(f string, args ...any)

func DBType

func DBType() string

func DefaultErrorHandler

func DefaultErrorHandler(c Ctx, err error) error

func Delete

func Delete[S ~[]E, E any](s S, i, j int) S

Delete removes the elements s[i:j] from s, returning the modified slice. Delete panics if s[i:j] is not a valid slice of s. Delete is O(len(s)-j), so if many items must be deleted, it is better to make a single call deleting them all together than to delete one at a time. Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those elements contain pointers you might consider zeroing those elements so that objects they reference can be garbage collected.

func Dir

func Dir(root string, listDirectory bool) http.FileSystem

Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.

func Dump

func Dump(v ...any)

Dump 打印数据信息

func EqualFold

func EqualFold[S byteSeq](b, s S) bool

EqualFold tests ascii strings or bytes for equality case-insensitively

func Erro

func Erro(f string, args ...any)

error logger

func Exists

func Exists(absDir string) bool

Exists check file or path exists

func Find

func Find(out any, args ...any) error

Find find all data record max 10000

func FixURI

func FixURI(pre, src, tag string) string

func GetTrimmedParam

func GetTrimmedParam(param string) string

GetTrimmedParam trims the ':' & '?' from a string

func Index

func Index[S ~[]E, E comparable](s S, v E) int

func Info

func Info(f string, args ...any)

info logger

func IsChild

func IsChild() bool

IsChild determines if the current process is a child of Prefork

func IsInvalidLengthError added in v2.0.10

func IsInvalidLengthError(err error) bool

IsInvalidLengthError is matcher function for custom error invalidLengthError

func LocalIP

func LocalIP() (ip net.IP, err error)

func Log

func Log(f string, args ...any)

func MIME

func MIME(extension string) (mime string)

GetMIME returns the content-type of a file extension

func MakePath

func MakePath(name, dst string, args ...any) (string, string, error)

MakePath make dir

path = {root}/{dst}/{id}
@param
name string filename
dst string dst path
root string root path optional
id   path optional type uid.UID, int, uint, int64,uint64
rename bool optional
return relPath, absPath

 `
   MakePath("favicon.png", "/images")
   (string) relpath "/images/10/favicon.png"
   (string) abspath "/images/10/favicon.png"

   MakePath("favicon.png", "/images", "/static")
   (string) relpath "/images/10/5hsbkthaadld/favicon.png"
   (string) abspath "/static/images/10/5hsbkthaadld/favicon.png"

   MakePath("favicon.png", "/images", "/static", uid.New())
   (string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
   (string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
              👇filename    👇dst      👇root     👇id      👇rename
   MakePath("favicon.png", "/images", "/static", uid.New(), true)
   (string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
   (string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
 `

func RegHandle

func RegHandle(mods ...any)

func RegisterModule

func RegisterModule(inst module)

func RemoveEscapeChar

func RemoveEscapeChar(word string) string

RemoveEscapeChar remove escape characters

func RoutePatternMatch

func RoutePatternMatch(path, pattern string, cfg ...Options) bool

RoutePatternMatch checks if a given path matches a core route pattern.

func SaveConfigFile

func SaveConfigFile(conf map[string]any) error

func StatusMessage

func StatusMessage(status int) string

StatusMessage returns the correct message for the provided HTTP statuscode

func Warn

func Warn(f string, args ...any)

warning logger

Types

type Array

type Array []any

Array 数组类型

func (Array) FindHandle

func (d Array) FindHandle(handle, value string) Map

func (Array) GormDataType

func (Array) GormDataType() string

GormDataType schema.Field DataType

func (*Array) Scan

func (d *Array) Scan(src any) error

Scan 数据驱动接口

func (Array) String

func (d Array) String() []string

Strings 转换为 []string

func (Array) StringsJoin

func (d Array) StringsJoin(sp string) string

StringsJoin 链接为字符串

func (Array) Value

func (d Array) Value() (driver.Value, error)

Value 数据驱动接口

type BaseCtx

type BaseCtx struct {
	W ResponseWriter
	R *http.Request
	// contains filtered or unexported fields
}

func (*BaseCtx) Abort

func (c *BaseCtx) Abort(args ...any) Ctx

func (*BaseCtx) Accepts

func (c *BaseCtx) Accepts(offers ...string) string

Accepts checks if the specified extensions or content types are acceptable.

func (*BaseCtx) AcceptsCharsets

func (c *BaseCtx) AcceptsCharsets(offers ...string) string

AcceptsCharsets checks if the specified charset is acceptable.

func (*BaseCtx) AcceptsEncodings

func (c *BaseCtx) AcceptsEncodings(offers ...string) string

AcceptsEncodings checks if the specified encoding is acceptable.

func (*BaseCtx) AcceptsLanguages

func (c *BaseCtx) AcceptsLanguages(offers ...string) string

AcceptsLanguages checks if the specified language is acceptable.

func (*BaseCtx) Append

func (c *BaseCtx) Append(key string, values ...string) Ctx

Append values to the same key, separated by commas

c.Append("Vary", "Accept-Encoding", "Accept", "X-Requested-With")

Response Header:

Vary: Accept-Encoding, Accept, X-Requested-With

func (*BaseCtx) Cookie

func (c *BaseCtx) Cookie(cookie *http.Cookie)

Cookie sets a cookie by passing a cookie struct.

func (*BaseCtx) Cookies

func (c *BaseCtx) Cookies(name string) (string, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.

func (*BaseCtx) Core

func (c *BaseCtx) Core() *Core

Core implements Ctx.

func (*BaseCtx) File

func (c *BaseCtx) File(filePath string)

File implements Ctx.

func (*BaseCtx) FileAttachment

func (c *BaseCtx) FileAttachment(filepath, filename string)

FileAttachment writes the specified file into the body stream in an efficient way On the client side, the file will typically be downloaded with the given filename

func (*BaseCtx) FileFromFS

func (c *BaseCtx) FileFromFS(filepath string, fs http.FileSystem)

FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.

func (*BaseCtx) Flush

func (c *BaseCtx) Flush(data any, statusCode ...int) error

Flush response dat and break

func (*BaseCtx) FormFile

func (c *BaseCtx) FormFile(key string) (*multipart.FileHeader, error)

FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.

func (*BaseCtx) FormValue added in v2.0.1

func (c *BaseCtx) FormValue(key string, def ...string) string

FormValue support old version

func (*BaseCtx) FormValues added in v2.0.1

func (c *BaseCtx) FormValues(key string, def ...[]string) []string

FormValues returns a slice of strings for a given query key.

func (*BaseCtx) Format

func (c *BaseCtx) Format(body any) error

Format performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format. If the header is not specified or there is no proper format, text/plain is used.

func (*BaseCtx) FromValueInt added in v2.0.2

func (c *BaseCtx) FromValueInt(key string, def ...int) int

func (*BaseCtx) FromValueUUID added in v2.0.2

func (c *BaseCtx) FromValueUUID(key string, def ...UUID) UUID

func (*BaseCtx) FromValueUid added in v2.0.2

func (c *BaseCtx) FromValueUid(key string, def ...uid.UID) uid.UID

func (*BaseCtx) Get

func (c *BaseCtx) Get(key string) (val any, ok bool)

Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)

func (*BaseCtx) GetAs

func (c *BaseCtx) GetAs(key string, v any) error

GetAs retrieve struct like c.Get("user").(User)

> Experimental function, problem unknown

func (*BaseCtx) GetBool

func (c *BaseCtx) GetBool(key string) (value bool)

GetBool returns the value associated with the key as a boolean.

func (*BaseCtx) GetDuration

func (c *BaseCtx) GetDuration(key string) (d time.Duration)

GetDuration returns the value associated with the key as a duration.

func (*BaseCtx) GetFloat64

func (c *BaseCtx) GetFloat64(key string, def ...float64) (value float64)

GetFloat64 returns the value associated with the key as a float64.

func (*BaseCtx) GetHeader

func (c *BaseCtx) GetHeader(key string, defaultValue ...string) string

GetHeader get Request header

func (*BaseCtx) GetInt

func (c *BaseCtx) GetInt(key string, def ...int) (i int)

GetInt returns the value associated with the key as an integer.

func (*BaseCtx) GetInt64

func (c *BaseCtx) GetInt64(key string, def ...int64) (i int64)

GetInt64 returns the value associated with the key as an integer.

func (*BaseCtx) GetMap

func (c *BaseCtx) GetMap(key string, def ...map[string]any) (value map[string]any)

GetMap returns the value associated with the key as a map of interfaces.

> return map[string]any

func (*BaseCtx) GetMapString

func (c *BaseCtx) GetMapString(key string, def ...map[string]string) (value map[string]string)

GetMapString returns the value associated with the key as a map of strings.

> return map[string]string

func (*BaseCtx) GetMapStringSlice

func (c *BaseCtx) GetMapStringSlice(key string, def ...map[string][]string) (value map[string][]string)

GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.

> return map[string][]string

func (*BaseCtx) GetParamInt added in v2.0.2

func (c *BaseCtx) GetParamInt(key string, defaultValue ...int) (int, error)

GetParamInt get int param, return -1 if failed

func (*BaseCtx) GetParamUid added in v2.0.2

func (c *BaseCtx) GetParamUid(key string, defaultValue ...uid.UID) (uid.UID, error)

GetParamUid get uid.UID param, return uid.Nil if failed

func (*BaseCtx) GetStatus

func (c *BaseCtx) GetStatus() int

GetStatus get response statusCode

func (*BaseCtx) GetString

func (c *BaseCtx) GetString(key string, def ...string) (value string)

GetString returns the value associated with the key as a string.

func (*BaseCtx) GetStrings

func (c *BaseCtx) GetStrings(key string, def ...[]string) (value []string)

GetStrings String Slice returns the value associated with the key as a slice of strings.

func (*BaseCtx) GetTime

func (c *BaseCtx) GetTime(key string) (t time.Time)

GetTime returns the value associated with the key as time.

func (*BaseCtx) GetUint

func (c *BaseCtx) GetUint(key string, def ...uint) (i uint)

GetUint returns the value associated with the key as an integer.

func (*BaseCtx) GetUint64

func (c *BaseCtx) GetUint64(key string, def ...uint64) (i uint64)

GetUint64 returns the value associated with the key as an integer.

func (*BaseCtx) JSON

func (c *BaseCtx) JSON(data any) error

func (*BaseCtx) JSONP

func (c *BaseCtx) JSONP(data any, callback ...string) error

func (*BaseCtx) Method

func (c *BaseCtx) Method() string

func (*BaseCtx) Next

func (c *BaseCtx) Next() error

func (*BaseCtx) Params

func (c *BaseCtx) Params(key string, defaultValue ...string) string

func (*BaseCtx) ParamsInt

func (c *BaseCtx) ParamsInt(key string, defaultValue ...int) (int, error)

ParamsInt get int param, return -1 if failed

func (*BaseCtx) ParamsUid

func (c *BaseCtx) ParamsUid(key string, defaultValue ...uid.UID) (uid.UID, error)

ParamsUid get uid.UID param, return uid.Nil if failed

func (*BaseCtx) ParamsUuid added in v2.0.2

func (c *BaseCtx) ParamsUuid(key string, defaultValue ...UUID) (UUID, error)

ParamsUid get uid.UID param, return uid.Nil if failed

func (*BaseCtx) Path

func (c *BaseCtx) Path() string

func (*BaseCtx) Query

func (c *BaseCtx) Query(key string, def ...string) string

FormValue Get query

key string
def string default val optional

> GET /?name=Jack&id=

`
  name := c.FormValue("name")  // name = Jack
  id := c.FormValue("id", "1") // id = 1 Because the default value is used
`

func (*BaseCtx) Querys

func (c *BaseCtx) Querys(key string, def ...[]string) []string

func (*BaseCtx) ReadBody

func (c *BaseCtx) ReadBody(out any) error

ReadBody binds the request body to a struct. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data If none of the content types above are matched, it will return a ErrUnprocessableEntity error

out any MIMEApplicationForm MIMEMultipartForm MIMETextXML must struct

func (*BaseCtx) Redirect

func (c *BaseCtx) Redirect(to string, stCode ...int)

func (*BaseCtx) RedirectJS

func (c *BaseCtx) RedirectJS(to string, msg ...string)

func (*BaseCtx) RemoteIP

func (c *BaseCtx) RemoteIP() net.IP

RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). It also checks if the remoteIP is a trusted proxy or not. In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks

func (*BaseCtx) RemoveCookie

func (c *BaseCtx) RemoveCookie(name, path string, dom ...string)

func (*BaseCtx) Render added in v2.0.4

func (c *BaseCtx) Render(f string, bind ...any) error

func (*BaseCtx) Request

func (c *BaseCtx) Request() *http.Request

Request implements Ctx.

func (*BaseCtx) Response

func (c *BaseCtx) Response() ResponseWriter

ResponseWriter implements Ctx.

func (*BaseCtx) SaveFile

func (c *BaseCtx) SaveFile(key, dst string, args ...any) (relpath, abspath string, err error)

SaveFile upload file save to a folder

path = {root}/{dst}/{id}
@param
name string filename
dst string dst path
root string root path optional
id   path optional type uid.UID, int, uint, int64,uint64
rename bool optional
return relPath, absPath

   c.SaveFile("file", "/images")
   (string) relpath "/images/10/favicon.png"
   (string) abspath "/images/10/favicon.png"

   c.SaveFile("file", "/images", "./static")
   (string) relpath "/images/10/5hsbkthaadld/favicon.png"
   (string) abspath "/static/images/10/5hsbkthaadld/favicon.png"

   c.SaveFile("file", "/images", "./static", uid.New())
   (string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
   (string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
              👇file    👇dst      👇root     👇id      👇rename
   c.SaveFile("file", "/images", "./static", uid.New(), true)
   (string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
   (string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"

func (*BaseCtx) SaveFiles

func (c *BaseCtx) SaveFiles(key, dst string, args ...any) (rel Array, err error)

SaveFiles like SaveFile

@params key string MultipartForm key name : files dst string static to ./static more args see SaveFile

rel, err := c.SaveFiles("files", "static", true)

return relative url path rel is

return []string {
	"/static/09/wjejwifx.jpg",
	"/static/09/wjejwifx.jpg",
	"/static/09/wjejwifx.jpg",
}

func (*BaseCtx) Send

func (c *BaseCtx) Send(buf []byte) error

Send send []byte to client

func (*BaseCtx) SendStatus

func (c *BaseCtx) SendStatus(code int, msg ...string) error

func (*BaseCtx) SendString

func (c *BaseCtx) SendString(str ...any) error

func (*BaseCtx) Set

func (c *BaseCtx) Set(key string, val any)

set locals var

func (*BaseCtx) SetCookie

func (c *BaseCtx) SetCookie(name, value string, exp time.Time, path string, args ...any)

SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*BaseCtx) SetHeader

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

func (*BaseCtx) StartAt

func (c *BaseCtx) StartAt(t ...time.Time) time.Time

func (*BaseCtx) Status

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

func (*BaseCtx) Stream added in v2.0.4

func (c *BaseCtx) Stream(step func(w io.Writer) bool) bool

Stream sends a streaming response and returns a boolean indicates "Is client disconnected in middle of stream"

func (*BaseCtx) ToJSON

func (c *BaseCtx) ToJSON(data any, msg ...any) error

func (*BaseCtx) ToJSONCode

func (c *BaseCtx) ToJSONCode(data any, msg ...any) error

func (*BaseCtx) Type

func (c *BaseCtx) Type(extension string, charset ...string) Ctx

Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

func (*BaseCtx) Vars added in v2.0.22

func (c *BaseCtx) Vars() Map

func (*BaseCtx) Vary

func (c *BaseCtx) Vary(fields ...string) Ctx

Vary add the given header field to the vary response header

c.Vary("Accept-Encoding", "Accept", "X-Requested-With")

Response Header:

Vary: Accept-Encoding, Accept, X-Requested-With

func (*BaseCtx) ViewReload added in v2.0.4

func (c *BaseCtx) ViewReload()

func (*BaseCtx) ViewTheme added in v2.0.4

func (c *BaseCtx) ViewTheme(theme string)

ViewTheme 使用模版风格

func (*BaseCtx) XML

func (c *BaseCtx) XML(data any) error

XML converts any interface or string to XML. This method also sets the content header to application/xml.

type Constraint

type Constraint struct {
	ID            TypeConstraint
	RegexCompiler *regexp.Regexp
	Data          []string
}

func (*Constraint) CheckConstraint

func (c *Constraint) CheckConstraint(param string) bool

type Core

type Core struct {
	*http.Server

	Conf Options

	Debug bool

	RequestMethods []string

	ErrorHandler ErrorHandler

	Ctx context.Context

	MaxMultipartMemory int64

	Views view.IEngine
	// contains filtered or unexported fields
}

func New

func New(options ...Options) *Core

func (*Core) AcquireCtx

func (app *Core) AcquireCtx(w http.ResponseWriter, r *http.Request) Ctx

func (*Core) Add

func (app *Core) Add(methods []string, path string, handler any, middleware ...any) Router

func (*Core) AddHandle

func (app *Core) AddHandle(methods []string, uri string, group *Group, handler any, middware ...HandlerFunc) Router

func (*Core) Connect

func (app *Core) Connect(path string, handler any, middleware ...any) Router

func (*Core) Delete

func (app *Core) Delete(path string, handler any, middleware ...any) Router

func (*Core) Get

func (app *Core) Get(path string, handler any, middleware ...any) Router

func (*Core) GetModule

func (app *Core) GetModule(id string) (ModuleInfo, error)

func (*Core) Group

func (app *Core) Group(prefix string, handlers ...any) Router

func (*Core) Head

func (app *Core) Head(path string, handler any, middleware ...any) Router

func (*Core) Listen

func (app *Core) Listen(port ...any) error

func (*Core) Options

func (app *Core) Options(path string, handler any, middleware ...any) Router

func (*Core) Patch

func (app *Core) Patch(path string, handler any, middleware ...any) Router

func (*Core) Post

func (app *Core) Post(path string, handler any, middleware ...any) Router

func (*Core) Put

func (app *Core) Put(path string, handler any, middleware ...any) Router

func (*Core) ReleaseCtx

func (app *Core) ReleaseCtx(c Ctx)

func (*Core) Serve

func (app *Core) Serve(ln net.Listener) error

func (*Core) ServeHTTP

func (app *Core) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Core) Static

func (app *Core) Static(relativePath, root string) Router

func (*Core) StaticFS

func (app *Core) StaticFS(relativePath string, fs http.FileSystem) Router

func (*Core) StaticFile

func (app *Core) StaticFile(relativePath, dirname string) Router

StaticFile static file

app.StaticFile("/favicon.ico", "./favicon.ico")

func (*Core) StaticFileFS

func (app *Core) StaticFileFS(relativePath, dirname string, fs http.FileSystem) Router

StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead..

app.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false})

func (*Core) Trace

func (app *Core) Trace(path string, handler any, middleware ...any) Router

func (*Core) Use

func (app *Core) Use(fn ...any) Router

type Ctx

type Ctx interface {
	Response() ResponseWriter                                              // Response() return http.ResponseWriter
	Request() *http.Request                                                // Request() return *http.Request
	RedirectJS(to string, msg ...string)                                   // use js redirect
	Redirect(to string, stCode ...int)                                     // base redirect
	RemoteIP() net.IP                                                      // remote client ip
	SetCookie(name, value string, exp time.Time, path string, args ...any) // set cookie
	RemoveCookie(name, path string, dom ...string)                         // remove some cookie
	Cookie(cookie *http.Cookie)                                            // set cookie with cookie object
	Cookies(name string) (string, error)                                   // get some cookie
	ReadBody(out any) error                                                // read put post any request body to struct or map
	Next() error                                                           // next HandlerFunc
	Path() string                                                          // return http.Request.URI.path

	Send(buf []byte) error                                                      // send []byte data
	SendString(msg ...any) error                                                // send string to body
	SendStatus(code int, msg ...string) error                                   // send status to client, options msg with display
	SetHeader(key string, value string)                                         // set response header
	GetHeader(key string, defaultValue ...string) string                        // get request header
	Method() string                                                             // return method e.g: GET,POST,PUT,DELETE,OPTION,HEAD...
	GetStatus() int                                                             // get response status
	Status(code int) Ctx                                                        // set response status
	Core() *Core                                                                // return app(*Core)
	Abort(args ...any) Ctx                                                      // Deprecated: As of v2.0.0, this function simply calls Ctx.Format.
	JSON(any) error                                                             // send json
	JSONP(data any, callback ...string) error                                   // send jsonp
	ToJSON(data any, msg ...any) error                                          // send json with status
	ToJSONCode(data any, msg ...any) error                                      // send have code to json
	StartAt(t ...time.Time) time.Time                                           // set ctx start time if t set, else get start at
	Params(key string, defaultValue ...string) string                           // get Param data e.g c.Param("param")
	ParamsUid(key string, defaultValue ...uid.UID) (uid.UID, error)             // get Param UID type, return uid.Nil if failed
	ParamsUuid(key string, defaultValue ...UUID) (UUID, error)                  // get Param UID type, return uid.Nil if failed
	ParamsInt(key string, defaultValue ...int) (int, error)                     // get Param int type, return -1 if failed
	GetParamUid(key string, defaultValue ...uid.UID) (uid.UID, error)           // get param uid.UID, return uid.Nil if failed
	GetParamInt(key string, defaultValue ...int) (int, error)                   // get param int, return -1 if failed
	File(filePath string)                                                       // send file
	FileAttachment(filepath, filename string)                                   // send file attachment
	FileFromFS(filePath string, fs http.FileSystem)                             // send file from FS
	Append(key string, values ...string) Ctx                                    // append response header
	Vary(fields ...string) Ctx                                                  // set response vary
	SaveFile(key, dst string, args ...any) (relpath, abspath string, err error) // upload some one file
	SaveFiles(key, dst string, args ...any) (rel Array, err error)              // upload multi-file
	Query(key string, def ...string) string                                     // get request query string like ?id=12345
	Querys(key string, def ...[]string) []string                                // like query, but return []string values
	FormValue(key string, def ...string) string                                 // like Query support old version
	FromValueInt(key string, def ...int) int                                    // parse form value to int
	FromValueUid(key string, def ...uid.UID) uid.UID                            // parse form value to uid
	FromValueUUID(key string, def ...UUID) UUID                                 // parse form value to uuid
	FormValues(key string, def ...[]string) []string                            // like Querys
	Flush(data any, statusCode ...int) error                                    // flush
	Accepts(offers ...string) string                                            // Accepts checks if the specified extensions or content types are acceptable.
	AcceptsCharsets(offers ...string) string                                    // AcceptsCharsets checks if the specified charset is acceptable.
	AcceptsEncodings(offers ...string) string                                   // AcceptsEncodings checks if the specified encoding is acceptable.
	AcceptsLanguages(offers ...string) string                                   // AcceptsLanguages checks if the specified language is acceptable.
	Format(body any) error                                                      // Format performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format. If the header is not specified or there is no proper format, text/plain is used.
	Type(extension string, charset ...string) Ctx                               // 发送 response content-type
	XML(data any) error                                                         // output xml
	Set(key string, val any)
	Get(key string) (val any, ok bool)
	GetString(key string, def ...string) (value string)
	GetBool(key string) (value bool)
	GetInt(key string, def ...int) (i int)
	GetInt64(key string, def ...int64) (i int64)
	GetUint(key string, def ...uint) (i uint)
	GetUint64(key string, def ...uint64) (i uint64)
	GetFloat64(key string, def ...float64) (value float64)
	GetTime(key string) (t time.Time)
	GetDuration(key string) (d time.Duration)
	GetStrings(key string, def ...[]string) (value []string)
	GetMap(key string, def ...map[string]any) (value map[string]any)
	GetMapString(key string, def ...map[string]string) (value map[string]string)
	GetMapStringSlice(key string, def ...map[string][]string) (value map[string][]string)
	GetAs(key string, v any) error
	Vars() Map
	Stream(step func(w io.Writer) bool) bool
	ViewReload() // set view reload
	Render(f string, bind ...any) error
	// contains filtered or unexported methods
}

type DB

type DB = gorm.DB

func Conn

func Conn() *DB

func NewModel

func NewModel(conf Options, debug, colorful bool) (*DB, error)

func Where

func Where(whr *Map, db ...*DB) (*DB, int, int)

Where build page query

whr *Map
db  *DB optional
return *DB, pos, lmt

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

Error makes it compatible with the `error` interface.

type ErrorHandler

type ErrorHandler func(Ctx, error) error

type Group

type Group struct {
	*Core

	Prefix string
	// contains filtered or unexported fields
}

func (*Group) Add

func (g *Group) Add(methods []string, path string, handler any, middleware ...any) Router

Add allows you to specify multiple HTTP methods to register a route.

func (*Group) Connect

func (g *Group) Connect(path string, handler any, middleware ...any) Router

func (*Group) Delete

func (g *Group) Delete(path string, handler any, middleware ...any) Router

func (*Group) Get

func (g *Group) Get(path string, handler any, middleware ...any) Router

Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.

func (*Group) Head

func (g *Group) Head(path string, handler any, middleware ...any) Router

func (*Group) Name

func (g *Group) Name(name string) Router

func (*Group) Options

func (g *Group) Options(path string, handler any, middleware ...any) Router

func (*Group) Patch

func (g *Group) Patch(path string, handler any, middleware ...any) Router

func (*Group) Post

func (g *Group) Post(path string, handler any, middleware ...any) Router

func (*Group) Put

func (g *Group) Put(path string, handler any, middleware ...any) Router

func (*Group) Trace

func (g *Group) Trace(path string, handler any, middleware ...any) Router

func (*Group) Use

func (g *Group) Use(fn ...any) Router

Use registers a middleware route that will match requests with the provided prefix (which is optional and defaults to "/"). Also, you can pass another app instance as a sub-router along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Use. The core error handler and any of the core sub apps are added to the application's error handlers to be invoked on errors that happen within the prefix route.

	app.Use(func(c core.Ctx) error {
	     return c.Next()
	})
	app.Use("/api", func(c core.Ctx) error {
	     return c.Next()
	})
	app.Use("/api", handler, func(c core.Ctx) error {
	     return c.Next()
	})
 	subApp := core.New()
	app.Use("/mounted-path", subApp)

This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...

type Handler

type Handler struct {
	Handlers map[string]any // record callable handle

	ID string
	// contains filtered or unexported fields
}

func (*Handler) Core

func (h *Handler) Core(app ...*Core) *Core

func (*Handler) HandName

func (h *Handler) HandName(name ...string) string

func (*Handler) Init

func (h *Handler) Init()

func (*Handler) Prefix

func (h *Handler) Prefix(prefix ...string) string

func (*Handler) Preload

func (h *Handler) Preload(c Ctx) error

func (*Handler) PushHandler

func (h *Handler) PushHandler(method, path string)

type HandlerFun

type HandlerFun = func(Ctx)

type HandlerFunc

type HandlerFunc = func(Ctx) error

func CustomRecoveryWithWriter

func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc

CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.

func Logger

func Logger(conf ...LoggerConfig) HandlerFunc

func Recovery

func Recovery() HandlerFunc

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

func RecoveryWithWriter

func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc

RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.

type HandlerFuncs

type HandlerFuncs []HandlerFunc

type HandlerNormal

type HandlerNormal = func(w http.ResponseWriter, r *http.Request)

type Int added in v2.0.24

type Int int64

func (Int) GormDataType added in v2.0.24

func (Int) GormDataType() string

GormDataType schema.Field DataType

func (Int) Int added in v2.0.24

func (m Int) Int() int

转换结果为标准的 int

func (Int) Int64 added in v2.0.24

func (m Int) Int64() int64

转换结果为标准的 int64

func (*Int) UnmarshalJSON added in v2.0.24

func (m *Int) UnmarshalJSON(data []byte) error

type InvalidUnmarshalError

type InvalidUnmarshalError struct {
	Type reflect.Type
}

An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)

func (*InvalidUnmarshalError) Error

func (e *InvalidUnmarshalError) Error() string

type JSON added in v2.0.24

type JSON json.RawMessage

func (JSON) GormDBDataType added in v2.0.24

func (JSON) GormDBDataType(db *gorm.DB, field *schema.Field) string

func (JSON) GormDataType added in v2.0.24

func (JSON) GormDataType() string

GormDataType gorm common data type

func (JSON) GormValue added in v2.0.24

func (js JSON) GormValue(ctx context.Context, db *gorm.DB) clause.Expr

func (JSON) MarshalJSON added in v2.0.24

func (j JSON) MarshalJSON() ([]byte, error)

MarshalJSON to output non base64 encoded []byte

func (*JSON) Scan added in v2.0.24

func (j *JSON) Scan(value interface{}) error

Scan scan value into Jsonb, implements sql.Scanner interface

func (JSON) String added in v2.0.24

func (j JSON) String() string

func (*JSON) UnmarshalJSON added in v2.0.24

func (j *JSON) UnmarshalJSON(b []byte) error

UnmarshalJSON to deserialize []byte

func (JSON) Value added in v2.0.24

func (j JSON) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type LoggerConfig

type LoggerConfig struct {
	ForceColor bool
	Debug      bool
	Output     io.Writer
	App        *Core
}

type Map

type Map map[string]any

func (Map) Contains added in v2.0.15

func (d Map) Contains(k string) bool

func (Map) GetBool

func (d Map) GetBool(k string) (value bool)

func (Map) GetInt

func (d Map) GetInt(k string, defaultValue ...int) (value int)

func (Map) GetString

func (d Map) GetString(k string, defaultValue ...string) (value string)

func (Map) GormDataType

func (Map) GormDataType() string

GormDataType schema.Field DataType

func (*Map) Scan

func (d *Map) Scan(src any) error

Scan 数据驱动接口

func (Map) ToString

func (d Map) ToString(k string, def ...string) string

func (Map) Value

func (d Map) Value() (driver.Value, error)

Value 数据驱动接口

type MethodType

type MethodType uint8
const (
	METHOD_GET MethodType = iota
	METHOD_POST
	METHOD_HEAD
	METHOD_PUT
	METHOD_DELETE
	METHOD_OPTIONS
	METHOD_CONNECT
	METHOD_TRACE
	METHOD_PATCH
	METHOD_USE
)

type Mod

type Mod interface {
	Init()
}

type Model

type Model struct {
	ID        uid.UID         `gorm:"size:12;primaryKey" json:"id,omitempty"`
	CreatedAt time.Time       `json:"created_at" gorm:"<-:create"`
	UpdatedAt time.Time       `json:"updated_at"`
	DeletedAt *gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index"`
}

func (*Model) BeforeCreate

func (m *Model) BeforeCreate(tx *DB) error

type Models added in v2.0.2

type Models struct {
	ID        UUID            `json:"id,omitempty" gorm:"size:32;primaryKey"`
	CreatedAt time.Time       `json:"created_at" gorm:"<-:create"`
	UpdatedAt time.Time       `json:"updated_at"`
	DeletedAt *gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index"`
}

func (*Models) BeforeCreate added in v2.0.2

func (m *Models) BeforeCreate(tx *DB) error

type Module

type Module interface {
	Init()
}

type ModuleInfo

type ModuleInfo struct {
	ID       string
	Instance func() Module
}

type Money added in v2.0.24

type Money float64

func (Money) AddInt added in v2.0.24

func (m Money) AddInt(in int, fraction ...int) Money

AddInt 加整数 m + in fraction in 保留小数位

func (Money) DivInt added in v2.0.24

func (m Money) DivInt(in int, fraction ...int) Money

DivInt 除以整数 m / in fraction in 保留小数位

func (Money) Float64 added in v2.0.24

func (m Money) Float64() float64

Float64 输出 float64

func (Money) GormDataType added in v2.0.24

func (Money) GormDataType() string

GormDataType schema.Field DataType

func (Money) IsEqual added in v2.0.24

func (m Money) IsEqual(x Money, fixed ...int) bool

func (Money) MulInt added in v2.0.24

func (m Money) MulInt(in int, fraction ...int) Money

MulInt 乘以整数 m * in fraction in 保留小数位

func (Money) SubInt added in v2.0.24

func (m Money) SubInt(in int, fraction ...int) Money

SubInt 减整数 m - in fraction in 保留小数位

func (Money) ToFixed added in v2.0.24

func (m Money) ToFixed(fraction ...int) Money

ToFixed 保留几位小数 Param fraction int return float64

func (Money) ToFloor added in v2.0.24

func (m Money) ToFloor(p int) Money

ToFloor 保留 p 位小数, 向下取整

func (Money) ToRound added in v2.0.24

func (m Money) ToRound(p int) Money

ToRound 保留 p 位小数,四舍五入

func (*Money) UnmarshalJSON added in v2.0.24

func (m *Money) UnmarshalJSON(data []byte) error

type NextPages added in v2.0.6

type NextPages struct {
	P     int  `json:"p"`
	L     int  `json:"l"`
	Next  bool `json:"next"`
	Prev  bool `json:"prev"`
	Data  any  `json:"data"`
	Extra any  `json:"extra,omitempty"`
}

func FindNext added in v2.0.6

func FindNext(whr *Map, out any, db ...*DB) (result NextPages, err error)

type Options

type Options map[string]any
var (
	Conf Options
)

func LoadConfigFile

func LoadConfigFile(file string, opts ...Options) Options

func (*Options) GetAs

func (opt *Options) GetAs(k string, v any) error

func (*Options) GetBool

func (opt *Options) GetBool(k string, def ...bool) bool

func (*Options) GetInt

func (opt *Options) GetInt(k string, def ...int) int

func (*Options) GetInt64

func (opt *Options) GetInt64(k string, def ...int64) int64

func (*Options) GetMap

func (opt *Options) GetMap(k string, def ...Options) Options

func (*Options) GetString

func (opt *Options) GetString(k string, def ...string) string

func (*Options) GetStrings

func (opt *Options) GetStrings(k string, def ...[]string) []string

func (*Options) ToString

func (opt *Options) ToString(k string, def ...string) string

func (*Options) Value

func (opt *Options) Value(k string) (any, bool)

type Pages

type Pages struct {
	P     int   `json:"p"`
	L     int   `json:"l"`
	Total int64 `json:"total"`
	Data  any   `json:"data"`
	Extra any   `json:"extra,omitempty"`
}

func FindPage

func FindPage(whr *Map, out any, db ...*DB) (result Pages, err error)

FindPage Gorm find to page process whr

type RecoveryFunc

type RecoveryFunc func(c Ctx, err any)

RecoveryFunc defines the function passable to CustomRecovery.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher

	// Returns the HTTP response status code of the current request.
	Status() int

	// Returns the number of bytes already written into the response http body.
	// See Written()
	Size() int

	// Writes the string into the response body.
	WriteString(string) (int, error)

	// Returns true if the response body was already written.
	Written() bool

	// Forces to write the http header (status code + headers).
	DoWriteHeader()

	// get the http.Pusher for server push
	Pusher() http.Pusher
}

ResponseWriter ...

type RestfulDefine

type RestfulDefine struct {
	Data    string
	Status  string
	Message string
	Code    any
}

type Route

type Route struct {

	// Public fields
	Method string `json:"method"` // HTTP method
	Name   string `json:"name"`   // Route's name
	//nolint:revive // Having both a Path (uppercase) and a path (lowercase) is fine
	Path     string        `json:"path"`   // Original registered route path
	Params   []string      `json:"params"` // Case sensitive param keys
	Handlers []HandlerFunc `json:"-"`      // Ctx handlers
	// contains filtered or unexported fields
}

type Router

type Router interface {
	Use(args ...any) Router
	// contains filtered or unexported methods
}

Router defines all router handle interface, including app and group router.

type StringOrNil

type StringOrNil string

空字符串 存入数据库 存 NULL ,这样会跳过数据库唯一索引的检查

func (*StringOrNil) Scan

func (s *StringOrNil) Scan(src any) error

implements sql.Scanner, will be invoked automatically when read from the db

func (StringOrNil) String

func (s StringOrNil) String() string

func (StringOrNil) Value

func (s StringOrNil) Value() (driver.Value, error)

implements driver.Valuer, will be invoked automatically when written to the db

type TypeConstraint

type TypeConstraint int16

TypeConstraint parameter constraint types

type UUID added in v2.0.2

type UUID struct {
	uuid.UUID
}

func NewUUID added in v2.0.2

func NewUUID() UUID

func ParseBytes added in v2.0.10

func ParseBytes(b []byte) (UUID, error)

ParseBytes is like Parse, except it parses a byte slice instead of a string.

func UUIDFromString added in v2.0.2

func UUIDFromString(s string) (UUID, error)

func (UUID) Bytes added in v2.0.18

func (u UUID) Bytes() []byte

func (UUID) GormDBDataType added in v2.0.24

func (UUID) GormDBDataType(db *gorm.DB, field *schema.Field) string

func (UUID) GormDataType added in v2.0.24

func (uuid UUID) GormDataType() string

GormDataType gorm common data type

func (UUID) IsEmpty added in v2.0.2

func (u UUID) IsEmpty() bool

func (UUID) MarshalText added in v2.0.10

func (id UUID) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*UUID) Scan added in v2.0.10

func (uuid *UUID) Scan(src any) error

Scan implements sql.Scanner so UUIDs can be read from databases transparently. Currently, database types that map to string and []byte are supported. Please consult database-specific driver documentation for matching types.

func (UUID) String added in v2.0.10

func (u UUID) String() string

func (*UUID) UnmarshalText added in v2.0.10

func (uuid *UUID) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (UUID) Value added in v2.0.10

func (uuid UUID) Value() (driver.Value, error)

Value implements sql.Valuer so that UUIDs can be written to databases transparently. Currently, UUIDs map to strings. Please consult database-specific driver documentation for matching types.

type Writers

type Writers struct{}

func (Writers) Printf

func (Writers) Printf(f string, args ...any)

Directories

Path Synopsis
example
middleware
Package reuseport provides TCP net.Listener with SO_REUSEPORT support.
Package reuseport provides TCP net.Listener with SO_REUSEPORT support.
Package tcplisten provides customizable TCP net.Listener with various performance-related options:
Package tcplisten provides customizable TCP net.Listener with various performance-related options:

Jump to

Keyboard shortcuts

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