restful

package
v0.0.0-...-e59f0fa Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2021 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	API_VERSION            = "a1"
	API_PATH               = "/" + API_VERSION
	TIMESTAMP_QUERY_PARAM  = "time"
	LANGUAGE_QUERY_PARAM   = "lang"
	BODY_INONEBOX_PARAM    = "onebox"
	IGNORE_HTTP_CODE_PARAM = "ihc"
	SING_NONCE_PARAM       = "sign_nonce" // 签名随机值
)
View Source
const (
	INTERNAL_ERR             = 10401 // 服务器内部错误
	HEADER_MISSING_ERR       = 10402 //缺少头域
	TOKEN_ISEMPTY_ERR        = 10403 // token为空
	DECODE_TOKEN_FAIL        = 10404 // token解码失败
	PARSE_TOKEN_ERR          = 10405 // token解析失败
	DECODE_CLAIM_FAIL        = 10406 // token claim解码失败
	PARSE_CLAIM_FAIL         = 10407 // token claim解析失败
	INVALID_ERR_FORMAT_ERR   = 10408 // 无效的错误格式
	INVALID_PATH_ARG_ERR     = 10409 // 无效的路径参数
	MAINTENANCE_ERR          = 10410 // 服务维护中
	INVALID_GRAPHQL_BODY_ERR = 10411 // 无效的graphql请求体
)
View Source
const (
	Header_x_forwarded_for   = "x-forwarded-for"
	Header_x_forwarded_host  = "x-forwarded-host"
	Header_x_auth_token      = "x-auth-token"
	Header_x_sub_token       = "x-sub-token"
	Header_accept_language   = "accept-language"
	Header_app_id            = "paasport-app-id"
	Header_sub_app_id        = "paasport-sub-app-id"
	Header_device_id         = "paasport-device-id"
	Header_sub_device_id     = "paasport-sub-device-id"
	Header_device_name       = "paasport-device-name"
	Header_sub_device_name   = "paasport-sub-device-name"
	Header_region            = "paasport-region"
	Header_user_agent        = "user-agent"
	Header_client_user_agent = "client-user-agent"
	Header_auth              = "authorization"
	Header_trace             = "paasport-trace-id"
	Header_account_id        = "paasport-account-id"
	Header_terminal_type     = "paasport-terminal-type"
	Header_tenant_name       = "paasport-tenant-name"
	Header_sub_tenant_name   = "paasport-sub-tenant-name"
	Header_project_name      = "paasport-project-name"
	Header_x_b3              = "x-b3"
	Header_x_envoy           = "x-envoy"
	Header_x_request         = "x-request"
	Header_x_b3_trace_id     = "X-B3-Traceid"
	Header_referer           = "referer"
	Header_content_type      = "content-type"
	Header_method            = "paasport-request-method"
)
View Source
const (
	//Name is a variable of type string which indicates the protocol being used
	Name              = "rest"
	DefaultMetricPath = "metrics"
	MimeFile          = "application/octet-stream"
	MimeMult          = "multipart/form-data"
)

constants for metric path and name

View Source
const (
	Path  = "path"
	Query = "query"
)

const for doc

Variables

可通过的头域列表

需要签名的头域列表

Functions

func HTTPRequest2Invocation

func HTTPRequest2Invocation(req *restful.Request, schema, operation string) (*invocation.Invocation, error)

HTTPRequest2Invocation convert http request to uniform invocation data format

func HTTPStatusFromCode

func HTTPStatusFromCode(b *Context, code codes.Code) int

HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto 如果query参数中携带ihc参数且不为空则忽略http状态码

func IncommingHeader

func IncommingHeader(ctx *Context) map[string]string

func IncommingHeaderMatcher

func IncommingHeaderMatcher(h string) bool

func Invocation2HTTPRequest

func Invocation2HTTPRequest(inv *invocation.Invocation, req *restful.Request)

Invocation2HTTPRequest convert invocation back to http request, set down all meta data

func Md5

func Md5(data string) string

func NewRestfulServer

func NewRestfulServer(opts server.Options) server.ProtocolServer

NewRestfulServer 新的restful服务初始化

func ParseError

func ParseError(err error) (codes.Code, int, error)

func Response

func Response(b *Context, resp interface{}, err error)

如果query参数中携带onebox参数且不为空则返回消息体和错误消息体一并返回

func WrapHandlerChain

func WrapHandlerChain(route Route, schemaType reflect.Type, schemaValue reflect.Value, schemaName string,
	opts server.Options) (restful.RouteFunction, error)

WrapHandlerChain wrap business handler with handler chain

Types

type Context

type Context struct {
	Ctx  context.Context
	Req  *restful.Request
	Resp *restful.Response
	// 将request body暂存在这,后续二次读取
	ReqBody []byte
}

Context is a struct which has both request and response objects

func NewBaseServer

func NewBaseServer(ctx context.Context) *Context

NewBaseServer is a function which return context

func (*Context) AddHeader

func (bs *Context) AddHeader(header string, value string)

AddHeader is a function used to add header to a response

func (*Context) Read

func (bs *Context) Read(schema interface{}) (err error)

Read 合并ReadQueryEntity 和ReadEntity

func (*Context) ReadBodyParameter

func (bs *Context) ReadBodyParameter(name string) (string, error)

ReadBodyParameter used to read body parameter of a request

func (*Context) ReadEntity

func (bs *Context) ReadEntity(schema interface{}) (err error)

ReadEntity is request reader

func (*Context) ReadHeader

func (bs *Context) ReadHeader(name string) string

ReadHeader is used to read header of request

func (*Context) ReadPathParameter

func (bs *Context) ReadPathParameter(name string) string

ReadPathParameter is used to read path parameter of a request

func (*Context) ReadPathParameters

func (bs *Context) ReadPathParameters() map[string]string

ReadPathParameters used to read multiple path parameters of a request

func (*Context) ReadQueryEntity

func (bs *Context) ReadQueryEntity(schema interface{}) (err error)

ReadQueryEntity is used to read query parameters into a specified struct. The struct tag should be `form` like:

type QueryRequest struct {
    Name string `form:"name"`
    Password string `form:"password"`
}

func (*Context) ReadQueryParameter

func (bs *Context) ReadQueryParameter(name string) string

ReadQueryParameter is used to read query parameter of a request

func (*Context) ReadRequest

func (bs *Context) ReadRequest() *http.Request

ReadRequest return a native net/http request

func (*Context) ReadResponseWriter

func (bs *Context) ReadResponseWriter() http.ResponseWriter

ReadResponseWriter return a native net/http ResponseWriter

func (*Context) ReadRestfulRequest

func (bs *Context) ReadRestfulRequest() *restful.Request

ReadRestfulRequest return a native go-restful request

func (*Context) ReadRestfulResponse

func (bs *Context) ReadRestfulResponse() *restful.Response

ReadRestfulResponse return a native go-restful Response

func (*Context) Write

func (bs *Context) Write(body []byte)

write is the response writer.

func (*Context) WriteError

func (bs *Context) WriteError(httpStatus int, err error) error

WriteError is a function used to write error into a response

func (*Context) WriteHeader

func (bs *Context) WriteHeader(httpStatus int)

WriteHeader is the response head writer

func (*Context) WriteHeaderAndJSON

func (bs *Context) WriteHeaderAndJSON(status int, value interface{}, contentType string) error

WriteHeaderAndJSON used to write head and JSON file in to response

func (*Context) WriteJSON

func (bs *Context) WriteJSON(value interface{}, contentType string) error

WriteJSON used to write a JSON file into response

type Parameters

type Parameters struct {
	Name      string //parameter name
	DataType  string // string, int etc
	ParamType int    //restful.QueryParameterKind or restful.PathParameterKind
	Desc      string
}

Parameters describe parameters in url path or query params

type RespBody

type RespBody struct {
	ErrCode       int         `json:"errCode"`        // 错误码
	Message       string      `json:"errMessage"`     // 错误信息
	Status        int         `json:"status"`         // http状态码
	Data          interface{} `json:"data,omitempty"` // 返回数据
	RequestId     string      `json:"request_id"`     // 请求ID
	RequestMethod string      `json:"request_method"` // 请求方法
	Success       bool        `json:"success"`
}

type RestfulServer

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

RestfulServer restful实现

func (*RestfulServer) AddRoute

func (r *RestfulServer) AddRoute(schema interface{}, route Route) error

AddRoute 添加路由

func (*RestfulServer) CreateLocalSchema

func (r *RestfulServer) CreateLocalSchema(config server.Options) error

CreateLocalSchema register to swagger ui,Whether to create a schema, you need to refer to the configuration.

func (*RestfulServer) DelRoute

func (r *RestfulServer) DelRoute(version, path, method string) error

DelRoute 删除路由 @version 路由版本 @path 路由路径 @method 路由方式

func (*RestfulServer) GetRoute

func (r *RestfulServer) GetRoute(version, path, method string) (Route, error)

GetRoute 获取路由 @version 路由版本 @path 路由路径 @method 路由方式

func (*RestfulServer) GetWebService

func (r *RestfulServer) GetWebService() []*restful.WebService

GetWebService 获取webservice

func (*RestfulServer) Register

func (r *RestfulServer) Register(schema interface{}, options ...server.RegisterOption) (string, error)

Register registe restfule server into go-chassis

func (*RestfulServer) Start

func (r *RestfulServer) Start() error

Start start restful server

func (*RestfulServer) Stop

func (r *RestfulServer) Stop() error

Stop stop restful server

func (*RestfulServer) String

func (r *RestfulServer) String() string

String get server name

type Returns

type Returns struct {
	Code    int // http response code
	Message string
	Model   interface{} // response body structure
}

Returns describe response doc

type Route

type Route struct {
	Method           string            //Method is one of the following: GET,PUT,POST,DELETE. required
	Path             string            //Path contains a path pattern. required
	ResourceFuncName string            //the func this API calls. required
	FuncDesc         string            //tells what this route is all about. Optional.
	Parameters       []*Parameters     //Parameters is a slice of request parameters for a single endpoint Optional.
	Returns          []*Returns        //what kind of response this API returns. Optional.
	Read             interface{}       //Read tells what resource type will be read from the request payload. Optional.
	Consumes         []string          //Consumes specifies that this WebService can consume one or more MIME types.
	Produces         []string          //Produces specifies that this WebService can produce one or more MIME types.
	Version          string            // route version
	Metadata         map[string]string // 自定义参数
}

Route describe http route path and swagger specifications for API

func GetRouteSpecs

func GetRouteSpecs(schema interface{}) ([]Route, error)

GetRouteSpecs is to return a rest API specification of a go struct

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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