bast

package module
v1.1.8-0...-5ee8a8c Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2021 License: Apache-2.0 Imports: 41 Imported by: 0

README

bast Build Status

A lightweight RESTful for Golang

support registry and discovery of services

Install


 go get -u github.com/axfor/bast

Router doc(Request example)

Router

Get

//Person struct  
type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
	Addr string `json:"addr"`
}
 
bast.Get("/xxx", func(ctx *bast.Context) {
    //verify imput parameter
    err := ctx.Verify("name@required|min:1", "age@required|min:1", "addr/address@required|min:1")
    if err != nil {
        ctx.Failed(err.Error())
        return
    }

    name := ctx.GetString("name")
    age := ctx.GetInt("age")

    //handling
    //...

    person := &Person{
        Name: name,
        Age:  Age,
    }

    //translator address
    person.Addr = ctx.Trans("addr", person.Name)

    //handling
    //...
    ctx.JSON(person)
})  


Post

//Person struct
type Person struct {
    Name   string    `json:"name" v:"required|min:1"`
    Age    int       `json:"age"  v:"min:1"`
    Title  string    `json:"title"`
}

bast.Post("/xxx", func(ctx *bast.Context) {
    person := &Person{}
    err := ctx.JSONObj(person) 
    //or ctx.JSONObj(person,true) //version of verify imput parameter
    if err != nil {
        ctx.Failed("sorry! invalid parameter")
        return
    }
    person.Age += 2

    //translator title
    person.Title = ctx.Trans("title", person.Name)

    //handling
    //...

    ctx.JSON(person)
})
    

For More


bast.Get(/* pattern string */, /* f func(ctx *Context) */)).Auth().Param("test xxx data")

//service registry to etcd
bast.Get(/* pattern string */, /* f func(ctx *Context) */)).Registry("UserAPI") 



Validate

a similar pipeline validator

Syntax


 key[/key translator][/split divide (default is |)]@verify1[:verify1 param]|verify2

Syntax such as

key1@required|int|min:1     
key2/key2_translator@required|string|min:1|max:12      
key3@sometimes|required|date      

Global register keys translator

note:only is key


//global register keys translator //note:only is key
func init() { 
    //register keys translator //note:is key
    //suck as:verify error
    //en:    The name field is required
    //zh-cn: {0} 不能空 

    lang.RegisterKeys("zh-cn", map[string]string{
	    "name":    "姓名",
	    "age":     "年龄",
	    "address": "地址",
    })

    //other langs 
}

Support for the validator

note:will continue to add new validator

  • date
  • email
  • int
  • ip
  • match
  • max
  • min
  • required
  • sometimes

Http Client

httpc is HTTP client library

install


 go get -u github.com/axfor/bast/httpc

Support for GET POST HEAD POST PUT PATCH DELETE etc

result support string,json,xml,yaml,file etc

string result

	reqUrl := "https://suggest.taobao.com/sug?code=utf-8&q=phone"
	result, err := httpc.Get(reqUrl).String()
	if err != nil {
		//handling
	}

string result by service dscovery version

	result, err := httpc.Gets("UserAPI").String()
	if err != nil {
		//handling
	}

json result

	type tb struct {
		Result [][]string `json:"result"`
	}

	rv := &tb{}

	reqUrl := "https://suggest.taobao.com/sug?code=utf-8"
	err := httpc.Get(reqUrl).Param("q", "phone").ToJSON(rv)
	if err != nil {
		//handling
	}

xml result

	type tb struct {
		Result [][]string `json:"result"`
	}

	rv := &tb{}

	reqUrl := "https://suggest.taobao.com/sug?code=utf-8"
	err := httpc.Get().Param("q", "phone").ToXML(rv)
	if err != nil {
		//handling
	}

yaml result

	type tb struct {
		Result [][]string `json:"result"`
	}

	rv := &tb{}

	reqUrl := "https://suggest.taobao.com/sug?code=utf-8"
	err := httpc.Get(reqUrl).Param("q", "phone").ToYAML(rv)
	if err != nil {
		//handling
	}

save result to file


	reqUrl := "https://suggest.taobao.com/sug?code=utf-8&q=phone"
	err := httpc.Post(reqUrl).ToFile("./files/f.json")
	if err != nil {
		//handling
	}

upload file to server

	reqUrl := "https://suggest.taobao.com/sug?code=utf-8&q=phone"
	result, err := httpc.Post(reqUrl).File("testFile", "./files/f.json").String()
	if err != nil {
		//handling
	}

mark tag and hook's

	reqUrl := "https://suggest.taobao.com/sug?code=utf-8&q=phone"
	result, err := httpc.Post(reqUrl).MarkTag("ai").String()
	if err != nil {
		//handling
	}

Global register hook Before and After


func init() {
	httpc.Before(func(c *httpc.Client) error {
		if c.Tag == "ai" {
			c.Header("xxxx-test-header", "httpc")
		} else {
			//others handling
		}
		return nil
	})

	httpc.After(func(c *httpc.Client) {
		if c.Tag == "ai" && c.OK() {
			//log..
		} else {
			//others handling
		}
	})
} 


Run


bast.Run(":9999")

CommandLine

like nginx commandline

If Your program name is Ai
-h | --help

    ./Ai -h

--start

Run in background


    ./Ai --start

--stop

stop program


    ./Ai --stop

--reload

graceful restart. stop and start


    ./Ai --reload

--conf

seting config files.(default is ./config.conf)


    ./Ai --conf=your path/config.conf 

--install

installed as service.(daemon)


    ./Ai --install

--uninstall

uninstall a service.(daemon)


    ./Ai --uninstall

--migration

migration or initial system(handle sql script ...)


    ./Ai --migration

Such as

run program (run in background)


    ./Ai --start --conf=./config.conf 

deploy program (startup)


    ./Ai --install

config template

support multiple instances

[
    {//a instance
        "key":"xxx-conf",
        "name":"xx",  
        "addr":":9999",
        "fileDir":"./file/",//(default is ./file/)
        "debug":false,
        "baseUrl":"", 
        "idNode":0,  
        "lang":"en",//default lang en,zh-cn 
        "trans":"",//translator files or dir
        "sameSite":"none",//cookie sameSite strict、lax、none 
        "wrap":true,//wrap response body 
        "session":{//session conf
            "enable":false,
            "lifeTime":20,
            "name":"_sid",//session name
            "prefix":"",//session id prefix 
            "suffix":"",//session id suffix 
            "engine":"memory",//session engine memory、redis、redis-cluster 
            "source":"cookie",//cookie、header 
            "sessionLock":false,///each session a lock(default is false)
            "redis":{//if source eq redis or redis-cluster
               "addrs":"ip:port,ip2:port2",
               "password":"",
               "poolSize":0
            }
        },
        "log":{
            "outPath":"./logs/logs.log", //(default is ./logs/logs.log)
            "level":"debug",
            "maxSize":10,
            "maxBackups":3,
            "maxAge":28,
            "debug":false,
            "logSelect":false
        },
        "cors":{//CORS https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
            "allowOrigin":"",
            "allowMethods":"GET, POST, OPTIONS, PATCH, PUT, DELETE, HEAD,UPDATE",
            "allowHeaders":"",
            "maxAge":"1728000",
            "allowCredentials":"true"
        },
        "page":{
            "page":"page name",
            "total":"total name",
            "pageRow":"pageRow name"
        },
        "conf":{//user config(non bast framework) such as db config
            "key":"app",
            "name":"xxx",
            "dbTitle":"xxx app",
            "dbName":"xxxx db",
            "dbUser":"xxx",
            "dbPwd":"******",
            "dbServer":"localhost"
            //..more field..//
        }, 
        "registry":{ //service registry to etcd
            "enable":true,
            "baseUrl":"http://127.0.0.1:9999/",
            "prefix":"bast/",
            "endpoints":"http://127.0.0.1:2379"
        },
        "discovery":{//service discovery from etcd
            "enable":true, 
            "prefix":"bast/",
            "endpoints":"http://127.0.0.1:2379"
        },
        "extend":"",//user extend
        "shutdown":60000,
    }
    //..more instances..//
]

Distributed system unique ID

snowflake-golang or snowflake-twitter

use


  id := bast.ID()
  fmt.Printf("id=%d", id)

benchmark test go test -bench=. -benchmem ./ids
physics cpu 4


    go test   -bench=. -benchmem  ./ids
    goos: darwin
    goarch: amd64 
    Benchmark_ID-4              20000000    72.1 ns/op       16 B/op     1 allocs/op
    Benchmark_Parallel_ID-4     10000000    150 ns/op        16 B/op     1 allocs/op
    PASS
    ok      github.com/axfor/bast/ids 10.126s

Documentation

Index

Constants

View Source
const (
	SerError                = 0       // error code
	SerOK                   = 1       // ok code
	SerDBError              = -10000  // db error code
	SerNoDataError          = -20000  // no data error code
	SerSignOutError         = -30000  // user sign out error code
	SerUserNotExistError    = -40000  // user not exist code
	SerInvalidParamError    = -50000  // invalid param  code
	SerInvalidUserAuthorize = -60000  // invalid user authorize  code
	SerExist                = -70000  // exist code
	SerNotExist             = -80000  // not exist code
	SerTry                  = -99999  // please try code
	SerMustFailed           = -111111 // must failed code
	SerFailed               = -222222 // failed code
	SerAuthorizationFailed  = -888888 // authorization failed code
	KindAcceptJSON          = 0       // json
	KindAcceptXML           = 1       // xml
	KindAcceptYAML          = 2       // yaml
)

const code

Variables

View Source
var (
	Log *logs.Log
)

var

Functions

func After

func After(f AfterHandle)

After set the request 'after' handle

func All

func All(pattern string, f func(ctx *Context))

All registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func AppDir

func AppDir() string

AppDir app path

func AppName

func AppName() string

AppName app name

func Auth

func Auth(f AuthorizationHandle)

Auth set the request 'authorization' handle

func Before

func Before(f BeforeHandle)

Before set the request 'before' handle

func Command

func Command() bool

Command Commandline args

func Conf

func Conf() *conf.AppConf

Conf returns the current app config

func Debug

func Debug(debug bool)

Debug set app debug status

func Exist

func Exist(filename string) bool

Exist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

func ExistAndAutoMkdir

func ExistAndAutoMkdir(filename string) (err error)

ExistAndAutoMkdir Check that the file directory exists, there is no automatically created

func False

func False() *bool

False return a * bool

func FileDefault

func FileDefault(dir string)

FileDefault default file router

func FileDir

func FileDir() string

FileDir if app config configuration fileDir return it,orherwise return app exec path

func FileMerge

func FileMerge(ctx *Context, dir string)

FileMerge files

func FileMergeHandle

func FileMergeHandle(dir string) func(ctx *Context)

FileMergeHandle return merge handle

func FileRouter

func FileRouter(dir, access, upload, merge string)

FileRouter file router

func FileServer

func FileServer(pattern string, root string)

FileServer registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func FileUpload

func FileUpload(ctx *Context, dir, access string)

FileUpload real upload handle

func FileUploadHandle

func FileUploadHandle(dir, access string) func(ctx *Context)

FileUploadHandle return a upload handle

func GUID

func GUID() string

GUID create GUID

func ID

func ID() int64

ID create Unique ID

func IsRuning

func IsRuning() bool

IsRuning return app is runing

func LangDir

func LangDir(dir string) error

LangDir translator dir

func LangFile

func LangFile(file string) error

LangFile translator file

func MaxDay

func MaxDay(month int) int

MaxDay return the maxnum day of the month

func Migration

func Migration(f MigrationHandle)

Migration set migration handler

func NoLookDirHandler

func NoLookDirHandler(h http.Handler) http.Handler

NoLookDirHandler disable directory look

func RegistConf

func RegistConf(handle conf.ConfingHandle, finish ...conf.FinishHandle)

RegistConf handler conf

func Registry

func Registry() error

Registry registry service to etce

func Router

func Router()

Router register to httpRouter

func Run

func Run(addr string) error

Run use addr to start app

func RunWithTLS

func RunWithTLS(addr, certFile, keyFile string) error

RunWithTLS use addr and cert to start app

func Serve

func Serve() bool

Serve use config(auto TLS) to start app

func ServeTLSWithAddr

func ServeTLSWithAddr(addr, certFile, keyFile string) bool

ServeTLSWithAddr use addr and certFile, keyFile to start app

func ServeWithAddr

func ServeWithAddr(addr string) bool

ServeWithAddr use addr to start app

func ServiceName

func ServiceName(key string) string

ServiceName random gets url with service name

func ServiceNames

func ServiceNames(key string) []string

ServiceNames gets all url with service name

func Shutdown

func Shutdown(ctx context.Context) error

Shutdown app

func String

func String(s string) *string

String return a * string

func TimeRangeWithYearMonth

func TimeRangeWithYearMonth(year, month int) (start, end time.Time)

TimeRangeWithYearMonth returns the time(year,month) of the specified mininum and maxnum time

func Trans

func Trans(language, key string, param ...string) string

Trans translator

func Transf

func Transf(language, key string, param ...interface{}) string

Transf translator

func True

func True() *bool

True return a * bool

func TryServe

func TryServe() bool

TryServe try to check the configuration can be turned on 1: is control commandline 2: config is ok

func UserConf

func UserConf() interface{}

UserConf returns the current user config

Types

type AfterHandle

type AfterHandle func(ctx *Context) error

AfterHandle a after handler for each request

type App

type App struct {
	Router *httprouter.Router

	Addr, CertFile, KeyFile string
	Server                  *http.Server
	Before                  BeforeHandle
	After                   AfterHandle
	Authorization           AuthorizationHandle
	Migration               MigrationHandle
	Debug, Daemon           bool
	// contains filtered or unexported fields
}

App is application major data

func (*App) ListenAndServe

func (app *App) ListenAndServe() error

ListenAndServe see net/http ListenAndServe

func (*App) ListenAndServeTLS

func (app *App) ListenAndServeTLS() error

ListenAndServeTLS see net/http ListenAndServeTLS

type AuthorizationHandle

type AuthorizationHandle func(ctx *Context) error

AuthorizationHandle a authorization handler for each request

type BeforeHandle

type BeforeHandle func(ctx *Context) error

BeforeHandle a before handler for each request

type Context

type Context struct {
	//In A Request represents an HTTP request received by a server
	// or to be sent by a client.
	In *http.Request
	//Accept
	Accept string
	//Kind Accept
	KindAccept int
	//Out A ResponseWriter interface is used by an HTTP handler to
	// construct an HTTP response.
	Out http.ResponseWriter
	//Params httprouter Params,/:name/:age
	Params httprouter.Params

	//NeedAuthorization is need authorization
	NeedAuthorization bool
	//IsAuthorization is authorization finish?
	IsAuthorization bool
	//Session is session
	Session engine.Store
	//Router
	Router *Pattern
	// contains filtered or unexported fields
}

Context is app Context

func (*Context) BaseURL

func (c *Context) BaseURL(url ...string) string

BaseURL gets root url(scheme+host) from current request param:

url relative path

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP return request client ip

func (*Context) Data

func (c *Context) Data(v interface{})

Data output Data data to client v data

func (*Context) DataResult

func (c *Context) DataResult(v interface{})

DataResult output Data data to client

func (*Context) DataWithCode

func (c *Context) DataWithCode(v interface{}, code int)

DataWithCode output Data data to client v data code is message code

func (*Context) DataWithCodeMsg

func (c *Context) DataWithCodeMsg(v interface{}, code int, msg string)

DataWithCodeMsg output data to client v data code is message code msg is string message

func (*Context) DataWithMsg

func (c *Context) DataWithMsg(v interface{}, msg string)

DataWithMsg output data to client v data msg is string message

func (*Context) DefaultFileURL

func (c *Context) DefaultFileURL(url string) string

DefaultFileURL returns full file url param:

url is relative path

func (*Context) Exist

func (c *Context) Exist(filename string) bool

Exist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

func (*Context) FailResult

func (c *Context) FailResult(msg string, errCode int, err ...error)

FailResult output fail result to client param:

	msg failed message
	errCode ailed message code
 err  error

func (*Context) Failed

func (c *Context) Failed(msg string, err ...error)

Failed output failed result to client param:

msg is fail message
err error

func (*Context) Failedf

func (c *Context) Failedf(format string, a ...interface{})

Failedf output failed result and format to client

func (*Context) Faileds

func (c *Context) Faileds(msg string, detail string)

Faileds output failed detail result to client param:

msg is fail message
detail is detail message

func (*Context) Flush

func (c *Context) Flush()

Flush sends any buffered data to the client

func (*Context) Form

func (c *Context) Form() url.Values

Form gets all form params from the current(uri not included)

func (*Context) GUID

func (c *Context) GUID() string

GUID return a GUID

func (*Context) GetBool

func (c *Context) GetBool(key string) bool

GetBool get a bool value from the current request based on the key param:

key is key name

func (*Context) GetBoolValue

func (c *Context) GetBoolValue(key string, def bool) bool

GetBoolValue get a bool value from the current request based on the key param:

	key is key name
 def is default value

func (*Context) GetFloat

func (c *Context) GetFloat(key string) (float64, error)

GetFloat gets a float value from the current request uri based on the key param:

key is key name
def default value

func (*Context) GetFloatValue

func (c *Context) GetFloatValue(key string, def float64) float64

GetFloatValue gets a float value from the current request based on the key(errors not included) param:

key is key name
def default value

func (*Context) GetInt

func (c *Context) GetInt(key string) (int, error)

GetInt gets a int value from the current request based on the key param:

key is key name
def default value

func (*Context) GetInt64

func (c *Context) GetInt64(key string) (int64, error)

GetInt64 gets a int64 value from the current request url based on the key param:

key is key name
def default value

func (*Context) GetInt64Value

func (c *Context) GetInt64Value(key string, def int64) int64

GetInt64Value gets a int64 value from the current request based on the key(errors not included) param:

key is key name
def default value

func (*Context) GetIntSlice

func (c *Context) GetIntSlice(key, sep string) []int64

GetIntSlice Use the key to get all int value from the current request param:

	key is key name
 sep spilt char

func (*Context) GetIntSliceAndRemovePrefix

func (c *Context) GetIntSliceAndRemovePrefix(key, sep, prefix string) ([]int64, bool)

GetIntSliceAndRemovePrefix Use the key to get all int value from the current request and remove prefix of each param:

	key is key name
 sep spilt char
 prefix	remove prefix string

func (*Context) GetIntValue

func (c *Context) GetIntValue(key string, def int) int

GetIntValue gets a int value from the current request based on the key(errors not included) param:

key is key name
def default value

func (*Context) GetLang

func (c *Context) GetLang() string

GetLang return

func (*Context) GetLeftLikeString

func (c *Context) GetLeftLikeString(key string) string

GetLeftLikeString get a sql(left like 'xx%') string value from the current request based on the key param:

key is key name

func (*Context) GetLikeString

func (c *Context) GetLikeString(key string) string

GetLikeString get a sql(like '%xx%') string value from the current request based on the key param:

key is key name

func (*Context) GetPage

func (c *Context) GetPage() (page int, total int, pageRow int)

GetPage get page param from the current request and check last page param:

	page 	current page index(start 1)
	total 	all data total count(cache total count for first service return)
 pageRow page maximum size(default is 100 row)

func (*Context) GetParam

func (c *Context) GetParam(key string) string

GetParam Use the key to get all int value from the current request url note:xx/:name/:name2 param:

key key name

func (*Context) GetRightLikeString

func (c *Context) GetRightLikeString(key string) string

GetRightLikeString get a sql(right like '%xx') string value from the current request based on the key param:

key is key name

func (*Context) GetString

func (c *Context) GetString(key string) string

GetString gets a string value from the current request based on the key param:

key is key name

func (*Context) GetStringSlice

func (c *Context) GetStringSlice(key, sep string) []string

GetStringSlice Use the key to get all string value from the current request param:

	key is key name
 sep spilt char

func (*Context) GetStringValue

func (c *Context) GetStringValue(key string, def string) string

GetStringValue gets a string value from the current request based on the key param:

	key is key name
 def is default value

func (*Context) GetStrings

func (c *Context) GetStrings(key string) []string

GetStrings gets strings from the current request based on the key param:

key is key name

func (*Context) GetTrimString

func (c *Context) GetTrimString(key string) string

GetTrimString Use the key to get a non-space string value from the current request param:

key is key name

func (*Context) HasParam

func (c *Context) HasParam(key string) bool

HasParam has a param from the current request based on the key(May not have a value) param:

key is key name

func (*Context) Hijack

func (c *Context) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface.

func (*Context) ID

func (c *Context) ID() int64

ID return a ID

func (*Context) JSON

func (c *Context) JSON(v interface{})

JSON output JSON data to client v data

func (*Context) JSON2String

func (c *Context) JSON2String(obj interface{}) (string, error)

JSON2String JSON to string param:

obj is object

func (*Context) JSONDecode

func (c *Context) JSONDecode(r io.Reader, obj interface{}) (err error)

JSONDecode gets data from the r reader(json fromat) and convert it to a objecet param:

r is a reader
obj target object

func (*Context) JSONObj

func (c *Context) JSONObj(obj interface{}, verify ...bool) error

JSONObj gets data from the current request body(json fromat) and convert it to a objecet param:

	obj 	target object
 verify	verify obj

func (*Context) JSONResult

func (c *Context) JSONResult(v interface{})

JSONResult output json data to client

func (*Context) JSONWithCode

func (c *Context) JSONWithCode(v interface{}, code int)

JSONWithCode output JSON data to client v data code is message code

func (*Context) JSONWithCodeMsg

func (c *Context) JSONWithCodeMsg(v interface{}, code int, msg string)

JSONWithCodeMsg output JSON data to client v data code is message code msg is string message

func (*Context) JSONWithMsg

func (c *Context) JSONWithMsg(v interface{}, msg string)

JSONWithMsg output JSON data to client v data msg is string message

func (*Context) JSONWithPage

func (c *Context) JSONWithPage(v interface{}, page, total int)

JSONWithPage output pagination JSON data to client v data page is page total is total row count

func (*Context) JSONWithPageCode

func (c *Context) JSONWithPageCode(v interface{}, page, total, code int)

JSONWithPageCode output pagination JSON data to client v data page is page total is total row count code is message code

func (*Context) JSONWithPageCodeMsg

func (c *Context) JSONWithPageCodeMsg(v interface{}, page, total, code int, msg string)

JSONWithPageCodeMsg output pagination JSON data to client v data page is page total is total row count code is message code msg is string message

func (*Context) MapObj

func (c *Context) MapObj() map[string]interface{}

MapObj gets current request body and convert it to a map

func (*Context) NoData

func (c *Context) NoData(msg string)

NoData output no data result to client param:

err message

func (*Context) Obj

func (c *Context) Obj(obj interface{}, verify ...bool) error

Obj gets data from the current request body(json or xml or yaml fromat) and convert it to a objecet param:

	obj 	target object
 verify	verify obj

func (*Context) ObjWithCodeMsg

func (c *Context) ObjWithCodeMsg(v interface{}, code int, msg string) interface{}

ObjWithCodeMsg return obj data v data code is message code msg is string message

func (*Context) ObjWithPageCodeMsg

func (c *Context) ObjWithPageCodeMsg(v interface{}, page, total, code int, msg string) interface{}

ObjWithPageCodeMsg return pagination obj data v data page is page total is total row count code is message code msg is string message

func (*Context) Offset

func (c *Context) Offset(total int) int

Offset return page offset param:

total 	all data total count(cache total count for first service return)

func (*Context) Page

func (c *Context) Page(v interface{}, page, total int)

Page output pagination data data to client v data page is page total is total row count

func (*Context) PageWithCode

func (c *Context) PageWithCode(v interface{}, page, total, code int)

PageWithCode output pagination data to client v data page is page total is total row count code is message code

func (*Context) PageWithCodeMsg

func (c *Context) PageWithCodeMsg(v interface{}, page, total, code int, msg string)

PageWithCodeMsg output pagination data to client v data page is page total is total row count code is message code msg is string message

func (*Context) ParseForm

func (c *Context) ParseForm()

ParseForm populates r.Form and r.PostForm.

For all requests, ParseForm parses the raw query from the URL and updates r.Form.

For POST, PUT, and PATCH requests, it also parses the request body as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form.

For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.

If the request Body's size has not already been limited by MaxBytesReader, the size is capped at 10MB.

ParseMultipartForm calls ParseForm automatically. ParseForm is idempotent.

func (*Context) ParseMultipartForm

func (c *Context) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files. ParseMultipartForm calls ParseForm if necessary. After one call to ParseMultipartForm, subsequent calls have no effect.

func (*Context) PostForm

func (c *Context) PostForm() url.Values

PostForm gets all form params from the current(uri and form)

func (*Context) Proxys

func (c *Context) Proxys() []string

Proxys return request proxys if request header has X-Real-IP, return it if request header has X-Forwarded-For, return it

func (*Context) Pusher

func (c *Context) Pusher() http.Pusher

Pusher is the interface implemented by ResponseWriters that support HTTP/2 server push. For more background, see https://tools.ietf.org/html/rfc7540#section-8.2.

func (*Context) Query

func (c *Context) Query() url.Values

Query gets all query params from the current request url

func (*Context) RawString

func (c *Context) RawString() string

RawString getter raw string value from current request(request body)

func (*Context) Redirect

func (c *Context) Redirect(url string)

Redirect redirect

func (*Context) Reset

func (c *Context) Reset()

Reset current context to pool

func (*Context) Result

func (c *Context) Result(msg string, detail ...string)

Result output result to client param:

msg is fail message
detail is detail message

func (*Context) Say

func (c *Context) Say(data []byte)

Say output raw bytes to client param:

data raw bytes

func (*Context) Says

func (c *Context) Says(str string)

Says output string to client param:

str string

func (*Context) SendFile

func (c *Context) SendFile(fileName string, rawFileName ...string)

SendFile send file to client param:

	fileName is file name
 rawFileName is raw file name

func (*Context) SessionClear

func (c *Context) SessionClear() error

SessionClear delete all session

func (*Context) SessionDelete

func (c *Context) SessionDelete(key string) error

SessionDelete delete session value by key

func (*Context) SessionID

func (c *Context) SessionID() string

SessionID get sessionID

func (*Context) SessionRead

func (c *Context) SessionRead(key string) interface{}

SessionRead get session value by key

func (*Context) SessionWrite

func (c *Context) SessionWrite(key string, value interface{}) error

SessionWrite set session value by key

func (*Context) SignOut

func (c *Context) SignOut(msg string)

SignOut output user signout to client param:

msg message

func (*Context) StatusCode

func (c *Context) StatusCode(statusCode int)

StatusCode set current request statusCode param:

statusCode HTTP status code. such as: 200x,300x and so on

func (*Context) String2JSON

func (c *Context) String2JSON(str string, obj interface{}) error

String2JSON string to JSON param:

	str json string
 obj is object

func (*Context) Success

func (c *Context) Success(msg string)

Success output success result to client

msg is success message

func (*Context) Successf

func (c *Context) Successf(format string, a ...interface{})

Successf output success result and format to client

func (*Context) TemporaryRedirect

func (c *Context) TemporaryRedirect(url string)

TemporaryRedirect redirect(note: 307 redirect,Can avoid data loss after POST redirection)

func (*Context) Trans

func (c *Context) Trans(key string, param ...string) string

Trans translator

func (*Context) Transf

func (c *Context) Transf(key string, param ...interface{}) string

Transf translator

func (*Context) URL

func (c *Context) URL() string

URL get eequest url

func (*Context) Validate

func (c *Context) Validate(rules ...string) error

Validate verify current request param: rules is validate rule such as:

key1@required|int|min:1
key2/key2_translator@required|string|min:1
key3@sometimes|required|data

func (*Context) Verify

func (c *Context) Verify(rules ...string) error

Verify verify current request param: rules is validate rule such as:

key1@required|int|min:1
key2/key2_translator@required|string|min:1
key3@sometimes|required|data

func (*Context) XML

func (c *Context) XML(v interface{})

XML output XML data to client v data

func (*Context) XMLDecode

func (c *Context) XMLDecode(r io.Reader, obj interface{}) (err error)

XMLDecode gets data from the r reader(xml format) and convert it to a object param:

r is a reader
obj target object

func (*Context) XMLObj

func (c *Context) XMLObj(obj interface{}, verify ...bool) error

XMLObj gets data from the current request(xml format) and convert it to a object param:

	obj 	target object
 verify	verify obj

func (*Context) XMLResult

func (c *Context) XMLResult(v interface{})

XMLResult output xml data to client

func (*Context) XMLWithCode

func (c *Context) XMLWithCode(v interface{}, code int)

XMLWithCode output XML data to client v data code is message code

func (*Context) XMLWithCodeMsg

func (c *Context) XMLWithCodeMsg(v interface{}, code int, msg string)

XMLWithCodeMsg output XML data to client v data code is message code msg is string message

func (*Context) XMLWithMsg

func (c *Context) XMLWithMsg(v interface{}, msg string)

XMLWithMsg output XML data to client v data msg is string message

func (*Context) XMLWithPage

func (c *Context) XMLWithPage(v interface{}, page, total int)

XMLWithPage output pagination XML data to client v data page is page total is total row count

func (*Context) XMLWithPageCode

func (c *Context) XMLWithPageCode(v interface{}, page, total, code int)

XMLWithPageCode output pagination XML data to client v data page is page total is total row count code is message code

func (*Context) XMLWithPageCodeMsg

func (c *Context) XMLWithPageCodeMsg(v interface{}, page, total, code int, msg string)

XMLWithPageCodeMsg output pagination XML data to client v data page is page total is total row count code is message code msg is string message

func (*Context) YAML

func (c *Context) YAML(v interface{})

YAML output YAML data to client v data

func (*Context) YAMLDecode

func (c *Context) YAMLDecode(r io.Reader, obj interface{}) (err error)

YAMLDecode gets data from the r reader(yaml format) and convert it to a object param:

r is a reader
obj target object

func (*Context) YAMLObj

func (c *Context) YAMLObj(obj interface{}, verify ...bool) error

YAMLObj gets data from the current request(yaml format) and convert it to a object param:

	obj 	target object
 verify	verify obj

func (*Context) YAMLResult

func (c *Context) YAMLResult(v interface{})

YAMLResult output yaml data to client

func (*Context) YAMLWithCode

func (c *Context) YAMLWithCode(v interface{}, code int)

YAMLWithCode output YAML data to client v data code is message code

func (*Context) YAMLWithCodeMsg

func (c *Context) YAMLWithCodeMsg(v interface{}, code int, msg string)

YAMLWithCodeMsg output YAML data to client v data code is message code msg is string message

func (*Context) YAMLWithMsg

func (c *Context) YAMLWithMsg(v interface{}, msg string)

YAMLWithMsg output YAML data to client v data msg is string message

func (*Context) YAMLWithPage

func (c *Context) YAMLWithPage(v interface{}, page, total int)

YAMLWithPage output pagination YAML data to client v data page is page total is total row count

func (*Context) YAMLWithPageCode

func (c *Context) YAMLWithPageCode(v interface{}, page, total, code int)

YAMLWithPageCode output pagination YAML data to client v data page is page total is total row count code is message code

func (*Context) YAMLWithPageCodeMsg

func (c *Context) YAMLWithPageCodeMsg(v interface{}, page, total, code int, msg string)

YAMLWithPageCodeMsg output pagination YAML data to client v data page is page total is total row count code is message code msg is string message

type Date

type Date Time

Date yyyy-MM-dd format date 1: auto handle string to time

func DateByBTime

func DateByBTime(t Time) Date

DateByBTime bast.Time to Date

func DateByBTimes

func DateByBTimes(t *Time) Date

DateByBTimes *bast.Time to Date

func DateByTime

func DateByTime(t time.Time) Date

DateByTime time.Time to Date

func DateWithString

func DateWithString(t string, layout ...string) (Date, error)

DateWithString string to Date

func DatesByBTime

func DatesByBTime(t Time) *Date

DatesByBTime *bast.Time to *Date

func DatesByBTimes

func DatesByBTimes(t *Time) *Date

DatesByBTimes *bast.Time to *Date

func DatesByTime

func DatesByTime(t time.Time) *Date

DatesByTime time.Time to *Date

func DatesWithString

func DatesWithString(t string, layout ...string) (*Date, error)

DatesWithString string to *Date

func NowDate

func NowDate() Date

NowDate returns the current local date.

func NowDates

func NowDates() *Date

NowDates returns the current local *date.

func (Date) After

func (t Date) After(u Date) bool

After reports whether the time instant t is after u.

func (Date) Before

func (t Date) Before(u Date) bool

Before reports whether the time instant t is before u.

func (Date) Equal

func (t Date) Equal(u Date) bool

Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 CEST and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.

func (Date) MarshalJSON

func (t Date) MarshalJSON() ([]byte, error)

MarshalJSON JSON MarshalJSON

func (*Date) Scan

func (t *Date) Scan(v interface{}) error

Scan support scan

func (Date) String

func (t Date) String() string

String

func (*Date) UnmarshalJSON

func (t *Date) UnmarshalJSON(b []byte) error

UnmarshalJSON JSON UnmarshalJSON

func (Date) Value

func (t Date) Value() (driver.Value, error)

Value support sql.Driver interface

type Datum

type Datum struct {
	Message `yaml:",inline"`
	XMLName xml.Name    `xml:"data"  json:"-" yaml:"-"`
	Data    interface{} `json:"data" xml:"data>data" yaml:"data"`
}

Datum is response data

type Float32

type Float32 float32

Float32 is auto handle string to float32

func (*Float32) UnmarshalJSON

func (c *Float32) UnmarshalJSON(b []byte) error

UnmarshalJSON JSON UnmarshalJSON

type Float64

type Float64 float64

Float64 is auto handle string to float64

func (*Float64) UnmarshalJSON

func (c *Float64) UnmarshalJSON(b []byte) error

UnmarshalJSON JSON UnmarshalJSON

type Fs

type Fs struct {
	FileName string `json:"fileName"`
	RawName  string `json:"rawName"`
	Chunks   int    `json:"chunks"`
}

Fs struct

type Int

type Int int

Int is auto handle string to int

func (*Int) UnmarshalJSON

func (c *Int) UnmarshalJSON(b []byte) error

UnmarshalJSON JSON UnmarshalJSON

type Int64

type Int64 int64

Int64 is auto handle string to int64

func (*Int64) UnmarshalJSON

func (c *Int64) UnmarshalJSON(b []byte) error

UnmarshalJSON JSON UnmarshalJSON

type InvalidPagination

type InvalidPagination struct {
	Pagination `yaml:",inline"`
	XMLName    xml.Name `xml:"page" json:"-" yaml:"-"`
	Invalid    bool     `json:"invalid" xml:"invalid" yaml:"invalid"`
	Fix        bool     `json:"fix" xml:"fix" yaml:"fix"`
}

InvalidPagination is invalid Pagination data

type Message

type Message struct {
	XMLName xml.Name `xml:"msg" json:"-" yaml:"-"`
	Code    int      `json:"code" xml:"code" yaml:"code"`
	Msg     string   `json:"msg" xml:"msg" yaml:"msg"`
}

Message is response message

type MessageDetail

type MessageDetail struct {
	XMLName xml.Name `xml:"msg" json:"-" yaml:"-"`
	Code    int      `json:"code" xml:"code" yaml:"code"`
	Msg     string   `json:"msg" xml:"msg" yaml:"msg"`
	Detail  string   `json:"detail" xml:"detail" yaml:"detail"`
}

MessageDetail is response detail message

type MethodNotAllowedHandler

type MethodNotAllowedHandler struct {
}

MethodNotAllowedHandler method Not Allowed

func (MethodNotAllowedHandler) ServeHTTP

ServeHTTP method Not Allowed handler

type MethodOptionsHandler

type MethodOptionsHandler struct {
}

MethodOptionsHandler method Options

func (MethodOptionsHandler) ServeHTTP

ServeHTTP method Options handler

type MigrationHandle

type MigrationHandle func() error

MigrationHandle is migration handler

type NotFoundHandler

type NotFoundHandler struct {
}

NotFoundHandler not found

func (NotFoundHandler) ServeHTTP

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

ServeHTTP not found handler

type Pagination

type Pagination struct {
	Message `yaml:",inline"`
	XMLName xml.Name    `xml:"page" json:"-" yaml:"-"`
	Data    interface{} `json:"data" xml:"data>data" yaml:"data"`
	Page    int         `json:"page" xml:"page" yaml:"page"`
	Total   int         `json:"total" xml:"total" yaml:"total"`
}

Pagination is Pagination data

type Pattern

type Pattern struct {
	Method    string
	Pattern   string
	Fn        func(ctx *Context)
	Parameter interface{}
	Name      string
	Service   string
	// contains filtered or unexported fields
}

Pattern Pattern obj

func Delete

func Delete(pattern string, f func(ctx *Context)) *Pattern

Delete registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func Get

func Get(pattern string, f func(ctx *Context)) *Pattern

Get registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func Head(pattern string, f func(ctx *Context)) *Pattern

Head registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func Options

func Options(pattern string, f func(ctx *Context)) *Pattern

Options registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func Patch

func Patch(pattern string, f func(ctx *Context)) *Pattern

Patch registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func Post

func Post(pattern string, f func(ctx *Context)) *Pattern

Post registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func Put

func Put(pattern string, f func(ctx *Context)) *Pattern

Put registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func (*Pattern) Auth

func (c *Pattern) Auth() *Pattern

Auth need api authorization eq Authorization

func (*Pattern) Nickname

func (c *Pattern) Nickname(name string) *Pattern

Nickname set nickname

func (*Pattern) Param

func (c *Pattern) Param(Parameter interface{}) *Pattern

Param set pouter parameter

func (*Pattern) Registry

func (c *Pattern) Registry(service string) *Pattern

Registry register to etcd etc.

func (*Pattern) Router

func (c *Pattern) Router() *Pattern

Router register to httpRouter

func (*Pattern) Unauth

func (c *Pattern) Unauth() *Pattern

Unauth need api Unauthorization eq Unauthorization

func (*Pattern) Unregistry

func (c *Pattern) Unregistry() *Pattern

Unregistry unregister to etcd etc.

type Time

type Time struct {
	time.Time
}

Time yyyy-MM-dd HH:mm:ss format time 1: auto handle string to time

func Now

func Now() Time

Now returns the current local time.

func NowTime

func NowTime() *Time

NowTime returns the current local *time.

func Nows

func Nows() *Time

Nows returns the current local *time.

func NowsNil

func NowsNil() *Time

NowsNil returns the nil *bast.time.

func TimeByDate

func TimeByDate(d Date) Time

TimeByDate Date to Time

func TimeByDates

func TimeByDates(d *Date) Time

TimeByDates *Date to Time

func TimeByTime

func TimeByTime(t time.Time) Time

TimeByTime time.Time to Time

func TimeWithString

func TimeWithString(t string, layout ...string) (Time, error)

TimeWithString string to Time

func TimesByDate

func TimesByDate(d Date) *Time

TimesByDate Date to *Time

func TimesByDates

func TimesByDates(d *Date) *Time

TimesByDates *Date to *Time

func TimesByTime

func TimesByTime(t time.Time) *Time

TimesByTime time.Time to *Time

func TimesWithString

func TimesWithString(t string, layout ...string) (*Time, error)

TimesWithString string to *Time

func (Time) After

func (t Time) After(u Time) bool

After reports whether the time instant t is after u.

func (Time) Before

func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u.

func (Time) Equal

func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 CEST and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.

func (Time) Format

func (t Time) Format(layout string) string

Format return format string time layout support yyyy、MM、dd、hh、HH、mm、ss

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON JSON MarshalJSON

func (*Time) Scan

func (t *Time) Scan(v interface{}) error

Scan support scan

func (Time) String

func (t Time) String() string

String

func (*Time) T

func (t *Time) T() *time.Time

T get time.Time if zero time return nil

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON JSON UnmarshalJSON

func (Time) Value

func (t Time) Value() (driver.Value, error)

Value support sql.Driver interface

type UInt

type UInt uint

UInt is auto handle string to uint

func (*UInt) UnmarshalJSON

func (c *UInt) UnmarshalJSON(b []byte) error

UnmarshalJSON JSON UnmarshalJSON

type UInt64

type UInt64 uint64

UInt64 is auto handle string to uint

func (*UInt64) UnmarshalJSON

func (c *UInt64) UnmarshalJSON(b []byte) error

UnmarshalJSON JSON UnmarshalJSON

Directories

Path Synopsis
Package snowflake provides a very simple Twitter snowflake generator and parser.
Package snowflake provides a very simple Twitter snowflake generator and parser.

Jump to

Keyboard shortcuts

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