http

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2025 License: MIT, Apache-2.0 Imports: 14 Imported by: 21

Documentation

Index

Constants

View Source
const (
	// ContentTypeJavascript header value for JSONP & Javascript data.
	ContentTypeJavascript = "text/javascript"
	// 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"
	// ContentTypeXml header value for XML data.
	ContentTypeXml = "text/xml"
	// ContentTypeMarkdown custom key/content type, the real is the text/html.
	ContentTypeMarkdown = "text/markdown"
	// ContentTypeYamlText header value for YAML plain text.
	ContentTypeYamlText = "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"
	ContentTypeJavascriptUnreadable = "application/javascript"
	// ContentTypeXmlUnreadable obsolete header value for XML.
	ContentTypeXmlUnreadable = "application/xml"
	// ContentTypeYaml header value for YAML data.
	ContentTypeYaml = "application/x-yaml"
	// ContentTypeProtobuf header value for Protobuf messages data.
	ContentTypeProtobuf = "application/x-protobuf"
	// ContentTypeMsgPack header value for MsgPack data.
	ContentTypeMsgPack = "application/msgpack"
	// ContentTypeMsgPack2 alternative header value for MsgPack data.
	ContentTypeMsgPack2 = "application/x-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"
	HeaderAcceptLanguage              = "Accept-Language"
	HeaderAcceptEncoding              = "Accept-Encoding"
	HeaderCacheControl                = "Cache-Control"
	HeaderSetCookie                   = "Set-Cookie"
	HeaderTrailer                     = "Trailer"
	HeaderTransferEncoding            = "Transfer-Encoding"
	HeaderTransferEncodingChunked     = "chunked"
	HeaderInternal                    = "Internal"
	HeaderTE                          = "TE"
	HeaderLastModified                = "Last-Modified"
	HeaderContentLength               = "Content-Length"
	HeaderAccessControlRequestMethod  = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"
	HeaderOrigin                      = "Origin"
	HeaderConnection                  = "Connection"
	HeaderRange                       = "Range"
	HeaderContentRange                = "Content-Range"
	HeaderAcceptRanges                = "Accept-Ranges"
)
View Source
const (
	HeaderGrpcTraceBin = "grpc-trace-bin"
	HeaderGrpcInternal = "grpc-internal"
)
View Source
const (
	HeaderDeviceInfo = "Device-AuthInfo"
	HeaderLocation   = "Location"
	HeaderArea       = "Area"
)
View Source
const DefaultRemoteAddr = "1.2.3.4"

DefaultRemoteAddr is the default remote address to return in RemoteAddr if an explicit DefaultRemoteAddr isn't set on ResponseRecorder.

Variables

View Source
var ResponseOk = json.RawMessage(`{"code":0}`)
View Source
var ResponseSysErr = json.RawMessage(`{"code":-1,"msg":"system error"}`)

Functions

func BasicAuth

func BasicAuth(username, password string) string

func CopyHttpHeader

func CopyHttpHeader(dst, src http.Header)

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 NewNoCloseRequest

func NewNoCloseRequest(req *http.Request, s []byte)

func NewNoCloseStrRequest

func NewNoCloseStrRequest(req *http.Request, s string)

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 RespErrCodeMsg

func RespErrCodeMsg(w http.ResponseWriter, code errors.ErrCode, msg string)

func RespErrRep

func RespErrRep(w http.ResponseWriter, rep *errors.ErrRep) (int, error)

func RespErrRepStatus

func RespErrRepStatus(w http.ResponseWriter, rep *errors.ErrRep, statusCode int) (int, error)

func RespError

func RespError(w http.ResponseWriter, err error) (int, error)

func RespStreamWrite

func RespStreamWrite(w http.ResponseWriter, dataSource iter.Seq[[]byte])

func RespSuccess

func RespSuccess[T any](w http.ResponseWriter, msg string, data T) (int, error)

func RespSuccessData

func RespSuccessData(w http.ResponseWriter, data any) (int, error)

func RespSuccessMsg

func RespSuccessMsg(w http.ResponseWriter, msg string) (int, error)

func Response

func Response[T any](w http.ResponseWriter, code errors.ErrCode, msg string, data T) (int, error)

func ResponseStatus

func ResponseStatus[T any](w http.ResponseWriter, code errors.ErrCode, msg string, data T, statusCode int) (int, error)

func SetBasicAuth

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

Types

type Body

type Body map[string]any

type CommonResponseWriter

type CommonResponseWriter struct {
	http.ResponseWriter
}

func (CommonResponseWriter) Header

func (w CommonResponseWriter) Header() Header

func (CommonResponseWriter) Status

func (w CommonResponseWriter) Status(code int)

func (CommonResponseWriter) Write

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

type ErrRep

type ErrRep errors.ErrRep

func ErrRepFrom

func ErrRepFrom(err error) *ErrRep

func NewErrorRespData

func NewErrorRespData(code errors.ErrCode, msg string) *ErrRep

func (*ErrRep) Response

func (res *ErrRep) Response(w http.ResponseWriter) (int, error)

func (*ErrRep) ResponseStatus

func (res *ErrRep) ResponseStatus(w http.ResponseWriter, statusCode int) (int, error)

type HandlerFuncs

type HandlerFuncs []http.HandlerFunc

func (HandlerFuncs) ServeHTTP

func (hs HandlerFuncs) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Handlers

type Handlers []http.Handler

func (Handlers) ServeHTTP

func (hs Handlers) ServeHTTP(w http.ResponseWriter, r *http.Request)
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) Values

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

type HttpResponse

type HttpResponse struct {
	Status  int            `json:"status,omitempty"`
	Headers MapHeader      `json:"header,omitempty"`
	Body    WriterToCloser `json:"body,omitempty"`
}

func (*HttpResponse) CommonResponse

func (res *HttpResponse) CommonResponse(w CommonResponseWriter) (int, error)

func (*HttpResponse) Response

func (res *HttpResponse) Response(w http.ResponseWriter) (int, error)

type HttpResponseRawBody

type HttpResponseRawBody struct {
	Status  int       `json:"status,omitempty"`
	Headers MapHeader `json:"header,omitempty"`
	Body    []byte    `json:"body,omitempty"`
}

func (*HttpResponseRawBody) CommonResponse

func (res *HttpResponseRawBody) CommonResponse(w CommonResponseWriter) (int, error)

func (*HttpResponseRawBody) Response

func (res *HttpResponseRawBody) Response(w http.ResponseWriter) (int, error)

type HttpResponseStream

type HttpResponseStream struct {
	Status  int              `json:"status,omitempty"`
	Headers MapHeader        `json:"header,omitempty"`
	Body    iter.Seq[[]byte] `json:"body,omitempty"`
}

func (*HttpResponseStream) CommonResponse

func (res *HttpResponseStream) CommonResponse(w ICommonResponseWriter) (int, error)

func (*HttpResponseStream) Response

func (res *HttpResponseStream) Response(w http.ResponseWriter) (int, error)

type ICommonResponseTo

type ICommonResponseTo interface {
	CommonResponse(w ICommonResponseWriter) (int, error)
}

type ICommonResponseWriter

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

type IHttpResponseTo

type IHttpResponseTo interface {
	Response(w http.ResponseWriter) (int, error)
}

type IntoHttpHeader

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

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) Values

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

type NoCloseBody

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

func NewNoCloseBody

func NewNoCloseBody(s []byte) *NoCloseBody

适用于轮询

func (*NoCloseBody) Close

func (r *NoCloseBody) Close() error

func (*NoCloseBody) Len

func (r *NoCloseBody) Len() int

func (*NoCloseBody) Read

func (r *NoCloseBody) Read(b []byte) (n int, err error)

func (*NoCloseBody) Size

func (r *NoCloseBody) Size() int64

type NoCloseStrBody

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

func NewNoCloseStrBody

func NewNoCloseStrBody(s string) *NoCloseStrBody

适用于轮询

func (*NoCloseStrBody) Close

func (r *NoCloseStrBody) Close() error

func (*NoCloseStrBody) Len

func (r *NoCloseStrBody) Len() int

func (*NoCloseStrBody) Read

func (r *NoCloseStrBody) Read(b []byte) (n int, err error)

func (*NoCloseStrBody) Size

func (r *NoCloseStrBody) Size() int64

type RawBody

type RawBody []byte

func (RawBody) Closer

func (res RawBody) Closer() error

func (RawBody) WriteTo

func (res RawBody) WriteTo(w io.Writer) (int64, error)

type ReceiveData

type ReceiveData = RespData[json.RawMessage]

func NewReceiveData

func NewReceiveData(code errors.ErrCode, msg string, data any) *ReceiveData

type RespAnyData

type RespAnyData = RespData[any]

func NewRespAnyData

func NewRespAnyData(code errors.ErrCode, msg string, data any) *RespAnyData

func NewSuccessRespData

func NewSuccessRespData(data any) *RespAnyData

type RespData

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

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

func NewRespData

func NewRespData[T any](code errors.ErrCode, msg string, data T) *RespData[T]

func (*RespData[T]) Response

func (res *RespData[T]) Response(w http.ResponseWriter) (int, error)

func (*RespData[T]) ResponseStatus

func (res *RespData[T]) ResponseStatus(w http.ResponseWriter, statusCode int) (int, error)

type ResponseRecorder

type ResponseRecorder struct {
	// Code is the HTTP response code set by WriteHeader.
	//
	// Note that if a Handler never calls WriteHeader or Write,
	// this might end up being 0, rather than the implicit
	// http.StatusOK. To get the implicit value, use the Result
	// method.
	Code int

	Headers http.Header

	// Body is the buffer to which the Handler's Write calls are sent.
	// If nil, the Writes are silently discarded.
	Body *bytes.Buffer

	// Flushed is whether the Handler called Flush.
	Flushed bool
	// contains filtered or unexported fields
}

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

func NewRecorder

func NewRecorder(header http.Header) *ResponseRecorder

NewRecorder returns an initialized ResponseRecorder.

func (*ResponseRecorder) Flush

func (rw *ResponseRecorder) Flush()

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

func (*ResponseRecorder) Header

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

Header implements http.ResponseWriter. It returns the response headers to mutate within a handler. To test the headers that were written after a handler completes, use the Result method and see the returned Response value's Header.

func (*ResponseRecorder) Reset

func (rw *ResponseRecorder) Reset()

func (*ResponseRecorder) Result

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

Result returns the response generated by the handler.

The returned Response will have at least its StatusCode, Header, Body, and optionally Trailer populated. More fields may be populated in the future, so callers should not DeepEqual the result in tests.

The Response.Header is a snapshot of the headers at the time of the first write call, or at the time of this call, if the handler never did a write.

The Response.Body is guaranteed to be non-nil and Body.Read call is guaranteed to not return any error other than io.EOF.

Result must only be called after the handler has finished running.

func (*ResponseRecorder) Write

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

Write implements http.ResponseWriter. The data in buf is written to rw.Body, if not nil.

func (*ResponseRecorder) WriteHeader

func (rw *ResponseRecorder) WriteHeader(code int)

WriteHeader implements http.ResponseWriter.

func (*ResponseRecorder) WriteString

func (rw *ResponseRecorder) WriteString(str string) (int, error)

WriteString implements io.StringWriter. The data in str is written to rw.Body, if not nil.

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) Values

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

type WriterToCloser

type WriterToCloser interface {
	io.WriterTo
	io.Closer
}

Directories

Path Synopsis
v2
fs
gin
web
`grpcweb` implements the gRPC-Web spec as a wrapper around a gRPC-Go Server.
`grpcweb` implements the gRPC-Web spec as a wrapper around a gRPC-Go Server.
Package httprouter is a trie based high performance HTTP request router.
Package httprouter is a trie based high performance HTTP request router.

Jump to

Keyboard shortcuts

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