myth

package module
Version: v0.0.0-...-de975e2 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2021 License: MIT Imports: 32 Imported by: 0

README

myth

myth

Documentation

Index

Constants

View Source
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`
)
View Source
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

View Source
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
)
View Source
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
)
View Source
const (
	LibName    = `myth`  // LibName toolkit name
	LibVersion = `0.6.0` // LibVersion toolkit version
)

Library constant

Variables

This section is empty.

Functions

func CleanPath

func CleanPath(p string) string

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:

1. Replace multiple slashes with a single slash.
2. Eliminate each . path name element (the current directory).
3. Eliminate each inner .. path name element (the parent directory)
   along with the non-.. element that precedes it.
4. 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 CloseDefaultLogger

func CloseDefaultLogger() error

CloseDefaultLogger close

func ContextRoutePath

func ContextRoutePath(ctx context.Context) string

ContextRoutePath current route

func ContextVars

func ContextVars(ctx context.Context) map[string]string

ContextVars returns the route variables for the current Context, if any.

func ErrSQLNoRows

func ErrSQLNoRows(e error) bool

ErrSQLNoRows SQL

func GetAesCryptoKey

func GetAesCryptoKey() (string, string)

GetAesCryptoKey get current key/iv

func GetRealIP

func GetRealIP(req *http.Request) (ip string)

GetRealIP get real IP from Request

func HmacSHA256

func HmacSHA256(k, s []byte) ([]byte, error)

func IsDate

func IsDate(s string) bool

IsDate 是否为有效日期

func IsTime

func IsTime(s string) bool

IsTime 是否时间格式字符串

func IsWeekEnd

func IsWeekEnd(d time.Weekday) bool

IsWeekEnd 日期是否周末

func ListenAndServe

func ListenAndServe(addr string, router http.Handler)

ListenAndServe new server and start

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler)

ListenAndServeTLS new server and start

func ListenAndServeTLSV2

func ListenAndServeTLSV2(addr, certFile, keyFile string, router http.Handler)

ListenAndServeTLSV2 new http2 server and start

func ListenAndServeV2

func ListenAndServeV2(addr string, router http.Handler)

ListenAndServeV2 new http2 server and start

func LogAlert

func LogAlert(v ...interface{})

LogAlert alert

func LogDebug

func LogDebug(v ...interface{})

LogDebug debug

func LogErr

func LogErr(v ...interface{})

LogErr err

func LogInfo

func LogInfo(v ...interface{})

LogInfo info

func LogWarn

func LogWarn(v ...interface{})

LogWarn warn

func MD5

func MD5(data string) string

MD5 hash string

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 Redirect

func Redirect(w http.ResponseWriter, r *http.Request, url string)

Redirect redirect

func SHA1

func SHA1(data string) string

SHA1 hash string

func SHA256

func SHA256(data string) string

SHA256 hash string

func SHA512

func SHA512(data []byte) ([]byte, error)

SHA512 hash

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 StrFmtTime

func StrFmtTime(s, fmt string) (t time.Time, err error)

StrFmtTime 时间转字符串

func StrToDate

func StrToDate(s string) (t time.Time, err error)

StrToDate 字符串转日期

func StrToTime

func StrToTime(s string) (t time.Time, err error)

StrToTime 字符串转时间

func TimeFmtStr

func TimeFmtStr(t time.Time, fmt string) string

TimeFmtStr 时间转字符串

func TimeToStr

func TimeToStr(t time.Time) string

TimeToStr 时间转字符串

func Vars

func Vars(r *http.Request) map[string]string

Vars returns the route variables for the current request, if any.

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

type AesCrypto struct {
	Key []byte
	IV  []byte
}

AesCrypto define

func NewAesCrypto

func NewAesCrypto() *AesCrypto

NewAesCrypto new AesCrypto

func (*AesCrypto) Decrypt

func (a *AesCrypto) Decrypt(crypted []byte) ([]byte, error)

Decrypt decrypt data

func (*AesCrypto) Encrypt

func (a *AesCrypto) Encrypt(data []byte) ([]byte, error)

Encrypt encrypt data

func (*AesCrypto) SetKey

func (a *AesCrypto) SetKey(key, iv string)

SetKey set key

type Error

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

Error error

func NewError

func NewError(code int, text string) *Error

NewError new

func (*Error) Code

func (e *Error) Code() int

Code err code

func (*Error) Error

func (e *Error) Error() string

Error err to string

func (*Error) Is

func (e *Error) Is(err error) bool

Is reports whether any error in err's chain matches target.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap return error

type HTTPMessage

type HTTPMessage struct {
	StatusCode int
	Body       []byte
	Header     http.Header
}

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) JSON

func (m HTTPMessage) JSON(dest interface{}) (err error)

JSON Body to JSON

func (HTTPMessage) JSONQuery

func (m HTTPMessage) JSONQuery() (jq *JSONQuery, err error)

JSONQuery Body to JSONQuery

func (HTTPMessage) XML

func (m HTTPMessage) XML(dest interface{}) (err error)

XML Body to XML

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

func NewJSONQuery(data []byte) (jq *JSONQuery, err error)

NewJSONQuery creates a new JSONQuery obj from []byte.

func (*JSONQuery) Array

func (jq *JSONQuery) Array(s ...string) ([]interface{}, error)

Array extracts a []interface{} from the JsonQuery

func (*JSONQuery) ArrayOfArrays

func (jq *JSONQuery) ArrayOfArrays(s ...string) ([][]interface{}, error)

ArrayOfArrays extracts an array of []interface{} (arrays) from some json

func (*JSONQuery) ArrayOfBools

func (jq *JSONQuery) ArrayOfBools(s ...string) ([]bool, error)

ArrayOfBools extracts an array of bools from some json

func (*JSONQuery) ArrayOfFloats

func (jq *JSONQuery) ArrayOfFloats(s ...string) ([]float64, error)

ArrayOfFloats extracts an array of float64s from some json

func (*JSONQuery) ArrayOfInts

func (jq *JSONQuery) ArrayOfInts(s ...string) ([]int, error)

ArrayOfInts extracts an array of ints from some json

func (*JSONQuery) ArrayOfObjects

func (jq *JSONQuery) ArrayOfObjects(s ...string) ([]map[string]interface{}, error)

ArrayOfObjects extracts an array of map[string]interface{} (objects) from some json

func (*JSONQuery) ArrayOfStrings

func (jq *JSONQuery) ArrayOfStrings(s ...string) ([]string, error)

ArrayOfStrings extracts an array of strings from some json

func (*JSONQuery) Bool

func (jq *JSONQuery) Bool(s ...string) (bool, error)

Bool extracts a bool the JSONQuery

func (*JSONQuery) Float

func (jq *JSONQuery) Float(s ...string) (float64, error)

Float extracts a float from the JsonQuery

func (*JSONQuery) Int

func (jq *JSONQuery) Int(s ...string) (int, error)

Int extracts an int from the JsonQuery

func (*JSONQuery) Int64

func (jq *JSONQuery) Int64(s ...string) (int64, error)

Int64 extracts an int64 from the JsonQuery

func (*JSONQuery) Interface

func (jq *JSONQuery) Interface(s ...string) (interface{}, error)

Interface extracts an interface{} from the JsonQuery

func (*JSONQuery) Matrix2D

func (jq *JSONQuery) Matrix2D(s ...string) ([][]interface{}, error)

Matrix2D is an alias for ArrayOfArrays

func (*JSONQuery) Object

func (jq *JSONQuery) Object(s ...string) (map[string]interface{}, error)

Object extracts a json object from the JsonQuery

func (*JSONQuery) String

func (jq *JSONQuery) String(s ...string) (string, error)

String extracts a string from the JsonQuery

type Logger

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

Logger logger

func NewDefaultLogger

func NewDefaultLogger(path string) (*Logger, error)

NewDefaultLogger defult logger

func NewLogger

func NewLogger(out io.Writer) *Logger

NewLogger new logger

func ReopenDefaultLogger

func ReopenDefaultLogger(path string) (*Logger, error)

ReopenDefaultLogger re open default logger

func (*Logger) Alert

func (l *Logger) Alert(v ...interface{})

Alert log Alert

func (*Logger) Debug

func (l *Logger) Debug(v ...interface{})

Debug log debug

func (*Logger) Err

func (l *Logger) Err(v ...interface{})

Err log Err

func (*Logger) Info

func (l *Logger) Info(v ...interface{})

Info log info

func (*Logger) Warn

func (l *Logger) Warn(v ...interface{})

Warn log Warn

type Map

type Map map[string]interface{}

Map is a shortcut for map[string]interface{}

func NewMap

func NewMap() Map

NewMap new map

func (Map) Bytes

func (m Map) Bytes() []byte

Bytes map to json bytes

func (Map) MarshalXML

func (m Map) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML allows type Map to be used with xml.Marshal.

func (Map) String

func (m Map) String() string

String map to json string

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

func NewReplyData(status int) *ReplyData

NewReplyData creates and return ReplyData with status and message

func ReplyErr

func ReplyErr(status int, message string) *ReplyData

ReplyErr creates and return ReplyData with error and message

func ReplyErrors

func ReplyErrors(status int, errors map[string]string) *ReplyData

ReplyErrors creates and return ReplyData with errors

func ReplyOk

func ReplyOk() *ReplyData

ReplyOk creates and return ReplyData with ok

func ReplyRow

func ReplyRow(row interface{}) *ReplyData

ReplyRow creates and return ReplyData with attr row

func ReplyRows

func ReplyRows(total, pageCount int, rows interface{}) *ReplyData

ReplyRows creates and return ReplyData with total and list

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) DELETE

func (r *Router) DELETE(path string, handle Handle)

DELETE is a shortcut for router.Handle("DELETE", path, handle)

func (*Router) GET

func (r *Router) GET(path string, handle Handle)

GET is a shortcut for router.Handle("GET", path, handle)

func (*Router) HEAD

func (r *Router) HEAD(path string, handle Handle)

HEAD is a shortcut for router.Handle("HEAD", path, handle)

func (*Router) Handle

func (r *Router) Handle(method, path string, handle 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

func (r *Router) Handler(method, path string, handler http.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

func (r *Router) Lookup(method, path string) (Handle, map[string]string, bool)

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) OPTIONS

func (r *Router) OPTIONS(path string, handle Handle)

OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)

func (*Router) PATCH

func (r *Router) PATCH(path string, handle Handle)

PATCH is a shortcut for router.Handle("PATCH", path, handle)

func (*Router) POST

func (r *Router) POST(path string, handle Handle)

POST is a shortcut for router.Handle("POST", path, handle)

func (*Router) PUT

func (r *Router) PUT(path string, handle Handle)

PUT is a shortcut for router.Handle("PUT", path, handle)

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"))

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto