util

package module
v0.0.0-...-a5168ab Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2019 License: MIT Imports: 36 Imported by: 0

README

util

csacred.com chuangxin1.com util

Documentation

Index

Constants

View Source
const (
	// DBErrCodeOK ok
	DBErrCodeOK = 0
	// DBErrCodeException exception
	DBErrCodeException = 1
	// DBErrCodeExists exists
	DBErrCodeExists = 2
	// DBErrCodeNotFound not found
	DBErrCodeNotFound = 3
	// DBErrCodeAuthorized authorized
	DBErrCodeAuthorized = 4
	// DBErrCodeNotConnect connect error
	DBErrCodeNotConnect = 5
)
View Source
const (
	// ErrOk OK
	ErrOk = 0
	// ErrNotFound 404 route not found
	ErrNotFound = 1001
	// ErrException 500
	ErrException = 1002
	// ErrBadRequest 400 route params error
	ErrBadRequest = 1003
	// ErrMethodNotAllowed 405
	ErrMethodNotAllowed = 1004
	// ErrParamsError 415
	ErrParamsError = 1005
	// ErrUnAuthorized 401
	ErrUnAuthorized = 1006
	// ErrDataNotFound 404
	ErrDataNotFound = 1007
	// ErrNotAllowed 405
	ErrNotAllowed = 1008
	// ErrDataExists 400
	ErrDataExists = 1009
	// ErrDataValidate 403
	ErrDataValidate = 1010

	// VarUserAuthorization oauth token
	VarUserAuthorization = `access_token`

	// HTTPHeaderAuthorization HTTP header Authorization
	HTTPHeaderAuthorization = `Authorization`
	// HTTPHeaderToken HTTP header Authorization X-Token
	HTTPHeaderToken = `X-Token`
)
View Source
const (

	// KB  kilo byte
	KB int = 1 << (10 * iota)
	// MB mega byte
	MB
	// GB giga byte
	GB
)
View Source
const (
	// LibName toolkit name Go micro service
	LibName = `GMS`
	// LibVersion toolkit version
	LibVersion = `0.2.2`
)
View Source
const (
	// RequestTimeOut http request timeout (second)
	RequestTimeOut = 30
)

Variables

This section is empty.

Functions

func AddDeleteHandle

func AddDeleteHandle(router *httprouter.Router, route string, handle Handle)

AddDeleteHandle add handle to router

func AddGetHandle

func AddGetHandle(router *httprouter.Router, route string, handle Handle)

AddGetHandle add handle to router

func AddHandler

func AddHandler(router *httprouter.Router, method, route string, handler http.Handler)

AddHandler add handler to router

func AddHeadHandle

func AddHeadHandle(router *httprouter.Router, route string, handle Handle)

AddHeadHandle add handle to router

func AddOptionsHandle

func AddOptionsHandle(router *httprouter.Router, route string, handle Handle)

AddOptionsHandle add handle to router

func AddPatchHandle

func AddPatchHandle(router *httprouter.Router, route string, handle Handle)

AddPatchHandle add handle to router

func AddPostHandle

func AddPostHandle(router *httprouter.Router, route string, handle Handle)

AddPostHandle add handle to router

func AddPutHandle

func AddPutHandle(router *httprouter.Router, route string, handle Handle)

AddPutHandle add handle to router

func CloseDefaultLogger

func CloseDefaultLogger() error

CloseDefaultLogger close

func ContextGet

func ContextGet(ctx context.Context, key interface{}) interface{}

ContextGet get from context

func ContextSet

func ContextSet(r *http.Request, key, val interface{}) *http.Request

ContextSet set to context

func ErrSQLNoRows

func ErrSQLNoRows(err error) bool

ErrSQLNoRows check norows error

func GetAesCryptoKey

func GetAesCryptoKey() string

GetAesCryptoKey get current key

func GetRealIP

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

GetRealIP get real IP from Request

func HTMLEscape

func HTMLEscape(url string) string

HTMLEscape html special char convert

space to &quot;, & to &amp;, < to &lt;, > to &gt;

func HTMLUnEscape

func HTMLUnEscape(url string) string

HTMLUnEscape html special char convert

&quot; to space, &amp; to &, &lt; to <, &gt; to >

func HTTPListenAndServe

func HTTPListenAndServe(addr string, router http.Handler)

HTTPListenAndServe new server and start

func LogDebug

func LogDebug(v ...interface{})

LogDebug log debug

func LogInfo

func LogInfo(v ...interface{})

LogInfo log info

func MD5

func MD5(data string) string

MD5 hash string

func ReadSerial

func ReadSerial(name string, baudrate int, bits byte) (data []byte, err error)

ReadSerial read from serial

func Redirect

func Redirect(w http.ResponseWriter, url string)

Redirect redirect

func ReleaseConfigDB

func ReleaseConfigDB(dbx *DB)

ReleaseConfigDB free db connect

func ReleaseDB

func ReleaseDB()

ReleaseDB free db connect

func ResponseJSON

func ResponseJSON(reply *ReplyData, err error, req *http.Request, w http.ResponseWriter) error

ResponseJSON reply JSON

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

SetAesCryptoKey set key, key 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 SetDbConfig

func SetDbConfig(cfg DbConfig)

SetDbConfig set

func WriteBytes

func WriteBytes(w http.ResponseWriter, response interface{}) error

WriteBytes response bytes

func WriteBytesContentType

func WriteBytesContentType(w http.ResponseWriter, response interface{}, contentType string) error

WriteBytesContentType response bytes and Content-Type

func WriteCtxBytes

func WriteCtxBytes(ctx context.Context, w http.ResponseWriter, response interface{}) error

WriteCtxBytes response text data.

func WriteCtxJSON

func WriteCtxJSON(ctx context.Context, w http.ResponseWriter, response interface{}) error

WriteCtxJSON response JSON data.

func WriteCtxXML

func WriteCtxXML(ctx context.Context, w http.ResponseWriter, response interface{}) error

WriteCtxXML response XML data.

func WriteJSON

func WriteJSON(w io.Writer, 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
}

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(origData []byte) ([]byte, error)

Encrypt encrypt data

func (*AesCrypto) SetKey

func (a *AesCrypto) SetKey(key string)

SetKey set key

type ContextKey

type ContextKey string

ContextKey context key type

type DB

type DB struct {
	Driver string
	// contains filtered or unexported fields
}

DB define

func NewConfigDB

func NewConfigDB(config DbConfig) (dbx *DB, err error)

NewConfigDB new DB dynamic object

func NewDB

func NewDB() *DB

NewDB new DB object

func (*DB) BeginTrans

func (d *DB) BeginTrans() (err error)

BeginTrans begin trans

func (*DB) Close

func (d *DB) Close()

Close close database connect

func (*DB) Commit

func (d *DB) Commit() error

Commit commit

func (*DB) Connect

func (d *DB) Connect() (err error)

Connect connect to database

func (*DB) Insert

func (d *DB) Insert(query string, args interface{}) (LastInsertId, RowsAffected int64, err error)

Insert insert into

func (*DB) InsertReply

func (d *DB) InsertReply(query string, args interface{}) (reply DbReply)

InsertReply insert and return DbReply

func (*DB) Limit

func (d *DB) Limit(page, pagesize int) string

Limit MySQL / PostgreSQL limit offset

func (*DB) Rollback

func (d *DB) Rollback() error

Rollback rollback

func (*DB) Row

func (d *DB) Row(dest interface{}, query string, args interface{}) error

Row get row

func (*DB) Rows

func (d *DB) Rows(dest interface{}, query string, args interface{}) error

Rows get rows

func (*DB) TransExec

func (d *DB) TransExec(query string, args interface{}) (LastInsertId, RowsAffected int64, err error)

TransExec trans execute

func (*DB) TransUpdate

func (d *DB) TransUpdate(query string, args interface{}) (reply DbReply)

TransUpdate trans update

func (*DB) Update

func (d *DB) Update(query string, args interface{}) (RowsAffected int64, err error)

Update update/delete

func (*DB) UpdateReply

func (d *DB) UpdateReply(query string, args interface{}) (reply DbReply)

UpdateReply update/delete and return DbReply

type DbConfig

type DbConfig struct {
	Driver       string
	DNS          string
	MaxOpenConns int
	MaxIdle      int
	MaxLifetime  time.Duration
}

DbConfig config

type DbReply

type DbReply struct {
	OK           bool
	Err          error
	LastErr      error
	ErrCode      int
	LastID       int64
	RowsAffected int64
}

DbReply db exec return insert/update/delete

func DbReplyFaild

func DbReplyFaild(errCode int, err, errText error) DbReply

DbReplyFaild exec faild

func DbReplyOk

func DbReplyOk(rowsAffected, lastID int64) DbReply

DbReplyOk exec ok

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.

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) 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 {
	FP  *os.File
	Log *log.Logger
}

Logger logger

func NewDefaultLogger

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

NewDefaultLogger defult logger

func NewLogger

func NewLogger(path string) (logger *Logger, err error)

NewLogger new

func ReopenDefaultLogger

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

ReopenDefaultLogger re open default logger

func (Logger) Close

func (logger Logger) Close() error

Close close

func (Logger) Debug

func (logger Logger) Debug(v ...interface{})

Debug log debug

func (Logger) Info

func (logger Logger) Info(v ...interface{})

Info log info

type Map

type Map map[string]interface{}

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

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 Message

type Message struct {
	StatusCode int
	Body       []byte
	Header     http.Header
	Cookies    []*http.Cookie
}

Message HTTP response

func Get

func Get(uri, certPath, keyPath string, header map[string]string) (msg Message, err error)

Get HTTP request GET

func Post

func Post(uri, certPath, keyPath string, header map[string]string, data io.Reader) (msg Message, err error)

Post HTTP request POST

type Queue

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

Queue concurrency safe list

func NewQueue

func NewQueue() *Queue

NewQueue new queue

func (*Queue) Back

func (q *Queue) Back() *list.Element

Back returns the last element of list l or nil if the list is empty.

func (*Queue) Front

func (q *Queue) Front() *list.Element

Front returns the first element of list l or nil if the list is empty.

func (*Queue) Init

func (q *Queue) Init(v interface{}, mark *list.Element) *list.List

Init initializes or clears list l.

func (*Queue) InsertAfter

func (q *Queue) InsertAfter(v interface{}, mark *list.Element) *list.Element

InsertAfter inserts a new element e with value v immediately after mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

func (*Queue) InsertBefore

func (q *Queue) InsertBefore(v interface{}, mark *list.Element) *list.Element

InsertBefore inserts a new element e with value v immediately before mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

func (*Queue) Len

func (q *Queue) Len() int

Len returns the number of elements of list l. The complexity is O(1).

func (*Queue) PushBack

func (q *Queue) PushBack(v interface{}) *list.Element

PushBack inserts a new element e with value v at the back of list l and returns e.

func (*Queue) PushFront

func (q *Queue) PushFront(v interface{}) *list.Element

PushFront inserts a new element e with value v at the front of list l and returns e.

func (*Queue) Remove

func (q *Queue) Remove(e *list.Element) interface{}

Remove removes e from l if e is an element of list l. It returns the element value e.Value. The element must not be nil.

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 DbReplyToReply

func DbReplyToReply(reply DbReply) *ReplyData

DbReplyToReply db reply to respinse

func ErrReplyData

func ErrReplyData(status int, message string) *ReplyData

ErrReplyData creates and return ReplyData with error and message

func ErrorsReplyData

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

ErrorsReplyData creates and return ReplyData with errors

func NewReplyData

func NewReplyData(status int) *ReplyData

NewReplyData creates and return ReplyData with status and message

func OkReplyData

func OkReplyData() *ReplyData

OkReplyData creates and return ReplyData with ok

func RowReplyData

func RowReplyData(row interface{}) *ReplyData

RowReplyData creates and return ReplyData with attr row

func RowsReplyData

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

RowsReplyData creates and return ReplyData with total and list

type Router

type Router = httprouter.Router

Router router

func NewRouter

func NewRouter() *Router

NewRouter new http router with default route

type RouterHandler

type RouterHandler struct {
	Method string
	Router string
	Hander http.Handler
}

RouterHandler hander

Directories

Path Synopsis
Package httprouter is a trie based high performance HTTP request router.
Package httprouter is a trie based high performance HTTP request router.

Jump to

Keyboard shortcuts

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