Documentation
¶
Index ¶
- Constants
- Variables
- func CORS() func(next http.Handler) http.Handler
- func CopyBody(b io.ReadCloser) (*bytes.Buffer, io.ReadCloser, error)
- func Delete(url, contentType string, body io.Reader) (*http.Response, error)
- func GenId(id ...string) string
- func Get(url string) (*http.Response, error)
- func Head(url string) (resp *http.Response, err error)
- func ListenAndServe(ctx context.Context, h http.Handler, opts ...Option) error
- func Log(format string, v ...any)
- func LogS(ctx context.Context, stat *Stat)
- func NewRequestWithContext(ctx context.Context, options Options) (*http.Request, error)
- func PUT(url, contentType string, body io.Reader) (*http.Response, error)
- func ParseBody(r io.ReadCloser) (*bytes.Buffer, error)
- func Post(url string, contentType string, body io.Reader) (*http.Response, error)
- func PostForm(url string, data url.Values) (*http.Response, error)
- func SSE() func(next http.Handler) http.Handler
- func Socket(ctx context.Context, opts ...Option) (net.Conn, error)
- func WarpHandler(next http.Handler) func(http.Handler) http.Handler
- func WarpRoundTripper(next http.RoundTripper) func(http.RoundTripper) http.RoundTripper
- type Node
- type Option
- func BasicAuth(username, password string) Option
- func Body(body any) Option
- func CertKey(cert, key string) Option
- func Cookie(cookie http.Cookie) Option
- func Cookies(cookies ...http.Cookie) Option
- func Form(form url.Values) Option
- func Gzip(body any) Option
- func Header(k, v string) Option
- func Headers(kv map[string]string) Option
- func Host(host string) Option
- func LocalAddr(addr net.Addr) Option
- func Logf(f func(context.Context, *Stat)) Option
- func MaxConns(conn int) Option
- func Method(method string) Option
- func OnShutdown(f func(*http.Server)) Option
- func OnStart(f func(*http.Server)) Option
- func Param(k string, v ...string) Option
- func Params(query map[string]string) Option
- func Path(path string) Option
- func Proxy(addr string) Option
- func RoundTripper(tr http.RoundTripper) Option
- func Setup(fn ...func(tripper http.RoundTripper) http.RoundTripper) Option
- func Stream(stream func(int64, []byte) error) Option
- func Timeout(timeout time.Duration) Option
- func Trace(mLimit ...int) Option
- func URL(url string) Option
- func Use(fn ...func(http.Handler) http.Handler) Option
- func Verify(verify bool) Option
- type Options
- type Response
- type ResponseWriter
- func (w *ResponseWriter) Flush()
- func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *ResponseWriter) Push(target string, opts *http.PushOptions) error
- func (w *ResponseWriter) Read(b []byte) (int, error)
- func (w *ResponseWriter) Write(b []byte) (int, error)
- func (w *ResponseWriter) WriteHeader(statusCode int)
- type RoundTripperFunc
- type ServeMux
- func (mux *ServeMux) Handle(path string, h http.Handler, opts ...Option)
- func (mux *ServeMux) HandleFunc(path string, f func(http.ResponseWriter, *http.Request), opts ...Option)
- func (mux *ServeMux) Pprof()
- func (mux *ServeMux) Print()
- func (mux *ServeMux) Redirect(source, target string)
- func (mux *ServeMux) Route(path string, v any, opts ...Option)
- func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (mux *ServeMux) Use(fn ...func(http.Handler) http.Handler)
- type Server
- type ServerSentEvents
- func (s *ServerSentEvents) End()
- func (s *ServerSentEvents) Header() http.Header
- func (s *ServerSentEvents) Read(b []byte) ([]byte, error)
- func (s *ServerSentEvents) Send(name string, b []byte) (int, error)
- func (s *ServerSentEvents) Write(b []byte) (int, error)
- func (s *ServerSentEvents) WriteHeader(statusCode int)
- type Session
- func (s *Session) Do(ctx context.Context, opts ...Option) (*http.Response, error)
- func (s *Session) DoRequest(ctx context.Context, opts ...Option) (*Response, error)
- func (s *Session) HTTPClient() *http.Client
- func (s *Session) RoundTrip(r *http.Request) (*http.Response, error)
- func (s *Session) RoundTripper(opts ...Option) http.RoundTripper
- func (s *Session) Transport() *http.Transport
- type Stat
Constants ¶
const RequestId = "Request-Id"
Variables ¶
var ( MethodGet = Method("GET") MethodPost = Method("POST") )
Method http method
var ErrHandler = func(err string, code int) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, err, code) }) }
ErrHandler handler err
Functions ¶
func CopyBody ¶
func CopyBody(b io.ReadCloser) (*bytes.Buffer, io.ReadCloser, error)
CopyBody reads all of b to memory and then returns two equivalent ReadClosers yielding the same bytes.
It returns an error if the initial slurp of all bytes fails. It does not attempt to make the returned ReadClosers have identical error-matching behavior.
func ListenAndServe ¶
ListenAndServe listens on the TCP network address addr and then calls [Serve] with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.
The handler is typically nil, in which case [DefaultServeMux] is used.
ListenAndServe always returns a non-nil error.
func NewRequestWithContext ¶
NewRequestWithContext creates a new HTTP request with the given context and options. It handles: - Converting the request body to an appropriate io.Reader - Setting the request method and URL - Appending path segments - Setting query parameters - Setting headers and cookies
Returns the constructed http.Request and any error encountered during creation.
func ParseBody ¶
func ParseBody(r io.ReadCloser) (*bytes.Buffer, error)
ParseBody parse body from `Request.Body`.
func SSE ¶
SSE returns a middleware function that enables Server-Sent Events support. The middleware:
- Sets appropriate SSE headers (Content-Type, Cache-Control, etc.)
- Creates a ServerSentEvents wrapper for the response writer
- Ensures proper stream termination via deferred End() call
- Enables CORS support for cross-origin requests
func WarpHandler ¶
WarpHandler warp `http.Handler`.
func WarpRoundTripper ¶
func WarpRoundTripper(next http.RoundTripper) func(http.RoundTripper) http.RoundTripper
WarpRoundTripper wraps an http.RoundTripper instance. This function returns a new decorator function that adds additional functionality to an existing RoundTripper.
Types ¶
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node trie node
type Option ¶
type Option func(*Options)
Option func
func Host ¶
Host set net/http.Request.Host. 在客户端,请求的Host字段(可选地)用来重写请求的Host头。 如过该字段为"",Request.Write方法会使用URL字段的Host。
func LocalAddr ¶
LocalAddr local ip for tcp: &net.TCPAddr{IP: ip} for unix: &net.UnixAddr{Net: "unix", Name: "xxx")}
func OnShutdown ¶
func Proxy ¶
Proxy set proxy addr os.Setenv("HTTP_PROXY", "http://127.0.0.1:9743") os.Setenv("HTTPS_PROXY", "https://127.0.0.1:9743") https://stackoverflow.com/questions/14661511/setting-up-proxy-for-http-client
func RoundTripper ¶
func RoundTripper(tr http.RoundTripper) Option
RoundTripper set default `*http.Transport` by customer define.
func Setup ¶
func Setup(fn ...func(tripper http.RoundTripper) http.RoundTripper) Option
Setup is used for client middleware
func URL ¶
URL set client to dial connection use http transport or unix socket. IF using socket connection. you must set unix in session, and set http in request. For example, sess := requests.New(requests.URL("unix:///tmp/requests.sock")) sess.DoRequest(context.Background(), requests.URL("http://path?k=v"), requests.Body("12345")) https://old.lubui.com/2021/07/26/golang-socket-file/
type Options ¶
type Options struct { Method string URL string Path []string RawQuery url.Values Header http.Header Cookies []http.Cookie Timeout time.Duration MaxConns int Verify bool Transport http.RoundTripper HttpRoundTripper []func(http.RoundTripper) http.RoundTripper Handler http.Handler HttpHandler []func(http.Handler) http.Handler OnStart func(*http.Server) OnShutdown func(*http.Server) // client session used LocalAddr net.Addr Proxy func(*http.Request) (*url.URL, error) // contains filtered or unexported fields }
Options request
type Response ¶
type Response struct { *http.Request // 原始 HTTP 请求 *http.Response // 原始 HTTP 响应 StartAt time.Time // 请求开始时间 Cost time.Duration // 请求耗时 Content *bytes.Buffer // 响应内容缓存 Err error // 请求过程中的错误 }
Response 包装了 http.Response 结构体,提供了额外的功能: 1. 记录请求开始时间和耗时 2. 缓存响应内容 3. 错误处理 4. 统计信息收集
type ResponseWriter ¶
type ResponseWriter struct { http.ResponseWriter StatusCode int // HTTP 响应状态码 Content *bytes.Buffer // 响应内容的缓存 // contains filtered or unexported fields }
ResponseWriter 包装了 http.ResponseWriter 接口,提供了额外的功能: 1. 记录响应状态码 2. 缓存响应内容 3. 支持并发安全的读写操作
func (*ResponseWriter) Flush ¶
func (w *ResponseWriter) Flush()
Flush 实现 http.Flusher 接口 将缓冲的数据立即发送到客户端
func (*ResponseWriter) Hijack ¶
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack 实现 http.Hijacker 接口 允许接管 HTTP 连接
func (*ResponseWriter) Push ¶
func (w *ResponseWriter) Push(target string, opts *http.PushOptions) error
Push 实现 http.Pusher 接口 支持 HTTP/2 服务器推送功能
func (*ResponseWriter) Read ¶
func (w *ResponseWriter) Read(b []byte) (int, error)
Read 实现 io.Reader 接口 从内容缓存中读取数据
func (*ResponseWriter) Write ¶
func (w *ResponseWriter) Write(b []byte) (int, error)
Write 实现 io.Writer 接口 将数据同时写入原始 ResponseWriter 和内容缓存
func (*ResponseWriter) WriteHeader ¶
func (w *ResponseWriter) WriteHeader(statusCode int)
WriteHeader 设置 HTTP 响应状态码 该方法确保状态码只被设置一次
type RoundTripperFunc ¶
RoundTripperFunc is a functional implementation of the http.RoundTripper interface. It allows converting regular functions to the RoundTripper interface, facilitating functional extensions.
type ServeMux ¶
type ServeMux struct {
// contains filtered or unexported fields
}
ServeMux implement ServeHTTP interface.
func (*ServeMux) HandleFunc ¶
func (mux *ServeMux) HandleFunc(path string, f func(http.ResponseWriter, *http.Request), opts ...Option)
HandleFunc set func pattern path to handle path cannot override, so if your path not work, maybe it is already exists!
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server server
func (*Server) ListenAndServe ¶
ListenAndServe listens on the TCP network address srv.Addr and then calls [Serve] or [ServeTLS] to handle requests on incoming (TLS) connections. Accepted connections are configured to enable TCP keep-alives.
If srv.Addr is blank, ":http" is used.
Filenames containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.
ListenAndServe(TLS) always returns a non-nil error. After Server.Shutdown or [Server.Close], the returned error is [ErrServerClosed].
type ServerSentEvents ¶
type ServerSentEvents struct {
// contains filtered or unexported fields
}
ServerSentEvents implements http.Handler interface for Server-Sent Events (SSE) streaming. It wraps a http.ResponseWriter to provide SSE-specific functionality.
func (*ServerSentEvents) End ¶
func (s *ServerSentEvents) End()
End terminates the SSE stream by writing two newlines. This should be called when the stream is complete.
func (*ServerSentEvents) Header ¶
func (s *ServerSentEvents) Header() http.Header
Header implements http.ResponseWriter interface. It returns the header map that will be sent by WriteHeader.
func (*ServerSentEvents) Read ¶
func (s *ServerSentEvents) Read(b []byte) ([]byte, error)
Read parses an SSE message from the given byte slice. It handles different types of SSE events (empty, event, data). Returns:
- For data events: returns the event value
- For empty or event lines: returns nil, nil
- For unknown events: returns nil and an error
func (*ServerSentEvents) Send ¶
func (s *ServerSentEvents) Send(name string, b []byte) (int, error)
Send writes a named SSE event with formatted data to the stream. It automatically flushes the response after writing. Parameters:
- name: The event name (e.g., "data", "event", etc.)
- b: The byte slice containing the event data
func (*ServerSentEvents) Write ¶
func (s *ServerSentEvents) Write(b []byte) (int, error)
Write implements http.ResponseWriter interface. It writes the byte slice as a data event to the SSE stream.
func (*ServerSentEvents) WriteHeader ¶
func (s *ServerSentEvents) WriteHeader(statusCode int)
WriteHeader implements http.ResponseWriter interface. It writes the HTTP status code to the response.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session httpclient session Clients and Transports are safe for concurrent use by multiple goroutines for efficiency should only be created once and re-used. so, session is also safe for concurrent use by multiple goroutines.
func (*Session) Do ¶
Do send a request and return `http.Response`. DO NOT forget close `resp.Body`. transport【http.Transport】-> http.client.Do -> transport.RoundTrip
func (*Session) DoRequest ¶
DoRequest send a request and return a response, and is safely close `resp.Body`.
func (*Session) HTTPClient ¶
HTTPClient returns the http.Client that is configured to be used for HTTP requests.
func (*Session) RoundTrip ¶
RoundTrip implements the RoundTripper interface. Like the `http.RoundTripper` interface, the error types returned by RoundTrip are unspecified.
func (*Session) RoundTripper ¶
func (s *Session) RoundTripper(opts ...Option) http.RoundTripper
RoundTripper returns a configured http.RoundTripper. It applies all registered middleware in reverse order.
type Stat ¶
type Stat struct { RequestId string `json:"RequestId"` StartAt string `json:"StartAt"` Cost int64 `json:"Cost"` Request struct { // RemoteAddr is remote addr in server side, // For client requests, it is unused. RemoteAddr string `json:"RemoteAddr"` // URL is Request.URL // For client requests, is request addr. contains schema://ip:port/path/xx // For server requests, is only path. eg: /api/v1/xxx URL string `json:"URL"` Method string `json:"Method"` Header map[string]string `json:"Header"` Body any `json:"Body"` } `json:"Request"` Response struct { // URL is server addr(http://127.0.0.1:8080). // For client requests, it is unused. URL string `json:"URL"` Header map[string]string `json:"Header"` Body any `json:"Body"` StatusCode int `json:"StatusCode"` ContentLength int64 `json:"ContentLength"` } `json:"Response"` Err string `json:"Err"` }
Stat stats