mvc

package
v0.0.0-...-5d3a41b Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2025 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Validator *validator.Validate

Validator use for verify the input params on struct level

Functions

func RegisterFieldValidator

func RegisterFieldValidator(tag string, valfunc validator.Func)

RegisterFieldValidator register validators on struct field level

func RegisterValidators

func RegisterValidators(valmap map[string]validator.Func)

RegisterValidators register struct field validators from given map

Types

type AuthHandlerFunc deprecated

type AuthHandlerFunc func(token string) (string, string)

Deprecated: Auth request token from http header and returen account secures.

var GAuthHandlerFunc AuthHandlerFunc

Deprecated: Global handler function to auth token from http header.

type NextFunc

type NextFunc func() (int, any)

NextFunc do action after input params validated.

type NextFunc2 deprecated

type NextFunc2 func(uuid string) (int, any)

Deprecated: Do action after input params validated, it decode token to get account uuid.

type NextFunc3 deprecated

type NextFunc3 func(uuid, pwd string) (int, any)

Deprecated: Do action after input params validated, it decode token to get account uuid and password.

type NextHander

type NextHander func(a *WAuths) (int, any)

NextHander do action after input params validated, it decode token to get account secures.

type RoleHandlerFunc deprecated

type RoleHandlerFunc func(sub, obj, act string) bool

Deprecated: Verify role access permission from account service.

var GRoleHandlerFunc RoleHandlerFunc

Deprecated: Global handler function to verify role from http header.

type ValidateHandlerFunc

type ValidateHandlerFunc func(token, router, method string) *WAuths

ValidateHandlerFunc auth request token from http header and returen account secures.

var ValidateHandler ValidateHandlerFunc

Global handler function to verify token and role from http header

type WAuthController deprecated

type WAuthController struct {
	WingController
}

Deprecated: This controller deprecated! use WRoleController instead it.

WAuthController the extend controller base on WingController to support auth account from http headers, the client caller must append two headers before post request if expect the controller method enable execute token authentication from header.

* Author : It must fixed keyword as WENGOLD-V1.2

* Token : Authenticate JWT token responsed by login success

`Optional headers` :

* Location : Optional value of client indicator, global location

* Authoration : The old version keyword for WENGOLD-V1.1

`USAGE` :

The validator register code of input params struct see WingController description, but the restful auth api of router method as follow usecase 1 and 2.

---

`controller.go`

// define custom controller using header auth function
type AccController struct {
	mvc.WAuthController
}

func init() {
	mvc.GAuthHandlerFunc = func(token string) (string, string) {
		// decode and verify token string, than return indecated
		// account uuid and password.
		return "account uuid", "account password"
	}
}

`USECASE 1. Auth account and Parse input params`

//	@Description Restful api bind with /login on POST method
//	@Param Author header string true "WENGOLD-V1.2"
//	@Param Token  header string true "Authentication token"
//	@Param data body types.Accout true "input param description"
//	@Success 200 {string} "response data description"
//	@router /login [post]
func (c *AccController) AccLogin() {
	ps := &types.Accout{}
	c.DoAfterValidated(ps, func(uuid string) (int, any) {
	// Or get authed account password as :
	// c.DoAfterAuthValidated(ps, func(uuid, pwd string) (int, any) {
		// do same business with input NO-EMPTY account uuid,
		// directe use c and ps param in this methed.
		// ...
		return http.StatusOK, "Done business"
	} , false /* not limit error message even code is 40x */)
}

`USECASE 2. Auth account on GET http method`

//	@Description Restful api bind with /detail on GET method
//	@Param Author header string true "WENGOLD-V1.2"
//	@Param Token  header string true "Authentication token"
//	@Success 200 {types.Detail} "response data description"
//	@router /detail [get]
func (c *AccController) AccDetail() {
	if uuid := c.AuthRequestHeader(); uuid != "" {
		// use c.BindValue("fieldkey", out) parse params from url
		c.ResponJSON(service.AccDetail(uuid))
	}
}

`USECASE 3. No-Auth and Use WingController`

//	@Description Restful api bind with /update on POST method
//	@Param data body types.UserInfo true "input param description"
//	@Success 200
//	@router /update [post]
func (c *AccController) AccUpdate() {
	ps := &types.UserInfo{}
	c.WingController.DoAfterValidated(ps, func() (int, any) {
		// directe use c and ps param in this methed.
		// ...
		return http.StatusOK, nil
	} , false /* not limit error message even code is 40x */)
}

`USECASE 4. No-Auth and Custom code`

//	@Description Restful api bind with /list on GET method
//	@Success 200 {object} []types.Account "response data description"
//	@router /list [get]
func (c *AccController) AccList() {
	// do same business without auth and input params
	c.ResponJSON(service.AccList())
}

func (*WAuthController) AuthRequestHeader deprecated

func (c *WAuthController) AuthRequestHeader(hidelog ...bool) string

Deprecated: Get authoration and token from http header, than verify it and return account secures.

@Return 401, 403 codes returned on error.

func (*WAuthController) DoAfterAuthUnmarshal deprecated

func (c *WAuthController) DoAfterAuthUnmarshal(ps any, nextFunc3 NextFunc3, fs ...bool)

Deprecated: Do bussiness action after success unmarshaled the given json data.

@Return 400, 401, 403, 404 codes returned on error.

func (*WAuthController) DoAfterAuthUnmarshalXml deprecated

func (c *WAuthController) DoAfterAuthUnmarshalXml(ps any, nextFunc3 NextFunc3, fs ...bool)

Deprecated: Do bussiness action after success unmarshaled the given xml data.

@Return 400, 401, 403, 404 codes returned on error.

func (*WAuthController) DoAfterAuthValidated deprecated

func (c *WAuthController) DoAfterAuthValidated(ps any, nextFunc3 NextFunc3, fs ...bool)

Deprecated: Do bussiness action after success validate the given json data.

@Return 400, 401, 403, 404 codes returned on error.

func (*WAuthController) DoAfterAuthValidatedXml deprecated

func (c *WAuthController) DoAfterAuthValidatedXml(ps any, nextFunc3 NextFunc3, fs ...bool)

Deprecated: Do bussiness action after success validate the given xml data.

@Return 400, 401, 403, 404 codes returned on error.

func (*WAuthController) DoAfterUnmarshal deprecated

func (c *WAuthController) DoAfterUnmarshal(ps any, nextFunc2 NextFunc2, fs ...bool)

Deprecated: Do bussiness action after success unmarshaled the given json data.

@Return 400, 401, 403, 404 codes returned on error.

func (*WAuthController) DoAfterUnmarshalXml deprecated

func (c *WAuthController) DoAfterUnmarshalXml(ps any, nextFunc2 NextFunc2, fs ...bool)

Deprecated: Do bussiness action after success unmarshaled the given xml data.

@Return 400, 401, 403, 404 codes returned on error.

func (*WAuthController) DoAfterValidated deprecated

func (c *WAuthController) DoAfterValidated(ps any, nextFunc2 NextFunc2, fs ...bool)

Deprecated: Do bussiness action after success validate the given json data.

@Return 400, 401, 403, 404 codes returned on error.

func (*WAuthController) DoAfterValidatedXml deprecated

func (c *WAuthController) DoAfterValidatedXml(ps any, nextFunc2 NextFunc2, fs ...bool)

Deprecated: Do bussiness action after success validate the given xml data.

@Return 400, 401, 403, 404 codes returned on error.

type WAuths

type WAuths struct {
	ID   int64  // Account id of int64,  set when using number id, default -1.
	UID  string // Account id of string, set when using string id, defalut empty.
	Pwd  string // Account password plaintext, maybe empty.
	Role string // Account role, maybe empty.
}

Account secure datas, set after pass validation.

type WRoleController

type WRoleController struct {
	WingController
}

WRoleController the extend controller base on WingController to support auth account from http headers, the client caller must append auth hander before post request if expect the controller method enable execute token authentication from header.

* Author : It must fixed keyword as WENGOLD-V2.0

* Token : Authenticate JWT token responsed by login success

`USAGE` :

The validator register code of input params struct see WingController description, but the restful auth api of router method as follow usecase 1 and 2.

---

`controller.go`

// define custom controller using header auth function
type AccController struct {
	mvc.WRoleController
}

func init() {
	mvc.ValidateHandler = func(token, router, method string) *mvc.WAuths {
		secures := &mvc.WAuths{}
		// decode and verify token string, than return indecated
		// account id, string uuid, password plaintext and role.
		return secures
	}
}

`USECASE 1. Auth account and Parse input params`

//	@Description Restful api bind with /login on POST method
//	@Param Author header string true "WENGOLD-V2.0"
//	@Param Token  header string true "Authentication token"
//	@Param data   body   types.Accout true "input param description"
//	@Success 200 {string} "response data description"
//	@router /login [post]
func (c *AccController) AccLogin() {
	ps := &types.Accout{}
	c.DoAfterValidated(ps, func(s *WAuths) (int, any) {
		// do api action with input NOT-NULL account secures,
		// directe use c and ps param in this methed.
		// ...
		return http.StatusOK, "Done business"
	} , false /* silent flag, true is not output success logs */)
}

`USECASE 2. Auth account on GET http method`

//	@Description Restful api bind with /detail on GET method
//	@Param Author header string true "WENGOLD-V2.0"
//	@Param Token  header string true "Authentication token"
//	@Success 200 {types.Detail} "response data description"
//	@router /detail [get]
func (c *AccController) AccDetail() {
	if s := c.AuthRequestHeader(); s != nil {
		// use c.BindValue("fieldkey", out) parse params from url
		c.ResponJSON(service.AccDetail(uuid))
	}
}

`USECASE 3. No-Auth and Use WingController`

//	@Description Restful api bind with /update on POST method
//	@Param data body types.UserInfo true "input param description"
//	@Success 200
//	@router /update [post]
func (c *AccController) AccUpdate() {
	ps := &types.UserInfo{}
	c.WingController.DoAfterValidated(ps, func() (int, any) {
		// directe use c and ps param in this methed.
		// ...
		return http.StatusOK, nil
	} , false /* not limit error message even code is 40x */)
}

`USECASE 4. No-Auth and Custom code`

//	@Description Restful api bind with /list on GET method
//	@Success 200 {object} []types.Account "response data description"
//	@router /list [get]
func (c *AccController) AccList() {
	// do same business without auth and input params
	c.ResponJSON(service.AccList())
}

func (*WRoleController) AuthRequestHeader

func (c *WRoleController) AuthRequestHeader(silent ...bool) *WAuths

Get authoration and token from http header, than verify it and return account secures.

This function just suport version of 'WENGOLD-V2.0' header without any input params.

@return 401: Invalid author header or permission denied.

func (*WRoleController) DoAfterUnmarshal

func (c *WRoleController) DoAfterUnmarshal(ps any, nextHander NextHander, opts ...bool)

Parse input params, then do api action after success unmarshaled.

This function only suport 'WENGOLD-V2.0' header with input params.

@return 401: Invalid author header or permission denied.
@Return 400: Failed parse input params.
@Return 404: Case exception in server.

func (*WRoleController) DoAfterValidated

func (c *WRoleController) DoAfterValidated(ps any, nextHander NextHander, opts ...bool)

Parse and validate input params, then do api action after success validated.

This function only suport 'WENGOLD-V2.0' header with input params.

@return 401: Invalid author header or permission denied.
@Return 400: Failed parse input params or validate error.
@Return 404: Case exception in server.

type WingController

type WingController struct {
	beego.Controller
}

WingController the base controller to support bee http functions.

`USAGE` :

Notice that you should register the field level validator for the input data's struct, then use it in struct describetion label as validate target.

---

`types.go`

// define restful api router input param struct
type struct Accout {
	Acc string `json:"acc" validate:"required,IsVaildUuid"`
	PWD string `json:"pwd" validate:"required_without"`
	Num int    `json:"num"`
}

// define custom validator on struct field level
func isVaildUuid(fl validator.FieldLevel) bool {
	m, _ := regexp.Compile("^[0-9a-zA-Z]*$")
	str := fl.Field().String()
	return m.MatchString(str)
}

func init() {
	// register router input params struct validators
	mvc.RegisterFieldValidator("IsVaildUuid", isVaildUuid)
}

---

`controller.go`

//	@Description Restful api bind with /login on POST method
//	@Param data body types.Accout true "input param description"
//	@Success 200 {string} "response data description"
//	@router /login [post]
func (c *AccController) AccLogin() {
	ps := &types.Accout{}
	c.DoAfterValidated(ps, func() (int, any) {
		// do same business function
		// directe use c and ps param in this methed.
		// ...
		return http.StatusOK, "Done business"
	} , false /* not limit error message even code is 40x */)
}

func (*WingController) BindValue

func (c *WingController) BindValue(key string, dest any) error

BindValue bind value with key from url, the dest container must pointer

func (*WingController) ClientFrom

func (c *WingController) ClientFrom() string

ClientFrom return client ip from who requested

func (*WingController) DoAfterUnmarshal

func (c *WingController) DoAfterUnmarshal(ps any, nextFunc NextFunc, fs ...bool)

DoAfterUnmarshal do bussiness action after success unmarshaled the given json data.

@Return 400, 404 codes returned on error.

func (*WingController) DoAfterUnmarshalXml

func (c *WingController) DoAfterUnmarshalXml(ps any, nextFunc NextFunc, fs ...bool)

DoAfterUnmarshalXml do bussiness action after success unmarshaled the given xml data.

@Return 400, 404 codes returned on error.

func (*WingController) DoAfterValidated

func (c *WingController) DoAfterValidated(ps any, nextFunc NextFunc, fs ...bool)

DoAfterValidated do bussiness action after success validate the given json data.

@Return 400, 404 codes returned on error.

func (*WingController) DoAfterValidatedXml

func (c *WingController) DoAfterValidatedXml(ps any, nextFunc NextFunc, fs ...bool)

DoAfterValidatedXml do bussiness action after success validate the given xml data.

@Return 400, 404 codes returned on error.

func (*WingController) E400Params

func (c *WingController) E400Params(err ...string)

E400Params response 400 invalid params error state to client

func (*WingController) E400Unmarshal

func (c *WingController) E400Unmarshal(err ...string)

E400rUnmarshal response 400 unmarshal params error state to client

func (*WingController) E400Validate

func (c *WingController) E400Validate(ps any, err ...string)

E400Validate response 400 invalid params error state to client, then print the params data and validate error

func (*WingController) E401Unauthed

func (c *WingController) E401Unauthed(err ...string)

E401Unauthed response 401 unauthenticated error state to client

func (*WingController) E403Denind

func (c *WingController) E403Denind(err ...string)

E403Denind response 403 permission denind error state to client

func (*WingController) E404Exception

func (c *WingController) E404Exception(err ...string)

E404Exception response 404 not found error state to client

func (*WingController) E405Disabled

func (c *WingController) E405Disabled(err ...string)

E405Disabled response 405 function disabled error state to client

func (*WingController) E406Input

func (c *WingController) E406Input(err ...string)

E406Input response 406 invalid inputs error state to client

func (*WingController) E409Duplicate

func (c *WingController) E409Duplicate(err ...string)

E409Duplicate response 409 duplicate error state to client

func (*WingController) E410Gone

func (c *WingController) E410Gone(err ...string)

E410Gone response 410 gone error state to client

func (*WingController) E426UpgradeRequired

func (c *WingController) E426UpgradeRequired(err ...string)

E426UpgradeRequired response 426 upgrade required error state to client

func (*WingController) ErrorState

func (c *WingController) ErrorState(state int, err ...string)

ErrorState response error state to client

func (*WingController) GetFloatDef

func (c *WingController) GetFloatDef(key string, def float64) float64

GetFloatDef get float value from url params with default value that enbale to use as error value to check get result.

func (*WingController) GetInt64Def

func (c *WingController) GetInt64Def(key string, def int64) int64

GetFloatDef get int64 value from url params with default value that enbale to use as error value to check get result.

func (*WingController) GetIntDef

func (c *WingController) GetIntDef(key string, def int) int

GetFloatDef get int value from url params with default value that enbale to use as error value to check get result.

func (*WingController) OutHeader

func (c *WingController) OutHeader(key, value string)

OutHeader set none-empty response header as key:value to frontend.

func (*WingController) OutRole

func (c *WingController) OutRole(role string, status int)

OutRole set role as response header to frontend.

func (*WingController) ResponData

func (c *WingController) ResponData(state int, data ...map[any]any)

ResponData sends JSON, JSONP, XML, YAML response datas to client, the data type depending on the value of the Accept header.

func (*WingController) ResponExErr

func (c *WingController) ResponExErr(errmsg invar.WExErr)

ResponExErr sends a extend error as response data on 202 status code

func (*WingController) ResponJSON

func (c *WingController) ResponJSON(state int, data ...any)

ResponJSON sends a json response to client on status check mode.

func (*WingController) ResponJSONP

func (c *WingController) ResponJSONP(state int, data ...any)

ResponJSONP sends a jsonp response to client on status check mode.

func (*WingController) ResponOK

func (c *WingController) ResponOK(hidelog ...bool)

ResponOK sends a empty success response to client

func (*WingController) ResponXML

func (c *WingController) ResponXML(state int, data ...any)

ResponXML sends xml response to client on status check mode.

func (*WingController) ResponYAML

func (c *WingController) ResponYAML(state int, data ...any)

ResponYAML sends yaml response to client on status check mode.

func (*WingController) SilentData

func (c *WingController) SilentData(state int, data ...map[any]any)

SilentData sends JSON, JSONNP, XML, YAML, response data to client without output ok log.

func (*WingController) SilentJSON

func (c *WingController) SilentJSON(state int, data ...any)

SilentJSON sends a json response to client without output ok log.

func (*WingController) SilentJSONP

func (c *WingController) SilentJSONP(state int, data ...any)

SilentJSONP sends a jsonp response to client without output ok log.

func (*WingController) SilentXML

func (c *WingController) SilentXML(state int, data ...any)

SilentXML sends xml response to client without output ok log.

func (*WingController) SilentYAML

func (c *WingController) SilentYAML(state int, data ...any)

SilentYAML sends yaml response to client without output ok log.

func (*WingController) UncheckJSON

func (c *WingController) UncheckJSON(state int, dataORerr ...any)

UncheckJSON sends a json response to client witchout status check.

func (*WingController) UncheckJSONP

func (c *WingController) UncheckJSONP(state int, dataORerr ...any)

UncheckJSONP sends a jsonp response to client witchout status check.

func (*WingController) UncheckXML

func (c *WingController) UncheckXML(state int, dataORerr ...any)

UncheckXML sends xml response to client witchout status check.

func (*WingController) UncheckYAML

func (c *WingController) UncheckYAML(state int, dataORerr ...any)

UncheckYAML sends yaml response to client witchout status check.

Directories

Path Synopsis
Package content provider for simple code to connect and access mysql or mssql database datas.
Package content provider for simple code to connect and access mysql or mssql database datas.
Package test utils as helper for simple code test scripts to test Rest4 APIs and database access methods.
Package test utils as helper for simple code test scripts to test Rest4 APIs and database access methods.

Jump to

Keyboard shortcuts

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