Documentation
¶
Index ¶
- Constants
- func BytesToString(b []byte) string
- func CleanPath(p string) string
- func CloseDefaultLogger() error
- func ContextRoutePath(ctx context.Context) string
- func ContextVars(ctx context.Context) map[string]string
- func ErrSQLNoRows(e error) bool
- func GetAesCryptoKey() (string, string)
- func GetRealIP(req *http.Request) (ip string)
- func HmacSHA1(k, s []byte) ([]byte, error)
- func HmacSHA256(k, s []byte) ([]byte, error)
- func IsDate(s string) bool
- func IsTime(s string) bool
- func IsWeekEnd(d time.Weekday) bool
- func ListenAndServe(addr string, router http.Handler)
- func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler)
- func ListenAndServeTLSV2(addr, certFile, keyFile string, router http.Handler)
- func ListenAndServeV2(addr string, router http.Handler)
- func LogAlert(v ...interface{})
- func LogDebug(v ...interface{})
- func LogErr(v ...interface{})
- func LogInfo(v ...interface{})
- func LogPanic(v ...interface{})
- func LogWarn(v ...interface{})
- func MD5(data string) string
- func MiddlewareChain(fn http.HandlerFunc, mws ...Middleware) http.HandlerFunc
- func NotAllowedHandler(w http.ResponseWriter, req *http.Request)
- func NotFoundHandler(w http.ResponseWriter, req *http.Request)
- func PanicHandler(w http.ResponseWriter, r *http.Request, err interface{})
- func Redirect(w http.ResponseWriter, r *http.Request, url string)
- func SHA1(data string) string
- func SHA256(data string) string
- func SHA512(data []byte) ([]byte, error)
- func SetAesCryptoKey(password, iv string)
- func SetCookie(w http.ResponseWriter, name, value, path string, maxAge int)
- func SetHTTPRequestTimeout(seconds int)
- func SetHeader(w http.ResponseWriter, key, value string)
- func StrFmtTime(s, fmt string) (t time.Time, err error)
- func StrToDate(s string) (t time.Time, err error)
- func StrToTime(s string) (t time.Time, err error)
- func StringToBytes(s string) []byte
- func TimeFmtStr(t time.Time, fmt string) string
- func TimeToStr(t time.Time) string
- func Vars(r *http.Request) map[string]string
- func WriteBytes(w http.ResponseWriter, response interface{}) error
- func WriteJSON(w http.ResponseWriter, response interface{}) error
- func WriteXML(w http.ResponseWriter, response interface{}) error
- type AesCrypto
- type Error
- type HTTPMessage
- type Handle
- type JSONQuery
- func (jq *JSONQuery) Array(s ...string) ([]interface{}, error)
- func (jq *JSONQuery) ArrayOfArrays(s ...string) ([][]interface{}, error)
- func (jq *JSONQuery) ArrayOfBools(s ...string) ([]bool, error)
- func (jq *JSONQuery) ArrayOfFloats(s ...string) ([]float64, error)
- func (jq *JSONQuery) ArrayOfInts(s ...string) ([]int, error)
- func (jq *JSONQuery) ArrayOfObjects(s ...string) ([]map[string]interface{}, error)
- func (jq *JSONQuery) ArrayOfStrings(s ...string) ([]string, error)
- func (jq *JSONQuery) Bool(s ...string) (bool, error)
- func (jq *JSONQuery) Float(s ...string) (float64, error)
- func (jq *JSONQuery) Int(s ...string) (int, error)
- func (jq *JSONQuery) Int64(s ...string) (int64, error)
- func (jq *JSONQuery) Interface(s ...string) (interface{}, error)
- func (jq *JSONQuery) Matrix2D(s ...string) ([][]interface{}, error)
- func (jq *JSONQuery) Object(s ...string) (map[string]interface{}, error)
- func (jq *JSONQuery) String(s ...string) (string, error)
- type Logger
- type M
- type Middleware
- type ReplyData
- type Router
- func (r *Router) DELETE(path string, handle Handle)
- func (r *Router) GET(path string, handle Handle)
- func (r *Router) HEAD(path string, handle Handle)
- func (r *Router) Handle(method, path string, handle Handle)
- func (r *Router) Handler(method, path string, handler http.Handler)
- func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)
- func (r *Router) Lookup(method, path string) (Handle, map[string]string, bool)
- func (r *Router) OPTIONS(path string, handle Handle)
- func (r *Router) PATCH(path string, handle Handle)
- func (r *Router) POST(path string, handle Handle)
- func (r *Router) PUT(path string, handle Handle)
- func (r *Router) ServeFiles(path string, root http.FileSystem)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
Constants ¶
const ( // TimeFmtLong yyyy-MM-dd hh:mm:ss TimeFmtLong = `2006-01-02 15:04:05` // TimeFmtNumeric yyyyMMddhhmmss TimeFmtNumeric = `20060102150405` // DateFmtLong yyyy-MM-dd DateFmtLong = `2006-01-02` // DateFmtNumeric yyyyMMdd DateFmtNumeric = `20060102` )
const ( ErrOk = 0 ErrNotFound = 1001 // ErrNotFound 404 route not found ErrException = 1002 // ErrException 500 ErrBadRequest = 1003 // ErrBadRequest 400 route params error ErrMethodNotAllowed = 1004 // ErrMethodNotAllowed 405 ErrParamsError = 1005 // ErrParamsError 415 ErrUnAuthorized = 1006 // ErrUnAuthorized 401 ErrDataNotFound = 1007 // ErrDataNotFound 404 ErrNotAllowed = 1008 // ErrNotAllowed 405 ErrDataExists = 1009 // ErrDataExists 400 ErrDataValidate = 1010 // ErrDataValidate 403 VarUserAuthorization = `access_token` // oauth token HTTPHeaderAuthorization = `Authorization` // HTTP header Authorization HTTPHeaderToken = `X-Token` // HTTP header Authorization X-Token )
Error code & constant
const ( // ReqContentTypeURL application/x-www-form-urlencoded ReqContentTypeURL = `application/x-www-form-urlencoded; charset=utf-8` // ReqContentTypeJSON application/json ReqContentTypeJSON = `application/json; charset=utf-8` // ReqContentTypeXML application/xml ReqContentTypeXML = `application/xml; charset=utf-8` // ReqContentTypeMultipart multipart/form-data ReqContentTypeMultipart = `multipart/form-data` // RequestTimeOut http request timeout (second) RequestTimeOut = 30 )
const ( // KB kilo byte KB int = 1 << (10 * iota) // MB mega byte MB // GB giga byte GB // TB tera byte TB // PB peta byte PB )
const ( LibName = `myth` // LibName toolkit name LibVersion = `0.6.0` // LibVersion toolkit version )
Library constant
Variables ¶
This section is empty.
Functions ¶
func BytesToString ¶
BytesToString converts byte slice to string without a memory allocation.
func CleanPath ¶
CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.
The following rules are applied iteratively until no further processing can be done:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.
If the result of this process is an empty string, "/" is returned
func ContextRoutePath ¶
ContextRoutePath current route
func ContextVars ¶
ContextVars returns the route variables for the current Context, if any.
func ListenAndServe ¶
ListenAndServe new server and start
func ListenAndServeTLS ¶
ListenAndServeTLS new server and start
func ListenAndServeTLSV2 ¶
ListenAndServeTLSV2 new http2 server and start
func ListenAndServeV2 ¶
ListenAndServeV2 new http2 server and start
func MiddlewareChain ¶
func MiddlewareChain(fn http.HandlerFunc, mws ...Middleware) http.HandlerFunc
MiddlewareChain applies middlewares to a http.HandlerFunc
func NotAllowedHandler ¶
func NotAllowedHandler(w http.ResponseWriter, req *http.Request)
NotAllowedHandler 405
func NotFoundHandler ¶
func NotFoundHandler(w http.ResponseWriter, req *http.Request)
NotFoundHandler 404
func PanicHandler ¶
func PanicHandler(w http.ResponseWriter, r *http.Request, err interface{})
PanicHandler panic router
func SetAesCryptoKey ¶
func SetAesCryptoKey(password, iv string)
SetAesCryptoKey set key, key/iv length:16, 24, 32 bytes to AES-128, AES-192, AES-256
func SetCookie ¶
func SetCookie(w http.ResponseWriter, name, value, path string, maxAge int)
SetCookie set http cookie
func SetHTTPRequestTimeout ¶
func SetHTTPRequestTimeout(seconds int)
SetHTTPRequestTimeout set request timeout
func SetHeader ¶
func SetHeader(w http.ResponseWriter, key, value string)
SetHeader set http response header
func StringToBytes ¶
StringToBytes converts string to byte slice without a memory allocation.
func WriteBytes ¶
func WriteBytes(w http.ResponseWriter, response interface{}) error
WriteBytes response bytes
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, response interface{}) error
WriteJSON response JSON data.
func WriteXML ¶
func WriteXML(w http.ResponseWriter, response interface{}) error
WriteXML response XML data.
Types ¶
type AesCrypto ¶
AesCrypto define
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error error
type HTTPMessage ¶
HTTPMessage HTTP response
func Get ¶
func Get(uri, certPath, keyPath string, header map[string]string) (msg HTTPMessage, err error)
Get HTTP request GET
func Post ¶
func Post(uri, certPath, keyPath string, header map[string]string, data io.Reader) (msg HTTPMessage, err error)
Post HTTP request POST
func (HTTPMessage) JSONQuery ¶
func (m HTTPMessage) JSONQuery() (jq *JSONQuery, err error)
JSONQuery Body to JSONQuery
type Handle ¶
type Handle func(http.ResponseWriter, *http.Request)
Handle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).
type JSONQuery ¶
type JSONQuery struct {
// contains filtered or unexported fields
}
JSONQuery is an object that enables querying of a Go map with a simple positional query language.
func NewJSONQuery ¶
NewJSONQuery creates a new JSONQuery obj from []byte.
func (*JSONQuery) ArrayOfArrays ¶
ArrayOfArrays extracts an array of []interface{} (arrays) from some json
func (*JSONQuery) ArrayOfBools ¶
ArrayOfBools extracts an array of bools from some json
func (*JSONQuery) ArrayOfFloats ¶
ArrayOfFloats extracts an array of float64s from some json
func (*JSONQuery) ArrayOfInts ¶
ArrayOfInts extracts an array of ints from some json
func (*JSONQuery) ArrayOfObjects ¶
ArrayOfObjects extracts an array of map[string]interface{} (objects) from some json
func (*JSONQuery) ArrayOfStrings ¶
ArrayOfStrings extracts an array of strings from some json
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger logger
func NewDefaultLogger ¶
NewDefaultLogger defult logger
func ReopenDefaultLogger ¶
ReopenDefaultLogger re open default logger
type M ¶
M is a shortcut for map[string]any
func (M) MarshalXML ¶
MarshalXML allows type Map to be used with xml.Marshal.
type Middleware ¶
type Middleware func(http.HandlerFunc) http.HandlerFunc
Middleware http middleware
type ReplyData ¶
type ReplyData struct { Status int `json:"status" xml:"status"` // Status code Message string `json:"message" xml:"message"` // Message description Errs map[string]string `json:"errors,omitempty" xml:"errors,omitempty"` // Errs errors PageCount int `json:"pageCount,omitempty"` Total int `json:"total,omitempty" xml:"total,omitempty"` // Total data total List interface{} `json:"rows,omitempty" xml:"rows,omitempty"` // List data list Data interface{} `json:"data,omitempty" xml:"data,omitempty"` // Data data attribute }
ReplyData define API output data
func NewReplyData ¶
NewReplyData creates and return ReplyData with status and message
func ReplyErrors ¶
ReplyErrors creates and return ReplyData with errors
type Router ¶
type Router struct { // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS bool // Configurable http.Handler which is called when no matching route is // found. If it is not set, http.NotFound is used. NotFound http.Handler // Configurable http.Handler which is called when a request // cannot be routed and HandleMethodNotAllowed is true. // If it is not set, http.Error with http.StatusMethodNotAllowed is used. // The "Allow" header with allowed request methods is set before the handler // is called. MethodNotAllowed http.Handler // Function to handle panics recovered from http handlers. // It should be used to generate a error page and return the http error code // 500 (Internal Server Error). // The handler can be used to keep your server from crashing because of // unrecovered panics. PanicHandler func(http.ResponseWriter, *http.Request, interface{}) // contains filtered or unexported fields }
Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes
func NewRouter ¶
func NewRouter() *Router
NewRouter returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.
func (*Router) Handle ¶
Handle registers a new request handle with the given path and method.
For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).
func (*Router) Handler ¶
Handler is an adapter which allows the usage of an http.Handler as a request handle. With go 1.7+, the Params will be available in the request context under ParamsKey.
func (*Router) HandlerFunc ¶
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)
HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handle.
func (*Router) Lookup ¶
Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.
func (*Router) ServeFiles ¶
func (r *Router) ServeFiles(path string, root http.FileSystem)
ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:
router.ServeFiles("/src/*filepath", http.Dir("/var/www"))