Documentation ¶
Overview ¶
Example ¶
package main import ( "strconv" "github.com/emicklei/go-restful" "github.com/tuotoo/biu" ) // Foo controller type Foo struct{} // WebService implements CtlInterface func (ctl Foo) WebService(ws biu.WS) { ws.Route(ws.GET("/").To(biu.Handle(ctl.getBar)). Param(ws.QueryParameter("num", "number").DataType("integer")). Doc("Get Bar").DefaultReturns("Bar", Bar{}), &biu.RouteOpt{ Errors: map[int]string{ 100: "num not Number", }, }) // add more routes as you like: // ws.Route(ws.POST("/foo"),nil) // ... } // Bar is the response of getBar type Bar struct { Msg string `json:"msg"` Num int `json:"num"` } func (ctl Foo) getBar(ctx biu.Ctx) { numStr := ctx.QueryParameter("num") num, err := strconv.Atoi(numStr) if ctx.ContainsError(err, 100) { return } ctx.ResponseJSON(Bar{Msg: "bar", Num: num}) } func main() { restful.Filter(biu.LogFilter()) biu.AddServices("/v1", nil, biu.NS{ NameSpace: "foo", Controller: Foo{}, Desc: "Foo Controller", }, ) // Note: you should add swagger service after adding services. // swagger document will be available at http://localhost:8080/v1/swagger swaggerService := biu.NewSwaggerService(biu.SwaggerInfo{ Title: "Foo Bar", Description: "Foo Bar Service", ContactName: "Tuotoo", ContactEmail: "jqs7@tuotoo.com", ContactURL: "https://tuotoo.com", Version: "1.0.0", RoutePrefix: "/v1", }) restful.Add(swaggerService) biu.Run(":8080", nil) }
Output:
Index ¶
- Constants
- Variables
- func AddServices(prefix string, filters []restful.FilterFunction, wss ...NS)
- func AuthFilter(code int) restful.FilterFunction
- func CheckError(err error, log *LogEvt) bool
- func CheckToken(token string) (userID string, err error)
- func ContainsError(w http.ResponseWriter, RouteSignature string, err error, code int) bool
- func Debug(msg string, evt *LogEvt)
- func Error(msg string, evt *LogEvt)
- func Fatal(msg string, evt *LogEvt)
- func Filter(f func(ctx Ctx)) restful.FilterFunction
- func Handle(f func(ctx Ctx)) restful.RouteFunction
- func Info(msg string, evt *LogEvt)
- func LogFilter() restful.FilterFunction
- func Logger() zerolog.Logger
- func NewSwaggerService(info SwaggerInfo) *restful.WebService
- func Panic(msg string, evt *LogEvt)
- func ParseToken(token string) (*jwt.Token, error)
- func RefreshToken(token string) (newToken string, err error)
- func ResponseError(w http.ResponseWriter, routeID string, msg string, code int)
- func ResponseJSON(w http.ResponseWriter, routeID string, v interface{})
- func Run(addr string, cfg *RunConfig)
- func SetLoggerLevel(level zerolog.Level)
- func SetLoggerOutput(w io.Writer)
- func Sign(userID string) (token string, err error)
- func Warn(msg string, evt *LogEvt)
- func WrapHandler(f func(ctx Ctx)) http.HandlerFunc
- type CommonResp
- type Container
- type CtlInterface
- type Ctx
- func (ctx *Ctx) Bind(obj interface{}) error
- func (ctx *Ctx) BindJSON(obj interface{}) error
- func (ctx *Ctx) BindQuery(obj interface{}) error
- func (ctx *Ctx) BindWith(obj interface{}, b binding.Binding) error
- func (ctx *Ctx) BodyParameterValues(name string) ([]string, error)
- func (ctx *Ctx) ContainsError(err error, code int, v ...interface{}) bool
- func (ctx *Ctx) ErrMsg(code int) string
- func (ctx *Ctx) Form(name string) Parameter
- func (ctx *Ctx) Header(name string) Parameter
- func (ctx *Ctx) IP() string
- func (ctx *Ctx) IsLogin() (userID string, err error)
- func (ctx *Ctx) Path(name string) Parameter
- func (ctx *Ctx) Proxy() []string
- func (ctx *Ctx) Query(name string) Parameter
- func (ctx *Ctx) Redirect(url string, code int)
- func (ctx *Ctx) ResponseError(msg string, code int)
- func (ctx *Ctx) ResponseJSON(v interface{})
- func (ctx *Ctx) ResponseStdErrCode(code int, v ...interface{})
- func (ctx *Ctx) RouteID() string
- func (ctx *Ctx) RouteSignature() string
- func (ctx *Ctx) UserID() string
- type LogEvt
- type NS
- type Parameter
- func (p Parameter) Bool() (bool, error)
- func (p Parameter) BoolArray() ([]bool, error)
- func (p Parameter) BoolDefault(defaultValue bool) bool
- func (p Parameter) Float32() (float32, error)
- func (p Parameter) Float32Array() ([]float32, error)
- func (p Parameter) Float32Default(defaultValue float32) float32
- func (p Parameter) Float64() (float64, error)
- func (p Parameter) Float64Array() ([]float64, error)
- func (p Parameter) Float64Default(defaultValue float64) float64
- func (p Parameter) Int() (int, error)
- func (p Parameter) Int16() (int16, error)
- func (p Parameter) Int16Array() ([]int16, error)
- func (p Parameter) Int16Default(defaultValue int16) int16
- func (p Parameter) Int32() (int32, error)
- func (p Parameter) Int32Array() ([]int32, error)
- func (p Parameter) Int32Default(defaultValue int32) int32
- func (p Parameter) Int64() (int64, error)
- func (p Parameter) Int64Array() ([]int64, error)
- func (p Parameter) Int64Default(defaultValue int64) int64
- func (p Parameter) Int8() (int8, error)
- func (p Parameter) Int8Array() ([]int8, error)
- func (p Parameter) Int8Default(defaultValue int8) int8
- func (p Parameter) IntArray() ([]int, error)
- func (p Parameter) IntDefault(defaultValue int) int
- func (p Parameter) String() (string, error)
- func (p Parameter) StringArray() ([]string, error)
- func (p Parameter) StringDefault(defaultValue string) string
- func (p Parameter) Time(layout string) (time.Time, error)
- func (p Parameter) TimeArray(layout string) ([]time.Time, error)
- func (p Parameter) TimeDefault(layout string, defaultValue time.Time) time.Time
- func (p Parameter) Uint() (uint, error)
- func (p Parameter) Uint16() (uint16, error)
- func (p Parameter) Uint16Array() ([]uint16, error)
- func (p Parameter) Uint16Default(defaultValue uint16) uint16
- func (p Parameter) Uint32() (uint32, error)
- func (p Parameter) Uint32Array() ([]uint32, error)
- func (p Parameter) Uint32Default(defaultValue uint32) uint32
- func (p Parameter) Uint64() (uint64, error)
- func (p Parameter) Uint64Array() ([]uint64, error)
- func (p Parameter) Uint64Default(defaultValue uint64) uint64
- func (p Parameter) Uint8() (uint8, error)
- func (p Parameter) Uint8Array() ([]uint8, error)
- func (p Parameter) Uint8Default(defaultValue uint8) uint8
- func (p Parameter) UintArray() ([]uint, error)
- func (p Parameter) UintDefault(defaultValue uint) uint
- type RouteOpt
- type RunConfig
- type Setter
- type SwaggerInfo
- type TestServer
- type WS
Examples ¶
Constants ¶
const MIME_HTML_FORM = "application/x-www-form-urlencoded"
nolint MIME_HTML_FORM is application/x-www-form-urlencoded header
Variables ¶
var CommonResponse = func(w http.ResponseWriter, routeID string, code int, message string, data interface{}) { if err := writeJSON(w, http.StatusOK, CommonResp{ Code: code, Message: message, Data: data, RouteID: routeID, }); err != nil { Warn("json encode", Log().Err(err)) } }
CommonResponse is a response func. just replace it if you'd like to custom response.
Functions ¶
func AddServices ¶
AddServices adds services with namespace.
func AuthFilter ¶
func AuthFilter(code int) restful.FilterFunction
AuthFilter checks if request contains JWT, and sets UserID in Attribute if exists,
func CheckError ¶
CheckError is a convenience method to check error is nil. If error is nil, it will return true, else it will log the error and return false
func CheckToken ¶ added in v0.1.0
CheckToken accept a jwt token and returns the uid in token.
func ContainsError ¶
ContainsError is a convenience method to check error is nil. If error is nil, it will return false, else it will log the error, make a CommonResp response and return true. if code is 0, it will use err.Error() as CommonResp.message.
func Fatal ¶
Fatal starts a new message with fatal level. The os.Exit(1) function is called by the Msg method.
func Filter ¶
func Filter(f func(ctx Ctx)) restful.FilterFunction
Filter transform a biu handler to a restful.FilterFunction
func Handle ¶
func Handle(f func(ctx Ctx)) restful.RouteFunction
Handle transform a biu handler to a restful.RouteFunction.
func LogFilter ¶
func LogFilter() restful.FilterFunction
LogFilter logs
{ remote_addr, method, uri, proto, status_code, content_length, }
for each request
func Logger ¶
Logger get the default logger of biu.
Example ¶
package main import ( "os" "github.com/rs/zerolog" "github.com/tuotoo/biu" ) func main() { biu.SetLoggerOutput(os.Stdout) biu.Debug("hello", biu.Log()) biu.SetLoggerLevel(zerolog.InfoLevel) biu.Debug("hello", biu.Log()) biu.Info("hello", biu.Log().Int("int", 1)) }
Output:
func NewSwaggerService ¶
func NewSwaggerService(info SwaggerInfo) *restful.WebService
NewSwaggerService creates a swagger webservice in /swagger
func Panic ¶
Panic starts a new message with panic level. The message is also sent to the panic function.
func ParseToken ¶ added in v0.1.0
ParseToken parse a token string.
func RefreshToken ¶ added in v0.1.0
RefreshToken accepts a valid token and returns a new token with new expire time.
func ResponseError ¶
func ResponseError(w http.ResponseWriter, routeID string, msg string, code int)
ResponseError is a convenience method to response an error code and message. It uses jsoniter for marshalling the value.
func ResponseJSON ¶
func ResponseJSON(w http.ResponseWriter, routeID string, v interface{})
ResponseJSON is a convenience method for writing a value wrap in CommonResp as JSON. It uses jsoniter for marshalling the value.
func SetLoggerLevel ¶
SetLoggerLevel sets the log level of logger.
func Sign ¶
Sign returns a signed jwt string.
Example ¶
biu.JWTTimeout(4 * time.Second). JWTSecret("hello world"). JWTRefreshTimeout(5 * time.Second) token, _ := biu.Sign("user") ctx := &biu.Ctx{ Request: &restful.Request{ Request: &http.Request{ Header: map[string][]string{ "Authorization": {token}, }, }, }, } u1, err := ctx.IsLogin() if err != nil { panic(err) } fmt.Println(u1) u2, err := biu.CheckToken(token) if err != nil { panic(err) } fmt.Println(u2) time.Sleep(time.Second * 2) newToken, err := biu.RefreshToken(token) if err != nil { panic(err) } _, err = biu.CheckToken(newToken) if err != nil { panic(err) } time.Sleep(time.Second * 3) // token is expired, newToken is still valid _, err = ctx.IsLogin() fmt.Println(err != nil) _, err = biu.CheckToken(token) fmt.Println(err != nil) _, err = biu.CheckToken(newToken) if err != nil { panic(err) } time.Sleep(time.Second) // cant refresh token if refresh timeout is reached _, err = biu.RefreshToken(newToken) fmt.Println(err != nil) ctx2 := &biu.Ctx{ Request: &restful.Request{ Request: &http.Request{ Header: map[string][]string{ "Authorization": {"wtf"}, }, }, }, } _, err = ctx2.IsLogin() fmt.Println(err != nil)
Output: user user true true true true
func WrapHandler ¶
func WrapHandler(f func(ctx Ctx)) http.HandlerFunc
WrapHandler wraps a biu handler to http.HandlerFunc
Types ¶
type CommonResp ¶
type CommonResp struct { Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data"` RouteID string `json:"route_id,omitempty"` }
CommonResp with code, message and data
type Container ¶
type Container struct{ *restful.Container }
Container of restful
func (*Container) AddServices ¶
AddServices adds services with namespace for container.
func (*Container) NewSwaggerService ¶
func (c *Container) NewSwaggerService(info SwaggerInfo) *restful.WebService
NewSwaggerService creates a swagger webservice in /swagger
func (*Container) NewTestServer ¶ added in v0.2.0
func (c *Container) NewTestServer() *TestServer
NewTestServer returns a Test Server.
type CtlInterface ¶
type CtlInterface interface {
WebService(WS)
}
CtlInterface is the interface of controllers
type Ctx ¶
type Ctx struct { *restful.Request *restful.Response *restful.FilterChain }
Ctx wrap *restful.Request and *restful.Response in one struct.
func (*Ctx) Bind ¶ added in v0.2.1
Bind checks the Content-Type to select a binding engine automatically, Depending the "Content-Type" header different bindings are used:
"application/json" --> JSON binding "application/xml" --> XML binding
otherwise --> returns an error. It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer. It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
func (*Ctx) BindQuery ¶ added in v0.2.1
BindQuery is a shortcut for ctx.BindWith(obj, binding.Query).
func (*Ctx) BindWith ¶ added in v0.2.1
BindWith binds the passed struct pointer using the specified binding engine. See the binding package.
func (*Ctx) BodyParameterValues ¶ added in v0.2.0
BodyParameterValues returns the array of parameter in a POST form body.
func (*Ctx) ContainsError ¶
ContainsError is a convenience method to check error is nil. If error is nil, it will return false, else it will log the error, make a CommonResp response and return true. if code is 0, it will use err.Error() as CommonResp.message.
func (*Ctx) IsLogin ¶
IsLogin gets JWT token in request by OAuth2Extractor, and parse it with CheckToken.
func (*Ctx) ResponseError ¶
ResponseError is a convenience method to response an error code and message. It uses jsoniter for marshalling the value.
func (*Ctx) ResponseJSON ¶
func (ctx *Ctx) ResponseJSON(v interface{})
ResponseJSON is a convenience method for writing a value wrap in CommonResp as JSON. It uses jsoniter for marshalling the value.
func (*Ctx) ResponseStdErrCode ¶
ResponseStdErrCode is a convenience method response a code with msg in Code Desc.
func (*Ctx) RouteSignature ¶ added in v0.2.0
RouteSignature returns the signature of current route. Example: /v1/user/login POST
type NS ¶
type NS struct { NameSpace string // url parent of controller Controller CtlInterface // controller implement CtlInterface Desc string // description of controller of namespace ExternalDesc string // external documentation of controller ExternalURL string // external url of ExternalDesc }
NS contains configuration of a namespace
type Parameter ¶ added in v0.2.1
type Parameter struct { Value []string // contains filtered or unexported fields }
Parameter wrap parameter value in a request.
func (Parameter) BoolDefault ¶ added in v0.2.1
BoolDefault converts a parameter value to bool with default value.
func (Parameter) Float32Array ¶ added in v0.2.1
Float32Array converts a parameter value to float32 array.
func (Parameter) Float32Default ¶ added in v0.2.1
Float32Default converts a parameter value to float32 with default value.
func (Parameter) Float64Array ¶ added in v0.2.1
Float64Array converts a parameter value to float64 array.
func (Parameter) Float64Default ¶ added in v0.2.1
Float64Default converts a parameter value to float64 with default value.
func (Parameter) Int16Array ¶ added in v0.2.1
Int16Array converts a parameter value to int16 array.
func (Parameter) Int16Default ¶ added in v0.2.1
Int16Default converts a parameter value to int16 with default value.
func (Parameter) Int32Array ¶ added in v0.2.1
Int32Array converts a parameter value to int32 array.
func (Parameter) Int32Default ¶ added in v0.2.1
Int32Default converts a parameter value to int32 with default value.
func (Parameter) Int64Array ¶ added in v0.2.1
Int64Array converts a parameter value to int64 array.
func (Parameter) Int64Default ¶ added in v0.2.1
Int64Default converts a parameter value to int64 with default value.
func (Parameter) Int8Default ¶ added in v0.2.1
Int8Default converts a parameter value to int8 with default value.
func (Parameter) IntDefault ¶ added in v0.2.1
IntDefault converts a parameter value to int with default value.
func (Parameter) StringArray ¶ added in v0.2.1
StringArray converts a parameter value to string array.
func (Parameter) StringDefault ¶ added in v0.2.1
StringDefault converts a parameter value to string with default value.
func (Parameter) Time ¶ added in v0.2.1
Time parse a parameter value to time.Time with given layout.
func (Parameter) TimeDefault ¶ added in v0.2.1
TimeDefault parse a parameter value to time.Time with given layout with default value.
func (Parameter) Uint16Array ¶ added in v0.2.1
Uint16Array converts a parameter value to uint16 array.
func (Parameter) Uint16Default ¶ added in v0.2.1
Uint16Default converts a parameter value to uint16 with default value.
func (Parameter) Uint32Array ¶ added in v0.2.1
Uint32Array converts a parameter value to uint32 array.
func (Parameter) Uint32Default ¶ added in v0.2.1
Uint32Default converts a parameter value to uint32 with default value.
func (Parameter) Uint64Array ¶ added in v0.2.1
Uint64Array converts a parameter value to uint64 array.
func (Parameter) Uint64Default ¶ added in v0.2.1
Uint64Default converts a parameter value to uint64 with default value.
func (Parameter) Uint8Array ¶ added in v0.2.1
Uint8Array converts a parameter value to uint8 array.
func (Parameter) Uint8Default ¶ added in v0.2.1
Uint8Default converts a parameter value to uint8 with default value.
func (Parameter) UintDefault ¶ added in v0.2.1
UintDefault converts a parameter value to uint with default value.
type RouteOpt ¶
type RouteOpt struct { ID string To func(ctx Ctx) Auth bool NeedPermissions []string Errors map[int]string }
RouteOpt contains some options of route.
type RunConfig ¶
type RunConfig struct { BeforeShutDown func() AfterShutDown func() }
RunConfig is the running config of container.
type Setter ¶ added in v0.1.0
type Setter struct{}
Setter is a setter for setting global options.
func JWTRefreshTimeout ¶ added in v0.1.0
JWTRefreshTimeout sets refresh timeout for JWT.
func JWTTimeout ¶ added in v0.1.0
JWTTimeout sets timeout for JWT.
func (Setter) JWTRefreshTimeout ¶ added in v0.1.0
JWTRefreshTimeout sets refresh timeout for JWT.
type SwaggerInfo ¶
type SwaggerInfo struct { Title string Description string TermsOfService string ContactName string ContactURL string ContactEmail string LicenseName string LicenseURL string Version string WebServicesURL string DisableCORS bool // route prefix of swagger service // swagger service will running under // http://<api>/<RoutePrefix>/swagger RoutePrefix string }
SwaggerInfo contains configuration of swagger documents.
type TestServer ¶ added in v0.2.0
TestServer wraps a httptest.Server
func NewTestServer ¶ added in v0.2.0
func NewTestServer() *TestServer
NewTestServer returns a Test Server.
func (*TestServer) WithT ¶ added in v0.2.0
func (s *TestServer) WithT(t *testing.T) *httpexpect.Expect
WithT accept testing.T and returns httpexpect.Expect