http

package
v1.7.2 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2025 License: MIT, Apache-2.0 Imports: 20 Imported by: 21

Documentation

Index

Constants

View Source
const (
	// ContentTypeHtml is the  string of text/html response header's content type value.
	ContentTypeHtml = "text/html"
	ContentTypeCss  = "text/css"
	// ContentTypeText header value for Text data.
	ContentTypeText = "text/plain"
	// ContentTypeTextXml header value for XML data.
	ContentTypeTextXml = "text/xml"
	// ContentTypeTextMarkdown custom key/content type, the real is the text/html.
	ContentTypeTextMarkdown = "text/markdown"
	// ContentTypeTextYaml header value for YAML plain text.
	ContentTypeTextYaml = "text/yaml"

	// ContentTypeMultipart header value for post multipart form data.
	ContentTypeMultipart = "multipart/form-data"

	// ContentTypeOctetStream header value for binary data.
	ContentTypeOctetStream = "application/octet-stream"
	// ContentTypeWebassembly header value for web assembly files.
	ContentTypeWebassembly = "application/wasm"
	// ContentTypeJson header value for JSON data.
	ContentTypeJson = "application/json"
	// ContentTypeJsonProblem header value for JSON API problem error.
	// Read more at: https://tools.ietf.org/html/rfc7807
	ContentTypeJsonProblem = "application/problem+json"
	// ContentTypeXmlProblem header value for XML API problem error.
	// Read more at: https://tools.ietf.org/html/rfc7807
	ContentTypeXmlProblem = "application/problem+xml"
	ContentTypeJavascript = "application/javascript"
	// ContentTypeXml obsolete header value for XML.
	ContentTypeXml = "application/xml"
	// ContentTypeYaml header value for YAML data.
	ContentTypeYaml = "application/yaml"
	// ContentTypeProtobuf header value for Protobuf messages data.
	ContentTypeProtobuf = "application/protobuf"
	// ContentTypeMsgPack header value for MsgPack data.
	ContentTypeMsgPack = "application/msgpack"
	// ContentTypeForm header value for post form data.
	ContentTypeForm = "application/x-www-form-urlencoded"

	// ContentTypeGrpc Content-Type header value for gRPC.
	ContentTypeGrpc      = "application/grpc"
	ContentTypeGrpcWeb   = "application/grpc-web"
	ContentTypePdf       = "application/pdf"
	ContentTypeJsonUtf8  = "application/json;charset=utf-8"
	ContentTypeFormParam = "application/x-www-form-urlencoded;param=value"

	ContentTypeImagePng              = "image/png"
	ContentTypeImageJpeg             = "image/jpeg"
	ContentTypeImageGif              = "image/gif"
	ContentTypeImageBmp              = "image/bmp"
	ContentTypeImageWebp             = "image/webp"
	ContentTypeImageAvif             = "image/avif"
	ContentTypeImageHeif             = "image/heif"
	ContentTypeImageSvg              = "image/svg+xml"
	ContentTypeImageTiff             = "image/tiff"
	ContentTypeImageXIcon            = "image/x-icon"
	ContentTypeImageVndMicrosoftIcon = "image/vnd.microsoft.icon"

	ContentTypeCharsetUtf8 = "charset=UTF-8"
)
View Source
const (
	FormDataFieldTmpl = `form-data; name="%s"`
	FormDataFileTmpl  = `form-data; name="%s"; filename="%s"`
	AttachmentTmpl    = `attachment; filename="%s"`
)
View Source
const (
	HeaderUserAgent                   = "User-Agent"
	HeaderXForwardedFor               = "X-Forwarded-For"
	HeaderXAccelBuffering             = "X-Accel-Buffering"
	HeaderAuth                        = "HeaderAuth"
	HeaderContentType                 = "Content-Type"
	HeaderTrace                       = "Tracing"
	HeaderTraceID                     = "Tracing-ID"
	HeaderTraceBin                    = "Tracing-Bin"
	HeaderAuthorization               = "Authorization"
	HeaderCookie                      = "Cookie"
	HeaderCookieValueToken            = "token"
	HeaderCookieValueDel              = "del"
	HeaderContentDisposition          = "Content-Disposition"
	HeaderContentEncoding             = "Content-Encoding"
	HeaderReferer                     = "Referer"
	HeaderAccept                      = "Accept"
	HeaderAcceptCharset               = "Accept-Charset"
	HeaderAcceptLanguage              = "Accept-Language"
	HeaderAcceptEncoding              = "Accept-Encoding"
	HeaderCacheControl                = "Cache-Control"
	HeaderSetCookie                   = "Set-Cookie"
	HeaderTrailer                     = "Trailer"
	HeaderTransferEncoding            = "Transfer-Encoding"
	HeaderTransferEncodingChunked     = "chunked"
	HeaderTE                          = "TE"
	HeaderLastModified                = "Last-Modified"
	HeaderContentLength               = "Content-Length"
	HeaderAccessControlRequestMethod  = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"
	HeaderOrigin                      = "Origin"
	HeaderConnection                  = "Connection"
	HeaderRange                       = "Range"
	HeaderHost                        = "Host"
	HeaderVia                         = "Via"
	HeaderDate                        = "Date"
	HeaderExpect                      = "Expect"
	HeaderFrom                        = "From"
	HeaderPragma                      = "Pragma"
	HeaderWarning                     = "Warning"
	HeaderContentRange                = "Content-Range"
	HeaderAcceptRanges                = "Accept-Ranges"
	HeaderXForwardedHost              = "X-Forwarded-Host"
)
View Source
const (
	HeaderGrpcTraceBin = "Grpc-Trace-Bin"
	HeaderGrpcInternal = "Grpc-Internal"
	HeaderGrpcStatus   = "Grpc-Status"
	HeaderGrpcMsg      = "Grpc-Msg"
	HeaderGrpcMessage  = "Grpc-Message"
	HeaderErrorCode    = "Error-Code"
)
View Source
const (
	HeaderDeviceInfo = "Device-Info"
	HeaderAppInfo    = "App-Info"
	HeaderLocation   = "Location"
	HeaderArea       = "Area"
	HeaderInternal   = "Internal"
)

Variables

View Source
var DefaultLogFormatter = func(param FormatterParams) string {
	var statusColor, methodColor, resetColor string
	if param.IsOutputColor() {
		statusColor = param.StatusCodeColor()
		methodColor = param.MethodColor()
		resetColor = param.ResetColor()
	}

	if param.Latency > time.Minute {

		param.Latency = param.Latency - param.Latency%time.Second
	}

	return fmt.Sprintf("%v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s",
		param.TimeStamp.Format("2006/01/02-15:04:05"),
		statusColor, param.StatusCode, resetColor,
		param.Latency,
		param.ClientIP,
		methodColor, param.Method, resetColor,
		param.Path,
		param.ErrorMessage,
	)
}

defaultLogFormatter is the default log format function Logger middleware uses.

Functions

func BasicAuth

func BasicAuth(username, password string) string

func CommonRespond added in v1.7.2

func CommonRespond(ctx context.Context, w CommonResponseWriter, res any) (int, error)

func CopyHttpHeader

func CopyHttpHeader(dst, src http.Header)

func DisableConsoleColor added in v1.4.0

func DisableConsoleColor()

DisableConsoleColor disables color output in the console.

func ForceConsoleColor added in v1.4.0

func ForceConsoleColor()

ForceConsoleColor force color output in the console.

func FormatContentDisposition

func FormatContentDisposition(filename string) string

func FormatContentRange

func FormatContentRange(start, end, total int64) string

func FormatRange

func FormatRange(start, end int64) string

func GetContentLength

func GetContentLength(header http.Header) int64

func GetToken

func GetToken(r *http.Request) string

func HeaderIntoHttpHeader

func HeaderIntoHttpHeader(header Header, httpHeader http.Header)

func HttpHeaderIntoHeader added in v1.3.9

func HttpHeaderIntoHeader(httpHeader http.Header, header Header)

func ParseContentDisposition

func ParseContentDisposition(header string) (string, error)

func ParseContentRange

func ParseContentRange(rangeHeader string) (start int64, end int64, total int64, err error)

func ParseDisposition

func ParseDisposition(disposition string) (mediatype string, params map[string]string, err error)

func ParseRange

func ParseRange(header string) (int64, int64, error)

func RespStatus added in v1.3.12

func RespStatus(ctx context.Context, w http.ResponseWriter, status int, data any) (int, error)

func Respond added in v1.3.9

func Respond(ctx context.Context, w http.ResponseWriter, data any) (int, error)

func RespondErrCodeMsg added in v1.7.2

func RespondErrCodeMsg(ctx context.Context, w http.ResponseWriter, code errorsx.ErrCode, msg string) (int, error)

func RespondError added in v1.7.2

func RespondError(ctx context.Context, w http.ResponseWriter, err error) (int, error)

func RespondStream added in v1.3.23

func RespondStream(ctx context.Context, w http.ResponseWriter, dataSource iter.Seq[WriterToCloser]) (int, error)

func RespondSuccess added in v1.7.2

func RespondSuccess(ctx context.Context, w http.ResponseWriter, res any) (int, error)

func SetBasicAuth

func SetBasicAuth(header http.Header, username, password string)

func UseMiddleware added in v1.3.10

func UseMiddleware(handler http.Handler, middlewares ...Middleware) http.Handler

Types

type Codec added in v1.6.6

type Codec interface {
	Marshaler
	Unmarshaler
}

type CommonRequestWriter added in v1.3.12

type CommonRequestWriter interface {
	io.Reader
}

type CommonResponder added in v1.3.12

type CommonResponder interface {
	CommonRespond(ctx context.Context, w CommonResponseWriter) (int, error)
}

type CommonResponseWriter

type CommonResponseWriter interface {
	Status(code int)
	Header() Header
	io.Writer
}

type Decoder added in v1.3.12

type Decoder interface {
	Decode(v any) error
}

Decoder decodes a byte sequence

type DecoderFunc added in v1.3.12

type DecoderFunc func(v any) error

DecoderFunc adapts an decoder function into Decoder.

func (DecoderFunc) Decode added in v1.3.12

func (f DecoderFunc) Decode(v any) error

Decode delegates invocations to the underlying function itself.

type Delimited added in v1.3.12

type Delimited interface {
	// Delimiter returns the record separator for the stream.
	Delimiter() []byte
}

Delimited defines the streaming delimiter.

type Encoder added in v1.3.12

type Encoder interface {
	Encode(v any) error
}

Encoder encodes gRPC payloads / fields into byte sequence.

type EncoderFunc added in v1.3.12

type EncoderFunc func(v any) error

EncoderFunc adapts an encoder function into Encoder

func (EncoderFunc) Encode added in v1.3.12

func (f EncoderFunc) Encode(v any) error

Encode delegates invocations to the underlying function itself.

type ErrResp added in v1.3.9

type ErrResp errorsx.ErrResp

func ErrRespFrom added in v1.3.9

func ErrRespFrom(err error) *ErrResp

func NewErrResp added in v1.3.12

func NewErrResp(code errorsx.ErrCode, msg string) *ErrResp

func (*ErrResp) CommonRespond added in v1.3.12

func (res *ErrResp) CommonRespond(ctx context.Context, w CommonResponseWriter) (int, error)

func (*ErrResp) ErrResp added in v1.6.13

func (res *ErrResp) ErrResp() *errorsx.ErrResp

func (*ErrResp) Error added in v1.6.13

func (res *ErrResp) Error() string

func (*ErrResp) Respond added in v1.3.9

func (res *ErrResp) Respond(ctx context.Context, w http.ResponseWriter) (int, error)

func (*ErrResp) ServeHTTP added in v1.3.12

func (res *ErrResp) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Formatter added in v1.4.0

type Formatter func(params FormatterParams) string

Formatter gives the signature of the formatter function passed to LoggerWithFormatter

type FormatterParams added in v1.4.0

type FormatterParams struct {
	Request *http.Request

	// TimeStamp shows the time after the server returns a response.
	TimeStamp time.Time
	// StatusCode is HTTP response code.
	StatusCode int
	// Latency is how much time the server cost to process a certain request.
	Latency time.Duration
	// ClientIP equals Context's ClientIP method.
	ClientIP string
	// Method is the HTTP method given to the request.
	Method string
	// Path is a path the client requests.
	Path string
	// ErrorMessage is set if error has occurred in processing the request.
	ErrorMessage string

	// BodySize is the size of the Response RespBody
	BodySize int
	// Keys are the keys set on the request's context.
	Keys map[any]any
	// contains filtered or unexported fields
}

FormatterParams is the structure any formatter will be handed when time to log comes

func (*FormatterParams) IsOutputColor added in v1.4.0

func (p *FormatterParams) IsOutputColor() bool

IsOutputColor indicates whether can colors be outputted to the log.

func (*FormatterParams) MethodColor added in v1.4.0

func (p *FormatterParams) MethodColor() string

MethodColor is the ANSI color for appropriately logging http method to a terminal.

func (*FormatterParams) ResetColor added in v1.4.0

func (p *FormatterParams) ResetColor() string

ResetColor resets all escape attributes.

func (*FormatterParams) StatusCodeColor added in v1.4.0

func (p *FormatterParams) StatusCodeColor() string

StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.

type Header interface {
	Add(key, value string)
	Set(key, value string)
	Get(key string) string
	Values(key string) []string
	Range(func(key, value string))
}

type HttpHeader

type HttpHeader http.Header

func (HttpHeader) Add

func (h HttpHeader) Add(k, v string)

func (HttpHeader) Get

func (h HttpHeader) Get(k string) string

func (HttpHeader) IntoHttpHeader

func (h HttpHeader) IntoHttpHeader(header http.Header)

func (HttpHeader) Range

func (h HttpHeader) Range(f func(key, value string))

func (HttpHeader) Set

func (h HttpHeader) Set(k, v string)

func (HttpHeader) ToHttpHeader added in v1.3.13

func (h HttpHeader) ToHttpHeader() http.Header

func (HttpHeader) Values

func (h HttpHeader) Values(k string) []string

type IntoHttpHeader

type IntoHttpHeader interface {
	IntoHttpHeader(header http.Header)
}

type Json added in v1.6.0

type Json struct {
}

func (*Json) ContentType added in v1.6.0

func (*Json) ContentType(_ any) string

func (*Json) Delimiter added in v1.7.0

func (j *Json) Delimiter() []byte

func (*Json) Marshal added in v1.6.0

func (j *Json) Marshal(v any) ([]byte, error)

func (*Json) Name added in v1.7.0

func (j *Json) Name() string

func (*Json) NewDecoder added in v1.7.0

func (j *Json) NewDecoder(r io.Reader) Decoder

NewDecoder returns a runtime.Decoder which reads JSON stream from "r".

func (*Json) NewEncoder added in v1.7.0

func (j *Json) NewEncoder(w io.Writer) Encoder

NewEncoder returns an Encoder which writes JSON stream into "w".

func (*Json) Unmarshal added in v1.6.0

func (j *Json) Unmarshal(data []byte, v interface{}) error

type LoggerConfig added in v1.4.0

type LoggerConfig struct {
	// Optional. defaultLogger value is gin.defaultLogFormatter
	Formatter Formatter

	Logger *log.Logger

	ErrHandle bool
	// SkipPaths is a url path array which logs are not written.
	// Optional.
	SkipPaths []string
}

LoggerConfig defines the config for Logger middleware.

type MapHeader

type MapHeader map[string]string

func (MapHeader) Add

func (h MapHeader) Add(k, v string)

func (MapHeader) Get

func (h MapHeader) Get(k string) string

func (MapHeader) IntoHttpHeader

func (h MapHeader) IntoHttpHeader(header http.Header)

func (MapHeader) Range

func (h MapHeader) Range(f func(key, value string))

func (MapHeader) Set

func (h MapHeader) Set(k, v string)

func (MapHeader) ToHttpHeader added in v1.3.13

func (h MapHeader) ToHttpHeader() http.Header

func (MapHeader) Values

func (h MapHeader) Values(k string) []string

type Marshaler added in v1.3.12

type Marshaler interface {
	// Marshal marshals "v" into byte sequence.
	Marshal(v any) ([]byte, error)
	// ContentType returns the Content-Type which this marshaler is responsible for.
	// The parameter describes the type which is being marshalled, which can sometimes
	// affect the content type returned.
	ContentType(v any) string
}

Marshaler defines a conversion between byte sequence and gRPC payloads / fields.

var (
	DefaultMarshaler Marshaler = &Json{}
)

type Middleware added in v1.3.10

type Middleware func(http.Handler) http.Handler

type MiddlewareContext added in v1.3.11

type MiddlewareContext struct {
	Request        *http.Request
	ResponseWriter http.ResponseWriter
	// contains filtered or unexported fields
}

func NewMiddlewareContext added in v1.3.11

func NewMiddlewareContext(handler http.Handler, handlers ...MiddlewareContextHandler) *MiddlewareContext

func (*MiddlewareContext) Next added in v1.3.11

func (m *MiddlewareContext) Next()

func (*MiddlewareContext) ServeHTTP added in v1.3.11

func (m *MiddlewareContext) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*MiddlewareContext) Use added in v1.3.11

type MiddlewareContextHandler added in v1.3.19

type MiddlewareContextHandler func(*MiddlewareContext)

type Record added in v1.7.2

type Record struct {
	ContentType string
	Body        *bytes.Buffer
	Raw         []byte
	Value       any
}

type Recorder added in v1.7.2

type Recorder struct {
	Code    int
	Request Record
	Reponse Record
	// contains filtered or unexported fields
}

Recorder is an implementation of http.ResponseWriter that records its mutations for later inspection in tests.

func NewRecorder

func NewRecorder(w http.ResponseWriter, r *http.Request) *Recorder

NewRecorder returns an initialized Recorder.

func (*Recorder) Close added in v1.7.2

func (rw *Recorder) Close() error

func (*Recorder) Flush added in v1.7.2

func (rw *Recorder) Flush()

Flush implements http.Flusher. To test whether Flush was called, see rw.Flushed.

func (*Recorder) Header added in v1.7.2

func (rw *Recorder) Header() http.Header

func (*Recorder) Read added in v1.7.2

func (rw *Recorder) Read(b []byte) (int, error)

func (*Recorder) RecordRequest added in v1.7.2

func (rw *Recorder) RecordRequest(contentType string, raw []byte, v any)

func (*Recorder) RecordResponse added in v1.7.2

func (rw *Recorder) RecordResponse(contentType string, raw []byte, v any)

func (*Recorder) Reset added in v1.7.2

func (rw *Recorder) Reset()

func (*Recorder) Result added in v1.7.2

func (rw *Recorder) Result() *http.Response

func (*Recorder) Write added in v1.7.2

func (rw *Recorder) Write(buf []byte) (int, error)

func (*Recorder) WriteHeader added in v1.7.2

func (rw *Recorder) WriteHeader(code int)

WriteHeader implements http.ResponseWriter.

type RequestRecorder added in v1.7.2

type RequestRecorder interface {
	RecordRequest(contentType string, raw []byte, v any)
}

type RespAnyData

type RespAnyData = RespData[any]

func NewRespData

func NewRespData(code errorsx.ErrCode, msg string, data any) *RespAnyData

type RespData

type RespData[T any] struct {
	Code errorsx.ErrCode `json:"code"`
	Msg  string          `json:"msg,omitempty"`
	//验证码
	Data T `json:"data,omitempty"`
}

RespData 主要用来接收返回,发送请使用ResAnyData

func (*RespData[T]) Respond added in v1.3.9

func (res *RespData[T]) Respond(ctx context.Context, w http.ResponseWriter) (int, error)

type RespondStreamer added in v1.3.23

type RespondStreamer interface {
	RespondStream(ctx context.Context, seq iter.Seq[WriterToCloser]) (int, error)
}

type Responder added in v1.3.12

type Responder interface {
	Respond(ctx context.Context, w http.ResponseWriter) (int, error)
}

type Response

type Response struct {
	Status  int            `json:"status,omitempty"`
	Headers http.Header    `json:"header,omitempty"`
	Body    WriterToCloser `json:"body,omitempty"`
}

func (*Response) CommonRespond added in v1.3.9

func (res *Response) CommonRespond(ctx context.Context, w CommonResponseWriter) (int, error)

func (*Response) Respond added in v1.3.9

func (res *Response) Respond(ctx context.Context, w http.ResponseWriter) (int, error)

type ResponseBody added in v1.3.23

type ResponseBody interface {
	ResponseBody() []byte
}

type ResponseRecorder

type ResponseRecorder interface {
	RecordResponse(contentType string, raw []byte, v any)
}

type ResponseStream added in v1.3.9

type ResponseStream struct {
	Status  int                      `json:"status,omitempty"`
	Headers http.Header              `json:"header,omitempty"`
	Body    iter.Seq[WriterToCloser] `json:"body,omitempty"`
}

func (*ResponseStream) CommonRespond added in v1.3.9

func (res *ResponseStream) CommonRespond(ctx context.Context, w CommonResponseWriter) (int, error)

func (*ResponseStream) Respond added in v1.3.9

func (res *ResponseStream) Respond(ctx context.Context, w http.ResponseWriter) (int, error)

func (*ResponseStream) ServeHTTP added in v1.3.12

func (res *ResponseStream) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ResponseWriterWrapper added in v1.3.12

type ResponseWriterWrapper struct {
	http.ResponseWriter
}

func (ResponseWriterWrapper) Header added in v1.3.12

func (w ResponseWriterWrapper) Header() Header

func (ResponseWriterWrapper) RespondStream added in v1.3.23

func (w ResponseWriterWrapper) RespondStream(ctx context.Context, seq iter.Seq[WriterToCloser]) (int, error)

func (ResponseWriterWrapper) Status added in v1.3.12

func (w ResponseWriterWrapper) Status(code int)

func (ResponseWriterWrapper) Write added in v1.3.12

func (w ResponseWriterWrapper) Write(p []byte) (int, error)

type SliceHeader

type SliceHeader []string

func NewHeader

func NewHeader() *SliceHeader

func (*SliceHeader) Add

func (h *SliceHeader) Add(k, v string)

func (SliceHeader) Clone

func (h SliceHeader) Clone() SliceHeader

func (*SliceHeader) Get

func (h *SliceHeader) Get(k string) string

func (SliceHeader) IntoHttpHeader

func (h SliceHeader) IntoHttpHeader(header http.Header)

func (*SliceHeader) Range

func (h *SliceHeader) Range(f func(key, value string))

func (*SliceHeader) Set

func (h *SliceHeader) Set(k, v string)

func (SliceHeader) ToHttpHeader added in v1.3.13

func (h SliceHeader) ToHttpHeader() http.Header

func (*SliceHeader) Values

func (h *SliceHeader) Values(k string) []string

type StatusCode added in v1.6.6

type StatusCode interface {
	StatusCode(v any) int
}

type StreamContentType added in v1.3.12

type StreamContentType interface {
	// StreamContentType returns the content type for a stream. This shares the
	// same behaviour as for `Marshaler.ContentType`, but is called, if present,
	// in the case of a streamed response.
	StreamContentType(v any) string
}

StreamContentType defines the streaming content type.

type Unmarshaler added in v1.7.0

type Unmarshaler interface {
	Unmarshal(data []byte, v any) error
}

type Unwrapper added in v1.7.2

type Unwrapper interface {
	Unwrap() http.ResponseWriter
}

type WriterToCloser

type WriterToCloser interface {
	io.WriterTo
	io.Closer
}

type XXXResponseBody added in v1.3.23

type XXXResponseBody interface {
	XXX_ResponseBody() any
}

Jump to

Keyboard shortcuts

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