Group types and vars

This commit is contained in:
Alexander Melentyev 2021-08-22 21:43:00 +03:00
parent 4e7584175d
commit 73a8bb7a01
13 changed files with 221 additions and 193 deletions

16
auth.go
View File

@ -16,15 +16,17 @@ import (
// AuthUserKey is the cookie name for user credential in basic auth. // AuthUserKey is the cookie name for user credential in basic auth.
const AuthUserKey = "user" const AuthUserKey = "user"
// Accounts defines a key/value for user/pass list of authorized logins. type (
type Accounts map[string]string // Accounts defines a key/value for user/pass list of authorized logins.
Accounts map[string]string
type authPair struct { authPair struct {
value string value string
user string user string
} }
type authPairs []authPair authPairs []authPair
)
func (a authPairs) searchCredential(authValue string) (string, bool) { func (a authPairs) searchCredential(authValue string) (string, bool) {
if authValue == "" { if authValue == "" {

View File

@ -24,27 +24,29 @@ const (
MIMEYAML = "application/x-yaml" MIMEYAML = "application/x-yaml"
) )
// Binding describes the interface which needs to be implemented for binding the type (
// data present in the request such as JSON request body, query parameters or // Binding describes the interface which needs to be implemented for binding the
// the form POST. // data present in the request such as JSON request body, query parameters or
type Binding interface { // the form POST.
Name() string Binding interface {
Bind(*http.Request, interface{}) error Name() string
} Bind(*http.Request, interface{}) error
}
// BindingBody adds BindBody method to Binding. BindBody is similar with Bind, // BindingBody adds BindBody method to Binding. BindBody is similar with Bind,
// but it reads the body from supplied bytes instead of req.Body. // but it reads the body from supplied bytes instead of req.Body.
type BindingBody interface { BindingBody interface {
Binding Binding
BindBody([]byte, interface{}) error BindBody([]byte, interface{}) error
} }
// BindingUri adds BindUri method to Binding. BindUri is similar with Bind, // BindingUri adds BindUri method to Binding. BindUri is similar with Bind,
// but it read the Params. // but it read the Params.
type BindingUri interface { BindingUri interface {
Name() string Name() string
BindUri(map[string][]string, interface{}) error BindUri(map[string][]string, interface{}) error
} }
)
// StructValidator is the minimal interface which needs to be implemented in // StructValidator is the minimal interface which needs to be implemented in
// order for it to be used as the validator engine for ensuring the correctness // order for it to be used as the validator engine for ensuring the correctness

View File

@ -22,27 +22,29 @@ const (
MIMEYAML = "application/x-yaml" MIMEYAML = "application/x-yaml"
) )
// Binding describes the interface which needs to be implemented for binding the type (
// data present in the request such as JSON request body, query parameters or // Binding describes the interface which needs to be implemented for binding the
// the form POST. // data present in the request such as JSON request body, query parameters or
type Binding interface { // the form POST.
Name() string Binding interface {
Bind(*http.Request, interface{}) error Name() string
} Bind(*http.Request, interface{}) error
}
// BindingBody adds BindBody method to Binding. BindBody is similar with Bind, // BindingBody adds BindBody method to Binding. BindBody is similar with Bind,
// but it reads the body from supplied bytes instead of req.Body. // but it reads the body from supplied bytes instead of req.Body.
type BindingBody interface { BindingBody interface {
Binding Binding
BindBody([]byte, interface{}) error BindBody([]byte, interface{}) error
} }
// BindingUri adds BindUri method to Binding. BindUri is similar with Bind, // BindingUri adds BindUri method to Binding. BindUri is similar with Bind,
// but it read the Params. // but it read the Params.
type BindingUri interface { BindingUri interface {
Name() string Name() string
BindUri(map[string][]string, interface{}) error BindUri(map[string][]string, interface{}) error
} }
)
// StructValidator is the minimal interface which needs to be implemented in // StructValidator is the minimal interface which needs to be implemented in
// order for it to be used as the validator engine for ensuring the correctness // order for it to be used as the validator engine for ensuring the correctness

View File

@ -10,9 +10,11 @@ import (
const defaultMemory = 32 << 20 const defaultMemory = 32 << 20
type formBinding struct{} type (
type formPostBinding struct{} formBinding struct{}
type formMultipartBinding struct{} formPostBinding struct{}
formMultipartBinding struct{}
)
func (formBinding) Name() string { func (formBinding) Name() string {
return "form" return "form"

View File

@ -13,16 +13,18 @@ import (
"github.com/gin-gonic/gin/internal/json" "github.com/gin-gonic/gin/internal/json"
) )
// EnableDecoderUseNumber is used to call the UseNumber method on the JSON var (
// Decoder instance. UseNumber causes the Decoder to unmarshal a number into an // EnableDecoderUseNumber is used to call the UseNumber method on the JSON
// interface{} as a Number instead of as a float64. // Decoder instance. UseNumber causes the Decoder to unmarshal a number into an
var EnableDecoderUseNumber = false // interface{} as a Number instead of as a float64.
EnableDecoderUseNumber = false
// EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method // EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method
// on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to // on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to
// return an error when the destination is a struct and the input contains object // return an error when the destination is a struct and the input contains object
// keys which do not match any non-ignored, exported fields in the destination. // keys which do not match any non-ignored, exported fields in the destination.
var EnableDecoderDisallowUnknownFields = false EnableDecoderDisallowUnknownFields = false
)
type jsonBinding struct{} type jsonBinding struct{}

View File

@ -30,14 +30,16 @@ const (
ErrorTypeNu = 2 ErrorTypeNu = 2
) )
// Error represents a error's specification. type (
type Error struct { // Error represents a error's specification.
Err error Error struct {
Type ErrorType Err error
Meta interface{} Type ErrorType
} Meta interface{}
}
type errorMsgs []*Error errorMsgs []*Error
)
var _ error = &Error{} var _ error = &Error{}

14
fs.go
View File

@ -9,13 +9,15 @@ import (
"os" "os"
) )
type onlyFilesFS struct { type (
fs http.FileSystem onlyFilesFS struct {
} fs http.FileSystem
}
type neuteredReaddirFile struct { neuteredReaddirFile struct {
http.File http.File
} }
)
// Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally // Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally
// in router.Static(). // in router.Static().

30
gin.go
View File

@ -27,11 +27,13 @@ var (
var defaultPlatform string var defaultPlatform string
// HandlerFunc defines the handler used by gin middleware as return value. type (
type HandlerFunc func(*Context) // HandlerFunc defines the handler used by gin middleware as return value.
HandlerFunc func(*Context)
// HandlersChain defines a HandlerFunc array. // HandlersChain defines a HandlerFunc array.
type HandlersChain []HandlerFunc HandlersChain []HandlerFunc
)
// Last returns the last handler in the chain. ie. the last handler is the main one. // Last returns the last handler in the chain. ie. the last handler is the main one.
func (c HandlersChain) Last() HandlerFunc { func (c HandlersChain) Last() HandlerFunc {
@ -41,16 +43,18 @@ func (c HandlersChain) Last() HandlerFunc {
return nil return nil
} }
// RouteInfo represents a request route's specification which contains method and path and its handler. type (
type RouteInfo struct { // RouteInfo represents a request route's specification which contains method and path and its handler.
Method string RouteInfo struct {
Path string Method string
Handler string Path string
HandlerFunc HandlerFunc Handler string
} HandlerFunc HandlerFunc
}
// RoutesInfo defines a RouteInfo array. // RoutesInfo defines a RouteInfo array.
type RoutesInfo []RouteInfo RoutesInfo []RouteInfo
)
// Trusted platforms // Trusted platforms
const ( const (

View File

@ -35,48 +35,50 @@ const (
var consoleColorMode = autoColor var consoleColorMode = autoColor
// LoggerConfig defines the config for Logger middleware. type (
type LoggerConfig struct { // LoggerConfig defines the config for Logger middleware.
// Optional. Default value is gin.defaultLogFormatter LoggerConfig struct {
Formatter LogFormatter // Optional. Default value is gin.defaultLogFormatter
Formatter LogFormatter
// Output is a writer where logs are written. // Output is a writer where logs are written.
// Optional. Default value is gin.DefaultWriter. // Optional. Default value is gin.DefaultWriter.
Output io.Writer Output io.Writer
// SkipPaths is a url path array which logs are not written. // SkipPaths is a url path array which logs are not written.
// Optional. // Optional.
SkipPaths []string SkipPaths []string
} }
// LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter // LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter
type LogFormatter func(params LogFormatterParams) string LogFormatter func(params LogFormatterParams) string
// LogFormatterParams is the structure any formatter will be handed when time to log comes // LogFormatterParams is the structure any formatter will be handed when time to log comes
type LogFormatterParams struct { LogFormatterParams struct {
Request *http.Request Request *http.Request
// TimeStamp shows the time after the server returns a response. // TimeStamp shows the time after the server returns a response.
TimeStamp time.Time TimeStamp time.Time
// StatusCode is HTTP response code. // StatusCode is HTTP response code.
StatusCode int StatusCode int
// Latency is how much time the server cost to process a certain request. // Latency is how much time the server cost to process a certain request.
Latency time.Duration Latency time.Duration
// ClientIP equals Context's ClientIP method. // ClientIP equals Context's ClientIP method.
ClientIP string ClientIP string
// Method is the HTTP method given to the request. // Method is the HTTP method given to the request.
Method string Method string
// Path is a path the client requests. // Path is a path the client requests.
Path string Path string
// ErrorMessage is set if error has occurred in processing the request. // ErrorMessage is set if error has occurred in processing the request.
ErrorMessage string ErrorMessage string
// isTerm shows whether does gin's output descriptor refers to a terminal. // isTerm shows whether does gin's output descriptor refers to a terminal.
isTerm bool isTerm bool
// BodySize is the size of the Response Body // BodySize is the size of the Response Body
BodySize int BodySize int
// Keys are the keys set on the request's context. // Keys are the keys set on the request's context.
Keys map[string]interface{} Keys map[string]interface{}
} }
)
// StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal. // StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.
func (p *LogFormatterParams) StatusCodeColor() string { func (p *LogFormatterParams) StatusCodeColor() string {

22
mode.go
View File

@ -29,17 +29,19 @@ const (
testCode testCode
) )
// DefaultWriter is the default io.Writer used by Gin for debug output and var (
// middleware output like Logger() or Recovery(). // DefaultWriter is the default io.Writer used by Gin for debug output and
// Note that both Logger and Recovery provides custom ways to configure their // middleware output like Logger() or Recovery().
// output io.Writer. // Note that both Logger and Recovery provides custom ways to configure their
// To support coloring in Windows use: // output io.Writer.
// import "github.com/mattn/go-colorable" // To support coloring in Windows use:
// gin.DefaultWriter = colorable.NewColorableStdout() // import "github.com/mattn/go-colorable"
var DefaultWriter io.Writer = os.Stdout // gin.DefaultWriter = colorable.NewColorableStdout()
DefaultWriter io.Writer = os.Stdout
// DefaultErrorWriter is the default io.Writer used by Gin to debug errors // DefaultErrorWriter is the default io.Writer used by Gin to debug errors
var DefaultErrorWriter io.Writer = os.Stderr DefaultErrorWriter io.Writer = os.Stderr
)
var ( var (
ginMode = debugCode ginMode = debugCode

View File

@ -16,38 +16,40 @@ const (
defaultStatus = http.StatusOK defaultStatus = http.StatusOK
) )
// ResponseWriter ... type (
type ResponseWriter interface { // ResponseWriter ...
http.ResponseWriter ResponseWriter interface {
http.Hijacker http.ResponseWriter
http.Flusher http.Hijacker
http.CloseNotifier http.Flusher
http.CloseNotifier
// Returns the HTTP response status code of the current request. // Returns the HTTP response status code of the current request.
Status() int Status() int
// Returns the number of bytes already written into the response http body. // Returns the number of bytes already written into the response http body.
// See Written() // See Written()
Size() int Size() int
// Writes the string into the response body. // Writes the string into the response body.
WriteString(string) (int, error) WriteString(string) (int, error)
// Returns true if the response body was already written. // Returns true if the response body was already written.
Written() bool Written() bool
// Forces to write the http header (status code + headers). // Forces to write the http header (status code + headers).
WriteHeaderNow() WriteHeaderNow()
// get the http.Pusher for server push // get the http.Pusher for server push
Pusher() http.Pusher Pusher() http.Pusher
} }
type responseWriter struct { responseWriter struct {
http.ResponseWriter http.ResponseWriter
size int size int
status int status int
} }
)
var _ ResponseWriter = &responseWriter{} var _ ResponseWriter = &responseWriter{}

View File

@ -16,39 +16,41 @@ var (
regEnLetter = regexp.MustCompile("^[A-Z]+$") regEnLetter = regexp.MustCompile("^[A-Z]+$")
) )
// IRouter defines all router handle interface includes single and group router. type (
type IRouter interface { // IRouter defines all router handle interface includes single and group router.
IRoutes IRouter interface {
Group(string, ...HandlerFunc) *RouterGroup IRoutes
} Group(string, ...HandlerFunc) *RouterGroup
}
// IRoutes defines all router handle interface. // IRoutes defines all router handle interface.
type IRoutes interface { IRoutes interface {
Use(...HandlerFunc) IRoutes Use(...HandlerFunc) IRoutes
Handle(string, string, ...HandlerFunc) IRoutes Handle(string, string, ...HandlerFunc) IRoutes
Any(string, ...HandlerFunc) IRoutes Any(string, ...HandlerFunc) IRoutes
GET(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes
POST(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes
DELETE(string, ...HandlerFunc) IRoutes DELETE(string, ...HandlerFunc) IRoutes
PATCH(string, ...HandlerFunc) IRoutes PATCH(string, ...HandlerFunc) IRoutes
PUT(string, ...HandlerFunc) IRoutes PUT(string, ...HandlerFunc) IRoutes
OPTIONS(string, ...HandlerFunc) IRoutes OPTIONS(string, ...HandlerFunc) IRoutes
HEAD(string, ...HandlerFunc) IRoutes HEAD(string, ...HandlerFunc) IRoutes
StaticFile(string, string) IRoutes StaticFile(string, string) IRoutes
Static(string, string) IRoutes Static(string, string) IRoutes
StaticFS(string, http.FileSystem) IRoutes StaticFS(string, http.FileSystem) IRoutes
} }
// RouterGroup is used internally to configure router, a RouterGroup is associated with // RouterGroup is used internally to configure router, a RouterGroup is associated with
// a prefix and an array of handlers (middleware). // a prefix and an array of handlers (middleware).
type RouterGroup struct { RouterGroup struct {
Handlers HandlersChain Handlers HandlersChain
basePath string basePath string
engine *Engine engine *Engine
root bool root bool
} }
)
var _ IRouter = &RouterGroup{} var _ IRouter = &RouterGroup{}

20
tree.go
View File

@ -19,16 +19,18 @@ var (
strStar = []byte("*") strStar = []byte("*")
) )
// Param is a single URL parameter, consisting of a key and a value. type (
type Param struct { // Param is a single URL parameter, consisting of a key and a value.
Key string Param struct {
Value string Key string
} Value string
}
// Params is a Param-slice, as returned by the router. // Params is a Param-slice, as returned by the router.
// The slice is ordered, the first URL parameter is also the first slice value. // The slice is ordered, the first URL parameter is also the first slice value.
// It is therefore safe to read values by the index. // It is therefore safe to read values by the index.
type Params []Param Params []Param
)
// Get returns the value of the first Param which key matches the given name and a boolean true. // Get returns the value of the first Param which key matches the given name and a boolean true.
// If no matching Param is found, an empty string is returned and a boolean false . // If no matching Param is found, an empty string is returned and a boolean false .