httpsvr

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2022 License: MIT Imports: 22 Imported by: 1

README

httpsvr

添加IDL约束条件, 约束接口的声明为func XXXX(ctx context.Context, req RequestDefine) (resp ResponseDefine, err error)

支持自定义的请求解析与相应编码函数

几点建议

  • 建议不要使用form, 这种无类型的数据提交方式适合弱类型语言与宽校验接口
  • 敏感或核心接口不要使用GET,原因可以自己查下

以上建议不采纳导致挖坑的后果需要自己填上。

How to Use

参考_example即可

FAQ

1、为什么要使用这个签名?

前面已经解释,这个共识也是和taowen等各方达成一致的结果。

2、我不想写IDL,如何支持?

自定义输入输出结构体,实现两个方法即可。用不了2分钟

3、为什么不支持标准的HTTP Handler的签名?

参考第一条

4、middleware不够灵活

middleware 用到的场景到底有多少? 这个组件的目标是简单高效可扩展,不是灵活随意搞,所以在各个方面都有限制实现的路径,但是整体支持功能扩展。

5、如果要加特性或者其他怎么搞?

很简单,ServerOption 新增配置即可,对应用方透明

Documentation

Overview

Package httpsvr ...

Package httpsvr ...

Package httpsvr ...

Package httpsvr ...

Package httpsvr ...

Package httpsvr ...

Package httpsvr ...

Package httpsvr ...

Index

Constants

This section is empty.

Variables

View Source
var Access = func(ctx context.Context, r *http.Request, w http.ResponseWriter, next HandlerFunc) HandlerFunc {
	return func(ctx context.Context, r *http.Request, w http.ResponseWriter) {
		next(ctx, r, w)
	}
}

Access 处理下一个回调方法

View Source
var Degrade = func(ctx context.Context, r *http.Request, w http.ResponseWriter, next HandlerFunc) HandlerFunc {
	return func(ctx context.Context, r *http.Request, w http.ResponseWriter) {
	}
}

Degrade 降级

View Source
var (
	// ErrEmptyBody body为空的错误消息
	ErrEmptyBody = errors.New("empty request body")
)
View Source
var Language = func(ctx context.Context, r *http.Request, w http.ResponseWriter, next HandlerFunc) HandlerFunc {
	return func(ctx context.Context, r *http.Request, w http.ResponseWriter) {
		r.ParseForm()
		lang := r.Form.Get(languageKey)
		if lang == "" {
			content := r.Header.Get(hintContentKey)
			v := make(map[string]interface{})
			if err := json.Unmarshal([]byte(content), &v); err != nil {
				logger.Infof(ctx, logger.DLTagUndefined, "_msg=hint_content not json,hintcontent=%s", content)
			}
			if lh, ok := v[languageKey]; ok {
				lang = fmt.Sprint(lh)
			}
		}
		if lang == "" {
			logger.Infof(ctx, logger.DLTagUndefined, "_msg=not found language")
			lang = localLanguage
		}

		ctx = ctxutil.SetLang(ctx, lang)
		next(ctx, r, w)
	}
}

Language ...

View Source
var Recovery = func(ctx context.Context, r *http.Request, w http.ResponseWriter, next HandlerFunc) HandlerFunc {
	return func(ctx context.Context, r *http.Request, w http.ResponseWriter) {
		defer func() {
			if err := recover(); err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte("Server is busy."))
				stack := make([]byte, 2048)
				stack = stack[:runtime.Stack(stack, false)]

				f := "PANIC: %s\n%s"
				logger.Errorf(ctx, logger.DLTagUndefined, f, err, stack)
			}
		}()

		if next != nil {
			next(ctx, r, w)
		}
	}
}

Recovery 捕获panic的通用处理方法

View Source
var RecoveryWithMetric = func(ctx context.Context, r *http.Request, w http.ResponseWriter, next HandlerFunc) HandlerFunc {
	return func(ctx context.Context, r *http.Request, w http.ResponseWriter) {
		defer func() {
			if err := recover(); err != nil {
				metrics.Add("panic", 1)
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte("Server is busy."))
				stack := make([]byte, 1024)
				stack = stack[:runtime.Stack(stack, false)]

				f := "PANIC: %s\n%s"
				logger.Errorf(ctx, logger.DLTagUndefined, f, err, stack)
			}
		}()

		if next != nil {
			next(ctx, r, w)
		}
	}
}

RecoveryWithMetric 捕获panic,记录metric

Functions

func GenExtraResponse

func GenExtraResponse(extData map[string]interface{}, code int, msg string) interface{}

GenExtraResponse 根据map产生响应

Types

type APIResponseHeader

type APIResponseHeader interface {
	GetCode() int
	GetMsg() string
}

APIResponseHeader api响应头格式

type Context

type Context struct {
	Params       httprouter.Params
	Req          *http.Request
	TraceID      string
	SpanID       string
	ParentSpanID string
	// contains filtered or unexported fields
}

Context 上下文结构,TraceID、SpanID、ResponseWriter、Request、Params等

func (*Context) FormValues

func (c *Context) FormValues() map[string]string

FormValues 解析参数并格式化为map

func (*Context) GetRequestBody

func (c *Context) GetRequestBody() ([]byte, error)

GetRequestBody 获取请求体

func (*Context) Write

func (c *Context) Write(data []byte, code int)

Write 写响应数据

type ControllerOption

type ControllerOption func(o *ctrlOption)

ControllerOption 定义ControllerOption类型

func AddResponseHeader

func AddResponseHeader(fn func() http.Header) ControllerOption

AddResponseHeader ...

func SetControllerMarshalFunc

func SetControllerMarshalFunc(fn func(v interface{}, err idl.APIErr) ([]byte, error)) ControllerOption

SetControllerMarshalFunc ...

func SetControllerUnmarshalFunc

func SetControllerUnmarshalFunc(fn func(r *http.Request, req interface{}) error) ControllerOption

SetControllerUnmarshalFunc 设置某个Controller的Unmarshal方法

func SetHandleTimeout

func SetHandleTimeout(to int64) ControllerOption

SetHandleTimeout ...

type HandlerFunc

type HandlerFunc func(ctx context.Context, r *http.Request, w http.ResponseWriter)

HandlerFunc 回调方法类型定义

type Middleware

type Middleware func(ctx context.Context, r *http.Request, w http.ResponseWriter, next HandlerFunc) HandlerFunc

Middleware 定义Middleware类型

type PHPResponseHeader

type PHPResponseHeader struct {
	Code interface{} `json:"errno"`
	Msg  string      `json:"errmsg"`
}

PHPResponseHeader php响应头格式

func (*PHPResponseHeader) GetCode

func (ph *PHPResponseHeader) GetCode() int

GetCode 获取PHPResponseHeader响应码

func (*PHPResponseHeader) GetMsg

func (ph *PHPResponseHeader) GetMsg() string

GetMsg 获取PHPResponseHeader响应消息

type Response

type Response struct {
	Code int         `json:"errno"`
	Msg  string      `json:"errmsg"`
	Data interface{} `json:"data"`
}

Response 响应结构体

func GenNotImplementResponse

func GenNotImplementResponse(name string) *Response

GenNotImplementResponse 产生404 响应

func GenResponse

func GenResponse(data interface{}, code int, msg string) *Response

GenResponse 根据参数产生响应

type Server

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

Server 定义Server结构体

func New

func New(addr string, opts ...ServerOption) *Server

New 创建默认Server

func (*Server) AddMiddleware

func (s *Server) AddMiddleware(md Middleware)

AddMiddleware 添加middleware

func (*Server) AddRoute

func (s *Server) AddRoute(method, path string, ctrl idl.IController, opts ...ControllerOption)

AddRoute 添加路由

func (*Server) HandleFunc

func (s *Server) HandleFunc(method, path string, hd func(w http.ResponseWriter, r *http.Request))

func (*Server) Serve

func (s *Server) Serve() error

Serve 监听普通连接

func (*Server) ServeHTTP

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

ServeHTTP server http

func (*Server) ServeTLS

func (s *Server) ServeTLS(certFile, keyFile string) error

ServeTLS 监听SSL连接

type ServerOption

type ServerOption func(o *option)

ServerOption 定义ServerOption类型

func EnableElasped

func EnableElasped(enable bool) ServerOption

EnableElasped enable elapsed

func EnableValidate

func EnableValidate(enable bool) ServerOption

EnableValidate enable validate

func SetHandleDefaultTimeout

func SetHandleDefaultTimeout(to int64) ServerOption

SetHandleDefaultTimeout ...

func SetLocalLanguage

func SetLocalLanguage(lang string) ServerOption

SetLocalLanguage ...

func SetServerMarshalFunc

func SetServerMarshalFunc(marshalFunc func(v interface{}, err idl.APIErr) ([]byte, error)) ServerOption

SetServerMarshalFunc ...

func SetServerReadTimeout

func SetServerReadTimeout(rt time.Duration) ServerOption

SetServerReadTimeout ...

func SetServerUnmarshalFunc

func SetServerUnmarshalFunc(fn func(*http.Request, interface{}) error) ServerOption

SetServerUnmarshalFunc ...

func SetServerWriteTimeout

func SetServerWriteTimeout(wt time.Duration) ServerOption

SetServerWriteTimeout ...

func WithDumpAccess

func WithDumpAccess(dump bool) ServerOption

WithDumpAccess dump access

func WithDumpResponse

func WithDumpResponse(dump bool) ServerOption

WithDumpResponse dump response

func WithLogger

func WithLogger(log logger.Logger) ServerOption

WithLogger log

type TraceHeader

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

TraceHeader header中的traceID、spanID和parentSpanID

func NewTraceHeader

func NewTraceHeader(r *http.Request) *TraceHeader

NewTraceHeader 创建TraceHeader

func (*TraceHeader) Encode

func (th *TraceHeader) Encode() map[string]string

Encode 将traceID和spanID格式化为map

func (*TraceHeader) GetParentSpanID

func (th *TraceHeader) GetParentSpanID() string

GetParentSpanID 从TraceHeader获取parentSpanID

func (*TraceHeader) GetSpanID

func (th *TraceHeader) GetSpanID() string

GetSpanID 从TraceHeader获取spanID

func (*TraceHeader) GetTraceID

func (th *TraceHeader) GetTraceID() string

GetTraceID 从TraceHeader获取traceID

Directories

Path Synopsis
idl

Jump to

Keyboard shortcuts

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