xhttp

package
v0.0.0-...-2a88403 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2024 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SchemeHTTPPrefix  = "http://"
	SchemeHTTPSPrefix = "https://"
)

协议前缀

View Source
const (
	MethodGet     = http.MethodGet
	MethodHead    = http.MethodHead
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodPatch   = http.MethodPatch
	MethodDelete  = http.MethodDelete
	MethodConnect = http.MethodConnect
	MethodOptions = http.MethodOptions
	MethodTrace   = http.MethodTrace
)

HTTP 方法

View Source
const (
	HeaderAccept               = "Accept"
	HeaderAcceptEncoding       = "Accept-Encoding"
	HeaderAcceptLanguage       = "Accept-Language"
	HeaderAccessToken          = "Access-Token"
	HeaderAllow                = "Allow"
	HeaderAuthorization        = "Authorization"
	HeaderCacheControl         = "Cache-Control"
	HeaderContentDisposition   = "Content-Disposition"
	HeaderContentEncoding      = "Content-Encoding"
	HeaderContentLength        = "Content-Length"
	HeaderContentType          = "Content-Type"
	HeaderDate                 = "Date"
	HeaderHost                 = "Host"
	HeaderLocation             = "Location"
	HeaderOrigin               = "Origin"
	HeaderRange                = "Range"
	HeaderReferer              = "Referer"
	HeaderToken                = "Token"
	HeaderUserAgent            = "User-Agent"
	HeaderVary                 = "Vary"
	HeaderXAppEngineRemoteAddr = "X-Appengine-Remote-Addr"
	HeaderXCSRFToken           = "X-Csrf-Token"
	HeaderXForwardedFor        = "X-Forwarded-For"
	HeaderXHealthSecret        = "X-Health-Secret"
	HeaderXRealIP              = "X-Real-Ip"
	HeaderXRequestedWith       = "X-Requested-With"

	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"

	HeaderCaErrorCode    = "X-Ca-Error-Code"
	HeaderCaErrorMessage = "X-Ca-Error-Message"
)

HTTP 头部

View Source
const (
	MIMEForm                      = "application/x-www-form-urlencoded"
	MIMEMultipartForm             = "multipart/form-data"
	MIMEMultipartFormWithBoundary = MIMEMultipartForm + "; boundary="
	MIMETextPlain                 = "text/plain"
	MIMEApplicationJSON           = "application/json"
	MIMEApplicationXML            = "application/xml"
	MIMEApplicationPDF            = "application/pdf"
	MIMEApplicationZip            = "application/zip"
	MIMEOctetStream               = "application/octet-stream"
)

MIME 类型

Variables

This section is empty.

Functions

func CopyRequest

func CopyRequest(r *http.Request, maxBodyLen ...int64) (*http.Request, error)

CopyRequest 复制请求

func ErrorCtx

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

ErrorCtx 错误响应包装返回

func FromFile

func FromFile(r *http.Request, name string) (*multipart.FileHeader, error)

FromFile 请求表单文件获取

func GetClientIP

func GetClientIP(r *http.Request) string

GetClientIP 获取客户端的IP

func GetInternalIP

func GetInternalIP() string

GetInternalIP 获取服务端的内部IP

func GetQuery

func GetQuery(r *http.Request, key string) (string, bool)

GetQuery 返回给定请求查询参数键的字符串值并判断其是否存在

func GetQueryArray

func GetQueryArray(r *http.Request, key string) ([]string, bool)

GetQueryArray 返回给定请求查询参数键的字符串切片值并判断其是否存在

func GetReaderLen

func GetReaderLen(reader io.Reader) (int64, error)

GetReaderLen 获取读取器实际内容长度

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID 获取链路追踪ID

func NewHTTPClient

func NewHTTPClient(config ...Config) *http.Client

NewHTTPClient 新建 HTTP 客户端(不传递配置时,将使用默认配置 DefaultConfig)

func OkJsonCtx

func OkJsonCtx(ctx context.Context, w http.ResponseWriter, v any)

OkJsonCtx 成功 json 响应返回

func Parse

func Parse(r *http.Request, v any) error

Parse 请求体解析

func ParseEndpoint

func ParseEndpoint(endpoint string) (parsedEndpoint string, useSSL bool)

ParseEndpoint 解析节点地址

func ParseForm

func ParseForm(r *http.Request, v any) error

ParseForm 请求表单解析

func ParseJsonBody

func ParseJsonBody(r *http.Request, v any) error

ParseJsonBody 解析 json 请求体

func Query

func Query(r *http.Request, key string) string

Query 返回给定请求查询参数键的字符串值

func QueryArray

func QueryArray(r *http.Request, key string) []string

QueryArray 返回给定请求查询参数键的字符串切片值

func TypeByExtension

func TypeByExtension(filePath string) string

TypeByExtension 获取与文件扩展名所关联的 MIME 类型以用于 HTTP 连接的 Content-Type 请求头中

func WithHTTPScheme

func WithHTTPScheme(url string) string

WithHTTPScheme 添加 HTTP 协议前缀

func WriteHeader

func WriteHeader(w http.ResponseWriter, err ...error)

WriteHeader 写入自定义响应 header

Types

type Config

type Config struct {
	HTTPTimeout           time.Duration // HTTP 请求超时时间
	DialTimeout           time.Duration // 拨号超时时间
	DialKeepAlive         time.Duration // 拨号保持连接时间
	MaxIdleConns          int           // 最大空闲连接数
	MaxIdleConnsPerHost   int           // 每个主机最大空闲连接数
	IdleConnTimeout       time.Duration // 空闲连接超时时间
	TLSHandshakeTimeout   time.Duration // TLS 握手超时时间
	ExpectContinueTimeout time.Duration // 期望继续超时时间
}

Config HTTP 客户端配置

func DefaultConfig

func DefaultConfig() Config

DefaultConfig 获取默认 HTTP 客户端配置

type DetailLoggedResponseWriter

type DetailLoggedResponseWriter struct {
	W   *LoggedResponseWriter
	Buf *bytes.Buffer
}

DetailLoggedResponseWriter 详细日志记录响应写入器

func NewDetailLoggedResponseWriter

func NewDetailLoggedResponseWriter(w http.ResponseWriter) *DetailLoggedResponseWriter

NewDetailLoggedResponseWriter 新建详细日志记录响应写入器

func (*DetailLoggedResponseWriter) Flush

func (w *DetailLoggedResponseWriter) Flush()

Flush 实现 Flush 方法

func (*DetailLoggedResponseWriter) Header

Header 实现 Header 方法

func (*DetailLoggedResponseWriter) Hijack

Hijack 实现 Hijack 方法

func (*DetailLoggedResponseWriter) Write

func (w *DetailLoggedResponseWriter) Write(bs []byte) (int, error)

Write 实现 Write 方法

func (*DetailLoggedResponseWriter) WriteHeader

func (w *DetailLoggedResponseWriter) WriteHeader(code int)

WriteHeader 实现 WriteHeader 方法

type LoggedResponseWriter

type LoggedResponseWriter struct {
	W    http.ResponseWriter
	Code int
}

LoggedResponseWriter 日志记录响应写入器

func NewLoggedResponseWriter

func NewLoggedResponseWriter(w http.ResponseWriter) *LoggedResponseWriter

NewLoggedResponseWriter 新建日志记录响应写入器

func (*LoggedResponseWriter) Flush

func (w *LoggedResponseWriter) Flush()

Flush 实现 Flush 方法

func (*LoggedResponseWriter) Header

func (w *LoggedResponseWriter) Header() http.Header

Header 实现 Header 方法

func (*LoggedResponseWriter) Hijack

Hijack 实现 Hijack 方法

func (*LoggedResponseWriter) Write

func (w *LoggedResponseWriter) Write(bs []byte) (int, error)

Write 实现 Write 方法

func (*LoggedResponseWriter) WriteHeader

func (w *LoggedResponseWriter) WriteHeader(code int)

WriteHeader 实现 WriteHeader 方法

type MultipartWriter

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

A MultipartWriter generates multipart messages.

func NewMultipartWriter

func NewMultipartWriter(w io.Writer) *MultipartWriter

NewMultipartWriter returns a new multipart Writer with a random boundary, writing to w.

func (*MultipartWriter) Boundary

func (w *MultipartWriter) Boundary() string

Boundary returns the Writer's boundary.

func (*MultipartWriter) Close

func (w *MultipartWriter) Close() error

Close finishes the multipart message and writes the trailing boundary end line to the output.

func (*MultipartWriter) CreateFormField

func (w *MultipartWriter) CreateFormField(fieldName string) (io.Writer, error)

CreateFormField calls CreatePart with a header using the given field name.

func (*MultipartWriter) CreateFormFile

func (w *MultipartWriter) CreateFormFile(fieldName, fileName string, contentType ...string) (io.Writer, error)

CreateFormFile is a convenience wrapper around CreatePart. It creates a new form-data header with the provided field name and file name.

func (*MultipartWriter) CreatePart

func (w *MultipartWriter) CreatePart(header textproto.MIMEHeader) (io.Writer, error)

CreatePart creates a new multipart section with the provided header. The body of the part should be written to the returned Writer. After calling CreatePart, any previous part may no longer be written to.

func (*MultipartWriter) FormDataContentType

func (w *MultipartWriter) FormDataContentType() string

FormDataContentType returns the Content-Type for an HTTP multipart/form-data with this Writer's Boundary.

func (*MultipartWriter) SetBoundary

func (w *MultipartWriter) SetBoundary(boundary string) error

SetBoundary overrides the Writer's default randomly-generated boundary separator with an explicit value.

SetBoundary must be called before any parts are created, may only contain certain ASCII characters, and must be non-empty and at most 70 bytes long.

func (*MultipartWriter) WriteField

func (w *MultipartWriter) WriteField(fieldName, value string) error

WriteField calls CreateFormField and then writes the given value.

func (*MultipartWriter) WriteFile

func (w *MultipartWriter) WriteFile(fieldName, fileName string, fileReader io.Reader, contentType ...string) (string, error)

WriteFile calls CreateFormFile and then writes the given file reader. It also returns the file content type.

type Response

type Response struct {
	TraceID string `json:"trace_id,omitempty" xml:"trace_id,omitempty" example:"a1b2c3d4e5f6g7h8"` // 链路追踪ID
	Code    uint32 `json:"code" xml:"code" example:"0"`                                            // 状态码
	Msg     string `json:"msg" xml:"msg" example:"ok"`                                             // 消息
	Data    any    `json:"data,omitempty" xml:"data,omitempty"`                                    // 数据
}

Response 业务通用响应体

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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