httptransport

package module
v1.22.0 Latest Latest
Warning

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

Go to latest
Published: May 30, 2023 License: MIT Imports: 31 Imported by: 7

README

HTTP Transport

GoDoc Widget codecov Go Report Card

Courier Transport for HTTP.

Documentation

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsRequestOut added in v1.18.1

func AsRequestOut(ctx context.Context) context.Context

func ContextWithHttpRequest

func ContextWithHttpRequest(ctx context.Context, req *http.Request) context.Context

func ContextWithOperationID added in v1.3.0

func ContextWithOperationID(ctx context.Context, operationID string) context.Context

func ContextWithOperatorFactory added in v1.17.0

func ContextWithOperatorFactory(ctx context.Context, om *courier.OperatorFactory) context.Context

func ContextWithServiceMeta

func ContextWithServiceMeta(ctx context.Context, meta ServiceMeta) context.Context

func EnableQueryInBodyForHttpGet added in v1.18.0

func EnableQueryInBodyForHttpGet(ctx context.Context) context.Context

func HttpRequestFromContext

func HttpRequestFromContext(ctx context.Context) *http.Request

func IsRequestOut added in v1.21.0

func IsRequestOut(ctx context.Context) bool

func OperationIDFromContext added in v1.3.0

func OperationIDFromContext(ctx context.Context) string

func OperatorFactoryFromContext added in v1.17.0

func OperatorFactoryFromContext(ctx context.Context) *courier.OperatorFactory

func ShouldQueryInBodyForHttpGet added in v1.18.0

func ShouldQueryInBodyForHttpGet(ctx context.Context) bool

Types

type BadRequestError added in v1.21.1

type BadRequestError interface {
	EnableErrTalk()
	SetMsg(msg string)
	AddErr(err error, nameOrIdx ...interface{})
}

type BasePathDescriber added in v1.16.0

type BasePathDescriber interface {
	BasePath() string
}

type HttpMiddleware

type HttpMiddleware func(http.Handler) http.Handler

func MiddlewareChain

func MiddlewareChain(mw ...HttpMiddleware) HttpMiddleware

type HttpRouteHandler

type HttpRouteHandler struct {
	*RequestTransformerMgr
	*HttpRouteMeta
	// contains filtered or unexported fields
}

func NewHttpRouteHandler

func NewHttpRouteHandler(serviceMeta *ServiceMeta, httpRoute *HttpRouteMeta, requestTransformerMgr *RequestTransformerMgr) *HttpRouteHandler

func (*HttpRouteHandler) ServeHTTP

func (handler *HttpRouteHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request)

type HttpRouteMeta

type HttpRouteMeta struct {
	Route                         *courier.Route
	OperatorFactoryWithRouteMetas []*OperatorFactoryWithRouteMeta
}
Example
package main

import (
	"fmt"
	"os"
	"sort"

	"github.com/fatih/color"
	"github.com/go-courier/httptransport"
	"github.com/go-courier/httptransport/testdata/server/cmd/app/routes"
)

func main() {
	os.Setenv("PROJECT_NAME", "service-example")
	os.Setenv("PROJECT_VERSION", "1.0.0")

	color.NoColor = true

	routeList := routes.RootRouter.Routes()

	sort.Slice(routeList, func(i, j int) bool {
		return httptransport.NewHttpRouteMeta(routeList[i]).Key() <
			httptransport.NewHttpRouteMeta(routeList[j]).Key()
	})

	for i := range routeList {
		httpRouteMeta := httptransport.NewHttpRouteMeta(routeList[i])
		fmt.Println(httpRouteMeta.String())
	}
}
Output:

GET /demo openapi.OpenAPI
GET /demo/binary/files routes.DownloadFile
GET /demo/binary/images routes.ShowImage
POS /demo/cookie routes.Cookie
POS /demo/forms/multipart routes.FormMultipartWithFile
POS /demo/forms/multipart-with-files routes.FormMultipartWithFiles
POS /demo/forms/urlencoded routes.FormURLEncoded
GET /demo/proxy routes.Proxy
GET /demo/redirect routes.Redirect
POS /demo/redirect routes.RedirectWhenError
POS /demo/restful routes.Create
HEA /demo/restful routes.HealthCheck
GET /demo/restful/{id} routes.DataProvider routes.GetByID
DEL /demo/restful/{id} routes.DataProvider routes.RemoveByID
PUT /demo/restful/{id} routes.DataProvider routes.UpdateByID
GET /demo/v2/proxy routes.ProxyV2

func NewHttpRouteMeta

func NewHttpRouteMeta(route *courier.Route) *HttpRouteMeta

func (*HttpRouteMeta) Key

func (route *HttpRouteMeta) Key() string

func (*HttpRouteMeta) Log added in v1.17.1

func (route *HttpRouteMeta) Log()

func (*HttpRouteMeta) Method

func (route *HttpRouteMeta) Method() string

func (*HttpRouteMeta) OperatorNames added in v1.17.1

func (route *HttpRouteMeta) OperatorNames() string

func (*HttpRouteMeta) Path

func (route *HttpRouteMeta) Path() string

func (*HttpRouteMeta) String

func (route *HttpRouteMeta) String() string

type HttpTransport

type HttpTransport struct {
	ServiceMeta

	Port int

	// for modifying http.Server
	ServerModifiers []ServerModifier

	// Middlewares
	// can use https://github.com/gorilla/handlers
	Middlewares []HttpMiddleware

	// validator mgr for parameter validating
	ValidatorMgr validator.ValidatorMgr
	// transformer mgr for parameter transforming
	TransformerMgr transformers.TransformerMgr

	CertFile string
	KeyFile  string
	// contains filtered or unexported fields
}

func NewHttpTransport

func NewHttpTransport(serverModifiers ...ServerModifier) *HttpTransport

func (*HttpTransport) Serve

func (t *HttpTransport) Serve(router *courier.Router) error

func (*HttpTransport) ServeContext added in v1.20.0

func (t *HttpTransport) ServeContext(ctx context.Context, router *courier.Router) error

func (*HttpTransport) ServeHTTP

func (t *HttpTransport) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*HttpTransport) SetDefaults

func (t *HttpTransport) SetDefaults()

type MetaOperator added in v1.16.0

type MetaOperator struct {
	courier.EmptyOperator
	// contains filtered or unexported fields
}

func BasePath added in v1.16.0

func BasePath(basePath string) *MetaOperator

func Group

func Group(path string) *MetaOperator
Example
package main

import (
	"fmt"

	"github.com/go-courier/httptransport"
)

func main() {
	g := httptransport.Group("/test")
	fmt.Println(g.Path())
}
Output:

/test

func (*MetaOperator) BasePath added in v1.16.0

func (g *MetaOperator) BasePath() string

func (*MetaOperator) Path added in v1.16.0

func (g *MetaOperator) Path() string

type MethodDescriber

type MethodDescriber interface {
	Method() string
}

type OperatorFactoryWithRouteMeta added in v1.17.0

type OperatorFactoryWithRouteMeta struct {
	*courier.OperatorFactory
	RouteMeta
}

func NewOperatorFactoryWithRouteMeta added in v1.17.0

func NewOperatorFactoryWithRouteMeta(op courier.Operator, last bool) *OperatorFactoryWithRouteMeta

type PathDescriber

type PathDescriber interface {
	Path() string
}

type PostValidator

type PostValidator interface {
	PostValidate(badRequest BadRequestError)
}

type RequestTransformer

type RequestTransformer struct {
	Type         reflect.Type
	InParameters map[string][]transformers.RequestParameter
}

func (*RequestTransformer) DecodeAndValidate added in v1.21.1

func (t *RequestTransformer) DecodeAndValidate(ctx context.Context, info httpx.RequestInfo, v interface{}) error
Example (RequestInfo_failedOfPost)
mgr := httptransport.NewRequestTransformerMgr(nil, nil)

rtForSomeRequest, err := mgr.NewRequestTransformer(context.Background(), reflect.TypeOf(&ReqWithPostValidate{}))
if err != nil {
	return
}

req, err := rtForSomeRequest.NewRequest(http.MethodPost, "/:id", &ReqWithPostValidate{})
if err != nil {
	return
}

e := rtForSomeRequest.DecodeAndValidate(context.Background(), httpx.NewRequestInfo(req), &ReqWithPostValidate{})
if e == nil {
	return
}

errFields := e.(*statuserror.StatusErr).ErrorFields

sort.Slice(errFields, func(i, j int) bool {
	return errFields[i].Field < errFields[j].Field
})

for _, ef := range errFields {
	fmt.Println(ef)
}
Output:

StartedAt in query - missing required field
StartedAt in query - ops

func (*RequestTransformer) DecodeFromRequestInfo

func (t *RequestTransformer) DecodeFromRequestInfo(ctx context.Context, info httpx.RequestInfo, v interface{}) error

func (*RequestTransformer) NewRequest

func (t *RequestTransformer) NewRequest(method string, rawUrl string, v interface{}) (*http.Request, error)

func (*RequestTransformer) NewRequestWithContext added in v1.18.0

func (t *RequestTransformer) NewRequestWithContext(ctx context.Context, method string, rawUrl string, v interface{}) (*http.Request, error)

type RequestTransformerMgr

type RequestTransformerMgr struct {
	validator.ValidatorMgr
	transformers.TransformerMgr
	// contains filtered or unexported fields
}

func NewRequestTransformerMgr

func NewRequestTransformerMgr(
	transformerMgr transformers.TransformerMgr,
	validatorMgr validator.ValidatorMgr,
) *RequestTransformerMgr
Example
mgr := httptransport.NewRequestTransformerMgr(nil, nil)

type PlainBody struct {
	A   string `json:"a" validate:"@string[2,]"`
	Int int    `json:"int,omitempty" default:"0" validate:"@int[0,]"`
}

type Req struct {
	Protocol  types.Protocol `name:"protocol,omitempty" in:"query" default:"HTTP"`
	QString   string         `name:"string,omitempty" in:"query" default:"s"`
	PlainBody PlainBody      `in:"body" mime:"plain" validate:"@struct<json>"`
}

req := &Req{}
req.PlainBody.A = "1"

rtForSomeRequest, err := mgr.NewRequestTransformer(context.Background(), reflect.TypeOf(req))
if err != nil {
	panic(err)
}

statusErr := rtForSomeRequest.InParameters["body"][0].Validator.Validate(req.PlainBody)

statusErr.(*errors.ErrorSet).Each(func(fieldErr *errors.FieldError) {
	fmt.Println(fieldErr.Path, strconv.Quote(fieldErr.Error.Error()))
})
Output:

a "string length should be larger than 2, but got invalid value 1"

func (*RequestTransformerMgr) NewRequest

func (mgr *RequestTransformerMgr) NewRequest(method string, rawUrl string, v interface{}) (*http.Request, error)

func (*RequestTransformerMgr) NewRequestTransformer

func (mgr *RequestTransformerMgr) NewRequestTransformer(ctx context.Context, typ reflect.Type) (*RequestTransformer, error)

func (*RequestTransformerMgr) NewRequestWithContext added in v1.18.0

func (mgr *RequestTransformerMgr) NewRequestWithContext(ctx context.Context, method string, rawUrl string, v interface{}) (*http.Request, error)

func (*RequestTransformerMgr) SetDefaults

func (mgr *RequestTransformerMgr) SetDefaults()

type ResponseWithError added in v1.20.1

type ResponseWithError interface {
	WriteError(err error)
}

type RouteMeta added in v1.17.0

type RouteMeta struct {
	ID         string
	Method     string
	Path       string
	BasePath   string
	Summary    string
	Deprecated bool
}

type ServerModifier

type ServerModifier func(server *http.Server) error

type ServiceMeta

type ServiceMeta struct {
	Name    string
	Version string
}

func ServerMetaFromContext

func ServerMetaFromContext(ctx context.Context) ServiceMeta

func (*ServiceMeta) SetDefaults

func (s *ServiceMeta) SetDefaults()

func (ServiceMeta) String

func (s ServiceMeta) String() string

type WithFromRequestInfo added in v1.21.1

type WithFromRequestInfo interface {
	FromRequestInfo(req *httpx.RequestInfo) error
}

Directories

Path Synopsis
generators
Each Validator have at least two process methods, one for 'Parsing' and one for 'Validating'.
Each Validator have at least two process methods, one for 'Parsing' and one for 'Validating'.

Jump to

Keyboard shortcuts

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