?
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
import "net/http"
概述
索引
示例
子目錄
http包提供HTTP客戶端和服務器實現(xiàn)。
Get,Head,Post和PostForm發(fā)出HTTP(或HTTPS)請求:
resp, err := http.Get("http://example.com/")...resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)...resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})
客戶必須在完成后關閉響應主體:
resp, err := http.Get("http://example.com/")if err != nil {// handle error}defer resp.Body.Close()body, err := ioutil.ReadAll(resp.Body)// ...
要控制HTTP客戶端標題,重定向策略和其他設置,請創(chuàng)建一個客戶端:
client := &http.Client{ CheckRedirect: redirectPolicyFunc,}resp, err := client.Get("http://example.com")// ...req, err := http.NewRequest("GET", "http://example.com", nil)// ...req.Header.Add("If-None-Match", `W/"wyzzy"`)resp, err := client.Do(req)// ...
為了控制代理,TLS配置,?;?,壓縮和其他設置,請創(chuàng)建一個傳輸:
tr := &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: true,}client := &http.Client{Transport: tr}resp, err := client.Get("https://example.com")
客戶端和傳輸對于多個goroutine并發(fā)使用是安全的,并且效率應該只創(chuàng)建一次并重新使用。
ListenAndServe啟動一個具有給定地址和處理程序的HTTP服務器。處理程序通常為零,這意味著使用DefaultServeMux。Handle和HandleFunc將處理程序添加到DefaultServeMux:
http.Handle("/foo", fooHandler)http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))})log.Fatal(http.ListenAndServe(":8080", nil))
通過創(chuàng)建自定義服務器,可以更好地控制服務器的行為:
s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20,}log.Fatal(s.ListenAndServe())
從Go 1.6開始,http包在使用HTTPS時對HTTP/2協(xié)議有透明的支持。必須禁用HTTP/2的程序可以通過將Transport.TLSNextProto(對于客戶端)或Server.TLSNextProto(對于服務器)設置為非零空映射來實現(xiàn)?;蛘?,當前支持以下GODEBUG環(huán)境變量:
GODEBUG=http2client=0 # disable HTTP/2 client support GODEBUG=http2server=0 # disable HTTP/2 server support GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs GODEBUG=http2debug=2 # ... even more verbose, with frame dumps
Go的API兼容性承諾不涵蓋GODEBUG變量。
http包的傳輸和服務器都自動為簡單配置啟用HTTP/2支持。要為更復雜的配置啟用HTTP/2,使用較低級別的HTTP/2功能或使用Go的http2軟件包的較新版本,請直接導入“golang.org/x/net/http2”并使用其配置傳輸和/或ConfigureServer功能。通過golang.org/x/net/http2軟件包手動配置HTTP/2優(yōu)先于net/http軟件包內(nèi)置的HTTP/2支持。
常量
變量
func CanonicalHeaderKey(s string) string
func DetectContentType(data []byte) string
func Error(w ResponseWriter, error string, code int)
func Handle(pattern string, handler Handler)
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
func ListenAndServe(addr string, handler Handler) error
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
func NotFound(w ResponseWriter, r *Request)
func ParseHTTPVersion(vers string) (major, minor int, ok bool)
func ParseTime(text string) (t time.Time, err error)
func ProxyFromEnvironment(req *Request) (*url.URL, error)
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
func Redirect(w ResponseWriter, r *Request, url string, code int)
func Serve(l net.Listener, handler Handler) error
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
func ServeFile(w ResponseWriter, r *Request, name string)
func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
func SetCookie(w ResponseWriter, cookie *Cookie)
func StatusText(code int) string
type Client
func (c *Client) Do(req *Request) (*Response, error)
func (c *Client) Get(url string) (resp *Response, err error)
func (c *Client) Head(url string) (resp *Response, err error)
func (c *Client) Post(url string, contentType string, body io.Reader) (resp *Response, err error)
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
type CloseNotifier
type ConnState
func (c ConnState) String() string
type Cookie
func (c *Cookie) String() string
type CookieJar
type Dir
func (d Dir) Open(name string) (File, error)
type File
type FileSystem
type Flusher
type Handler
func FileServer(root FileSystem) Handler
func NotFoundHandler() Handler
func RedirectHandler(url string, code int) Handler
func StripPrefix(prefix string, h Handler) Handler
func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
type HandlerFunc
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
type Header
func (h Header) Add(key, value string)
func (h Header) Del(key string)
func (h Header) Get(key string) string
func (h Header) Set(key, value string)
func (h Header) Write(w io.Writer) error
func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error
type Hijacker
type ProtocolError
func (pe *ProtocolError) Error() string
type PushOptions
type Pusher
type Request
func NewRequest(method, url string, body io.Reader) (*Request, error)
func ReadRequest(b *bufio.Reader) (*Request, error)
func (r *Request) AddCookie(c *Cookie)
func (r *Request) BasicAuth() (username, password string, ok bool)
func (r *Request) Context() context.Context
func (r *Request) Cookie(name string) (*Cookie, error)
func (r *Request) Cookies() []*Cookie
func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
func (r *Request) FormValue(key string) string
func (r *Request) MultipartReader() (*multipart.Reader, error)
func (r *Request) ParseForm() error
func (r *Request) ParseMultipartForm(maxMemory int64) error
func (r *Request) PostFormValue(key string) string
func (r *Request) ProtoAtLeast(major, minor int) bool
func (r *Request) Referer() string
func (r *Request) SetBasicAuth(username, password string)
func (r *Request) UserAgent() string
func (r *Request) WithContext(ctx context.Context) *Request
func (r *Request) Write(w io.Writer) error
func (r *Request) WriteProxy(w io.Writer) error
type Response
func Get(url string) (resp *Response, err error)
func Head(url string) (resp *Response, err error)
func Post(url string, contentType string, body io.Reader) (resp *Response, err error)
func PostForm(url string, data url.Values) (resp *Response, err error)
func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
func (r *Response) Cookies() []*Cookie
func (r *Response) Location() (*url.URL, error)
func (r *Response) ProtoAtLeast(major, minor int) bool
func (r *Response) Write(w io.Writer) error
type ResponseWriter
type RoundTripper
func NewFileTransport(fs FileSystem) RoundTripper
type ServeMux
func NewServeMux() *ServeMux
func (mux *ServeMux) Handle(pattern string, handler Handler)
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
type Server
func (srv *Server) Close() error
func (srv *Server) ListenAndServe() error
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
func (srv *Server) RegisterOnShutdown(f func())
func (srv *Server) Serve(l net.Listener) error
func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
func (srv *Server) SetKeepAlivesEnabled(v bool)
func (srv *Server) Shutdown(ctx context.Context) error
type Transport
func (t *Transport) CancelRequest(req *Request)
func (t *Transport) CloseIdleConnections()
func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)
func (t *Transport) RoundTrip(req *Request) (*Response, error)
FileServer FileServer (StripPrefix) Get Hijacker ResponseWriter (Trailers) ServeMux.Handle StripPrefix
client.go cookie.go doc.go filetransport.go fs.go h2_bundle.go header.go http.go jar.go method.go request.go response.go server.go sniff.go status.go transfer.go transport.go
常見的HTTP方法。
除非另有說明,否則這些在RFC 7231第4.3節(jié)中定義。
const ( MethodGet = "GET" MethodHead = "HEAD" MethodPost = "POST" MethodPut = "PUT" MethodPatch = "PATCH" // RFC 5789 MethodDelete = "DELETE" MethodConnect = "CONNECT" MethodOptions = "OPTIONS" MethodTrace = "TRACE")
向IANA注冊的HTTP狀態(tài)代碼。
const ( StatusContinue = 100 // RFC 7231, 6.2.1 StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusOK = 200 // RFC 7231, 6.3.1 StatusCreated = 201 // RFC 7231, 6.3.2 StatusAccepted = 202 // RFC 7231, 6.3.3 StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4 StatusNoContent = 204 // RFC 7231, 6.3.5 StatusResetContent = 205 // RFC 7231, 6.3.6 StatusPartialContent = 206 // RFC 7233, 4.1 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 StatusMultipleChoices = 300 // RFC 7231, 6.4.1 StatusMovedPermanently = 301 // RFC 7231, 6.4.2 StatusFound = 302 // RFC 7231, 6.4.3 StatusSeeOther = 303 // RFC 7231, 6.4.4 StatusNotModified = 304 // RFC 7232, 4.1 StatusUseProxy = 305 // RFC 7231, 6.4.5 StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7 StatusPermanentRedirect = 308 // RFC 7538, 3 StatusBadRequest = 400 // RFC 7231, 6.5.1 StatusUnauthorized = 401 // RFC 7235, 3.1 StatusPaymentRequired = 402 // RFC 7231, 6.5.2 StatusForbidden = 403 // RFC 7231, 6.5.3 StatusNotFound = 404 // RFC 7231, 6.5.4 StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5 StatusNotAcceptable = 406 // RFC 7231, 6.5.6 StatusProxyAuthRequired = 407 // RFC 7235, 3.2 StatusRequestTimeout = 408 // RFC 7231, 6.5.7 StatusConflict = 409 // RFC 7231, 6.5.8 StatusGone = 410 // RFC 7231, 6.5.9 StatusLengthRequired = 411 // RFC 7231, 6.5.10 StatusPreconditionFailed = 412 // RFC 7232, 4.2 StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11 StatusRequestURITooLong = 414 // RFC 7231, 6.5.12 StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13 StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4 StatusExpectationFailed = 417 // RFC 7231, 6.5.14 StatusTeapot = 418 // RFC 7168, 2.3.3 StatusUnprocessableEntity = 422 // RFC 4918, 11.2 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusUpgradeRequired = 426 // RFC 7231, 6.5.15 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusUnavailableForLegalReasons = 451 // RFC 7725, 3 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 StatusServiceUnavailable = 503 // RFC 7231, 6.6.4 StatusGatewayTimeout = 504 // RFC 7231, 6.6.5 StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6 StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 StatusInsufficientStorage = 507 // RFC 4918, 11.5 StatusLoopDetected = 508 // RFC 5842, 7.2 StatusNotExtended = 510 // RFC 2774, 7 StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6)
DefaultMaxHeaderBytes是HTTP請求中頭部允許的最大大小。這可以通過設置Server.MaxHeaderBytes來覆蓋。
const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
DefaultMaxIdleConnsPerHost是Transport的MaxIdleConnsPerHost的默認值。
const DefaultMaxIdleConnsPerHost = 2
TimeFormat是在HTTP頭中生成時間時使用的時間格式。它就像time.RFC1123一樣,但是將GMT編碼為時區(qū)。格式化的時間必須以UTC格式生成正確的格式。
有關解析此時間格式的信息,請參閱ParseTime。
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
TrailerPrefix是ResponseWriter.Header映射鍵的奇幻的前綴,如果存在,它表示映射條目實際上是用于響應預告片的,而不是響應標頭。在ServeHTTP呼叫結束并且值在trailers中發(fā)送后,該前綴被剝離。
該機制僅適用于在寫入標題之前未知的trailers。如果在寫入標題之前,一套trailers是固定的或已知的,則優(yōu)選正常的trailers機制:
https://golang.org/pkg/net/http/#ResponseWriter https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
const TrailerPrefix = "Trailer:"
var ( // 推送法返回 ErrNotSupported // 實現(xiàn)來指示 HTTP\/2 推送支持不是 // 可用。 ErrNotSupported = &ProtocolError{"feature not supported"} // ErrUnexpectedTrailer 由傳輸返回, 當服務器 // 答復與拖車頭, 但沒有塊答復。 ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"} // ErrMissingBoundary 是按請求返回的. MultipartReader 當 // request's Content-Type does not include a "boundary" parameter. ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"} // ErrNotMultipart is returned by Request.MultipartReader when the // request's Content-Type is not multipart/form-data. ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"} // Deprecated: ErrHeaderTooLong is not used. ErrHeaderTooLong = &ProtocolError{"header too long"} // Deprecated: ErrShortBody is not used. ErrShortBody = &ProtocolError{"entity body too short"} // Deprecated: ErrMissingContentLength is not used. ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"})
HTTP服務器使用的錯誤。
var ( // ErrBodyNotAllowed is returned by ResponseWriter.Write calls // when the HTTP method or response code does not permit a // body. ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body") // ErrHijacked is returned by ResponseWriter.Write calls when // the underlying connection has been hijacked using the // Hijacker interface. A zero-byte write on a hijacked // connection will return ErrHijacked without any other side // effects. ErrHijacked = errors.New("http: connection has been hijacked") // ErrContentLength is returned by ResponseWriter.Write calls // when a Handler set a Content-Length response header with a // declared size and then attempted to write more bytes than // declared. ErrContentLength = errors.New("http: wrote more than the declared Content-Length") // Deprecated: ErrWriteAfterFlush is no longer used. ErrWriteAfterFlush = errors.New("unused"))
var ( // ServerContextKey 是一個上下文鍵??捎糜?nbsp;HTTP // 具有上下文的處理程序。WithValue 訪問服務器, // 已啟動處理程序。關聯(lián)的值將為 // 類型 * 服務器。 ServerContextKey = &contextKey{"http-server"} // LocalAddrContextKey 是一個上下文鍵??捎糜?nbsp; // 帶有上下文的 HTTP 處理程序。WithValue 訪問地址 // 連接到達的本地地址。 // 關聯(lián)的值將為類型網(wǎng)。地址. LocalAddrContextKey = &contextKey{"local-addr"})
DefaultClient是默認的客戶端,由Get,Head和Post使用。
var DefaultClient = &Client{}
DefaultServeMux是Serve使用的默認ServeMux。
var DefaultServeMux = &defaultServeMux
ErrAbortHandler是中止處理程序的標志性恐慌值。雖然ServeHTTP的任何恐慌都會中止對客戶端的響應,但使用ErrAbortHandler進行恐慌也會禁止將堆棧跟蹤記錄到服務器的錯誤日志中。
var ErrAbortHandler = errors.New("net/http: abort Handler")
在正文關閉后讀取Request或Response Body時返回ErrBodyReadAfterClose。這通常發(fā)生在HTTP處理程序在其ResponseWriter上調用WriteHeader或Write之后讀取主體時。
var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
在超時的處理程序中的ResponseWriter Write調用上返回ErrHandlerTimeout。
var ErrHandlerTimeout = errors.New("http: Handler timeout")
當讀取格式不正確的分塊編碼的請求或響應主體時,返回ErrLineTooLong。
var ErrLineTooLong = internal.ErrLineTooLong
當提供的文件字段名稱不存在于請求中或文件字段中時,F(xiàn)ormFile將返回ErrMissingFile。
var ErrMissingFile = errors.New("http: no such file")
當找不到cookie時,ErrNoCookie通過Request的Cookie方法返回。
var ErrNoCookie = errors.New("http: named cookie not present")
當沒有位置標題時,ErrNoLocation由Response's Location方法返回。
var ErrNoLocation = errors.New("http: no Location header in response")
在調用Shutdown或Close之后,服務器的Serve,ServeTLS,ListenAndServe和ListenAndServeTLS方法會返回ErrServerClosed。
var ErrServerClosed = errors.New("http: Server closed")
ErrSkipAltProtocol是由Transport.RegisterProtocol定義的一個sentinel錯誤值。
var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")
Client.CheckRedirect鉤子可以返回ErrUseLastResponse來控制重定向的處理方式。如果返回,則不會發(fā)送下一個請求,并且返回其最新的響應,并且其主體未關閉。
var ErrUseLastResponse = errors.New("net/http: use last response")
NoBody是一個沒有字節(jié)的io.ReadCloser。閱讀始終返回EOF和關閉總是返回零。它可用于傳出的客戶端請求中,以明確表示請求具有零字節(jié)。但是,另一種方法是簡單地將Request.Body設置為零。
var NoBody = noBody{}
func CanonicalHeaderKey(s string) string
CanonicalHeaderKey返回標題密鑰的規(guī)范格式。規(guī)范化將第一個字母和連字符后面的任何字母轉換為大寫;其余的都轉換為小寫。例如,“accept-encoding”的規(guī)范密鑰是“Accept-Encoding”。如果s包含空格或無效標題字段字節(jié),則不做任何修改就返回。
func DetectContentType(data []byte) string
DetectContentType實現(xiàn)http://mimesniff.spec.whatwg.org/中描述的算法來確定給定數(shù)據(jù)的內(nèi)容類型。它至多會考慮前512個字節(jié)的數(shù)據(jù)。DetectContentType始終返回一個有效的MIME類型:如果無法確定更具體的MIME類型,則返回“application/octet-stream”。
func Error(w ResponseWriter, error string, code int)
錯誤以指定的錯誤消息和HTTP代碼答復請求。它不以其他方式結束請求;調用者應該確保沒有進一步寫入w。錯誤信息應該是純文本。
func Handle(pattern string, handler Handler)
Handle將給定模式的處理程序注冊到DefaultServeMux中。ServeMux的文檔解釋了模式如何匹配。
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
HandleFunc在DefaultServeMux中為給定模式注冊處理函數(shù)。ServeMux的文檔解釋了模式如何匹配。
func ListenAndServe(addr string, handler Handler) error
ListenAndServe偵聽TCP網(wǎng)絡地址addr,然后使用處理程序調用Serve來處理傳入連接上的請求。接受的連接被配置為啟用TCP保持活動。Handler通常為零,在這種情況下使用DefaultServeMux。
一個簡單的示例服務器是:
package mainimport ("io""net/http""log")// hello world, the web serverfunc HelloServer(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, world!\n")}func main() { http.HandleFunc("/hello", HelloServer) log.Fatal(http.ListenAndServe(":12345", nil))}
ListenAndServe總是返回一個非零錯誤。
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
ListenAndServeTLS的作用與ListenAndServe完全相同,只不過它需要HTTPS連接。此外,必須提供包含服務器證書和匹配私鑰的文件。如果證書由證書頒發(fā)機構簽署,則certFile應該是服務器證書,任何中間器和CA證書的串聯(lián)。
一個簡單的示例服務器是:
import ("log""net/http")func handler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Write([]byte("This is an example server.\n"))}func main() { http.HandleFunc("/", handler) log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/") err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil) log.Fatal(err)}
可以使用crypto/tls中的generate_cert.go來生成cert.pem和key.pem。
ListenAndServeTLS總是返回一個非零錯誤。
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
MaxBytesReader與io.LimitReader類似,但是用于限制傳入請求體的大小。與io.LimitReader相反,MaxBytesReader的結果是一個ReadCloser,它為超出限制的Read返回一個非EOF錯誤,并在其Close方法被調用時關閉底層的閱讀器。
MaxBytesReader可防止客戶端意外或惡意發(fā)送大量請求并浪費服務器資源。
func NotFound(w ResponseWriter, r *Request)
NotFound使用HTTP 404找不到錯誤來回復請求。
func ParseHTTPVersion(vers string) (major, minor int, ok bool)
ParseHTTPVersion分析HTTP版本字符串。“HTTP/1.0”返回(1, 0, true)。
func ParseTime(text string) (t time.Time, err error)
ParseTime分析時間標題(例如Date: header),嘗試HTTP/1.1允許的三種格式:TimeFormat,time.RFC850和time.ANSIC。
func ProxyFromEnvironment(req *Request) (*url.URL, error)
ProxyFromEnvironment返回用于給定請求的代理的URL,如環(huán)境變量HTTP_PROXY,HTTPS_PROXY和NO_PROXY(或其小寫版本)所示。對于https請求,HTTPS_PROXY優(yōu)先于HTTP_PROXY。
環(huán)境值可以是完整的URL或“host:port”,在這種情況下,假設“http”方案。如果值是不同的形式,則返回錯誤。
如果沒有在環(huán)境中定義代理,或者代理不應該用于給定請求(如NO_PROXY所定義),則返回零URL和零錯誤。
作為一種特殊情況,如果req.URL.Host是“l(fā)ocalhost”(帶或不帶端口號),則會返回一個零URL和零錯誤。
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
ProxyURL返回一個總是返回相同URL的代理函數(shù)(用于傳輸)。
func Redirect(w ResponseWriter, r *Request, url string, code int)
將重定向到url的請求重定向到請求,url可能是相對于請求路徑的路徑。
提供的代碼應該位于3xx范圍內(nèi),通常是StatusMovedPermanently,StatusFound或StatusSeeOther。
func Serve(l net.Listener, handler Handler) error
Serve接受偵聽器l上的傳入HTTP連接,為每個服務器創(chuàng)建一個新的服務程序。服務程序讀取請求,然后調用處理程序來回復它們。Handler通常為零,在這種情況下使用DefaultServeMux。
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
ServeContent使用提供的ReadSeeker中的內(nèi)容答復請求。ServeContent優(yōu)于io.Copy的主要好處是它正確處理Range請求,設置MIME類型,并處理If-Match,If-Unmodified-Since,If-None-Match,If-Modified-Since和If-Range要求。
如果未設置響應的Content-Type標頭,則ServeContent首先嘗試從名稱的文件擴展名中推導出該類型,如果失敗,則返回讀取內(nèi)容的第一個塊并將其傳遞給DetectContentType。這個名字是沒有用的;特別是它可以是空的,并且不會在響應中發(fā)送。
如果modtime不是零時間或Unix紀元,則ServeContent將其包含在響應中的Last-Modified標頭中。如果請求包含If-Modified-Since標頭,則ServeContent使用modtime決定是否需要發(fā)送內(nèi)容。
內(nèi)容的Seek方法必須工作:ServeContent使用搜索到內(nèi)容的結尾來確定其大小。
如果調用者已經(jīng)根據(jù)RFC 7232第2.3節(jié)設置了w的ETag頭,則ServeContent使用它來處理使用If-Match,If-None-Match或If-Range的請求。
請注意* os.File實現(xiàn)了io.ReadSeeker接口。
func ServeFile(w ResponseWriter, r *Request, name string)
ServeFile使用指定文件或目錄的內(nèi)容答復請求。
如果提供的文件或目錄名稱是相對路徑,則相對于當前目錄進行解釋并可能上升到父目錄。如果提供的名稱是從用戶輸入構建的,則應在調用ServeFile之前對其進行消毒。作為預防措施,ServeFile將拒絕r.URL.Path包含“..”路徑元素的請求。
作為一種特殊情況,ServeFile將r.URL.Path以“/index.html”結尾的任何請求重定向到相同的路徑,而沒有最終的“index.html”。要避免這種重定向,請修改路徑或使用ServeContent。
func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
Serve接受listener l上的傳入HTTPS連接,為每個服務器創(chuàng)建一個新的服務程序。服務程序讀取請求,然后調用處理程序來回復它們。
Handler通常為零,在這種情況下使用DefaultServeMux。
此外,必須提供包含服務器證書和匹配私鑰的文件。如果證書由證書頒發(fā)機構簽署,則certFile應該是服務器證書,任何中間器和CA證書的串聯(lián)。
func SetCookie(w ResponseWriter, cookie *Cookie)
SetCookie將一個Set-Cookie頭添加到提供的ResponseWriter的頭文件中。提供的cookie必須具有有效的名稱。無效的Cookie可能會悄悄丟棄。
func StatusText(code int) string
StatusText返回HTTP狀態(tài)碼的文本。如果代碼未知,它將返回空字符串。
客戶端是一個HTTP客戶端。其零值(DefaultClient)是使用DefaultTransport的可用客戶端。
客戶端的傳輸通常具有內(nèi)部狀態(tài)(緩存的TCP連接),因此客戶端應該被重用,而不是根據(jù)需要創(chuàng)建。客戶端可以安全地由多個goroutine并發(fā)使用。
客戶端比RoundTripper(比如Transport)更高級,并且還處理諸如cookie和重定向之類的HTTP細節(jié)。
在重定向之后,客戶端將轉發(fā)在初始請求中設置的所有標頭,除了:
?將“Authorization”,“WWW-Authenticate”和“Cookie”等敏感標頭轉發(fā)給不受信任的目標時。在重定向到不是子域匹配的域或初始域的完全匹配時,這些標頭將被忽略。例如,從“foo.com”到“foo.com”或“sub.foo.com”的重定向將轉發(fā)敏感標題,但重定向到“bar.com”則不會。
?轉發(fā)“Cookie”標頭時使用非零 cookie Jar。由于每個重定向可能會改變cookie jar的狀態(tài),重定向可能會改變初始請求中設置的cookie。轉發(fā)“Cookie”標頭時,任何突變的Cookie都將被忽略,并期望Jar將插入這些帶有更新值的突變cookie(假設該匹配的來源)。如果Jar為零,則最初的cookie將不發(fā)送更改。
type Client struct { // Transport specifies the mechanism by which individual // HTTP requests are made. // If nil, DefaultTransport is used. Transport RoundTripper // CheckRedirect specifies the policy for handling redirects. // If CheckRedirect is not nil, the client calls it before // following an HTTP redirect. The arguments req and via are // the upcoming request and the requests made already, oldest // first. If CheckRedirect returns an error, the Client's Get // method returns both the previous Response (with its Body // closed) and CheckRedirect's error (wrapped in a url.Error) // instead of issuing the Request req. // As a special case, if CheckRedirect returns ErrUseLastResponse, // then the most recent response is returned with its body // unclosed, along with a nil error. // // If CheckRedirect is nil, the Client uses its default policy, // which is to stop after 10 consecutive requests. CheckRedirect func(req *Request, via []*Request) error // Jar specifies the cookie jar. // // The Jar is used to insert relevant cookies into every // outbound Request and is updated with the cookie values // of every inbound Response. The Jar is consulted for every // redirect that the Client follows. // // If Jar is nil, cookies are only sent if they are explicitly // set on the Request. Jar CookieJar // Timeout specifies a time limit for requests made by this // Client. The timeout includes connection time, any // redirects, and reading the response body. The timer remains // running after Get, Head, Post, or Do return and will // interrupt reading of the Response.Body. // // A Timeout of zero means no timeout. // // The Client cancels requests to the underlying Transport // using the Request.Cancel mechanism. Requests passed // to Client.Do may still set Request.Cancel; both will // cancel the request. // // For compatibility, the Client will also use the deprecated // CancelRequest method on Transport if found. New // RoundTripper implementations should use Request.Cancel // instead of implementing CancelRequest. Timeout time.Duration}
func (c *Client) Do(req *Request) (*Response, error)
不要發(fā)送HTTP請求,并按照客戶端上配置的策略(例如redirects, cookies,auth)返回HTTP響應。
如果由客戶端策略(如CheckRedirect)引起,或者無法說出HTTP(如網(wǎng)絡連接問題),則返回錯誤。非2xx狀態(tài)碼不會導致錯誤。
如果返回的錯誤為零,則Response將包含一個非零體,用戶需要關閉。如果Body尚未關閉,則客戶端的底層RoundTripper(通常是Transport)可能無法重新使用持久性TCP連接到服務器以進行后續(xù)“保持活動”請求。
如果非零,請求主體將被底層傳輸關閉,即使出現(xiàn)錯誤。
出錯時,可以忽略任何響應。非零錯誤的非零響應僅在CheckRedirect失敗時發(fā)生,即使返回的Response.Body已經(jīng)關閉。
通常會使用Get,Post或PostForm來代替Do.
如果服務器回復重定向,則客戶端首先使用CheckRedirect函數(shù)確定是否應該遵循重定向。如果允許,301,302或303重定向會導致后續(xù)請求使用HTTP方法GET(如果原始請求是HEAD,則為HEAD),但不包含主體。只要定義了Request.GetBody函數(shù),307或308重定向就會保留原始的HTTP方法和主體。NewRequest函數(shù)自動為通用標準庫體類型設置GetBody。
func (c *Client) Get(url string) (resp *Response, err error)
將問題GET獲取到指定的URL。如果響應是以下重定向代碼之一,則在調用客戶端的CheckRedirect函數(shù)后,Get遵循重定向:
301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)
如果客戶端的CheckRedirect功能失敗或者出現(xiàn)HTTP協(xié)議錯誤,則返回錯誤。非2xx響應不會導致錯誤。
當err為零時,resp總是包含非零的resp.Body。來電者在完成閱讀后應關閉resp.Body。
要使用自定義標題發(fā)出請求,請使用NewRequest和Client.Do。
func (c *Client) Head(url string) (resp *Response, err error)
Head向指定的URL發(fā)出HEAD。如果響應是以下重定向代碼之一,則Head在調用客戶端的CheckRedirect函數(shù)后遵循重定向:
301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)
func (c *Client) Post(url string, contentType string, body io.Reader) (resp *Response, err error)
發(fā)布POST到指定的URL。
調用者在完成閱讀后應關閉resp.Body。
如果提供的主體是io.Closer,則在請求后關閉。
要設置自定義標題,請使用NewRequest和Client.Do。
有關如何處理重定向的詳細信息,請參閱Client.Do方法文檔。
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
PostForm向指定的URL發(fā)布POST,并將數(shù)據(jù)的鍵和值作為請求主體進行URL編碼。
Content-Type頭部設置為application/x-www-form-urlencoded。要設置其他標題,請使用NewRequest和DefaultClient.Do。
當err為零時,resp總是包含非零的resp.Body。調用者在完成閱讀后應關閉resp.Body。
有關如何處理重定向的詳細信息,請參閱Client.Do方法文檔。
CloseNotifier接口由ResponseWriters實現(xiàn),它允許檢測基礎連接何時消失。
如果客戶端在響應準備好之前斷開連接,則可以使用此機制取消服務器上的長時間操作。
type CloseNotifier interface { // CloseNotify returns a channel that receives at most a // single value (true) when the client connection has gone // away. // // CloseNotify may wait to notify until Request.Body has been // fully read. // // After the Handler has returned, there is no guarantee // that the channel receives a value. // // If the protocol is HTTP/1.1 and CloseNotify is called while // processing an idempotent request (such a GET) while // HTTP/1.1 pipelining is in use, the arrival of a subsequent // pipelined request may cause a value to be sent on the // returned channel. In practice HTTP/1.1 pipelining is not // enabled in browsers and not seen often in the wild. If this // is a problem, use HTTP/2 or only use CloseNotify on methods // such as POST. CloseNotify() <-chan bool}
ConnState表示客戶端連接到服務器的狀態(tài)。它由可選的Server.ConnState掛鉤使用。
type ConnState int
const ( // StateNew represents a new connection that is expected to // send a request immediately. Connections begin at this // state and then transition to either StateActive or // StateClosed. StateNew ConnState = iota // StateActive represents a connection that has read 1 or more // bytes of a request. The Server.ConnState hook for // StateActive fires before the request has entered a handler // and doesn't fire again until the request has been // handled. After the request is handled, the state // transitions to StateClosed, StateHijacked, or StateIdle. // For HTTP/2, StateActive fires on the transition from zero // to one active request, and only transitions away once all // active requests are complete. That means that ConnState // cannot be used to do per-request work; ConnState only notes // the overall state of the connection. StateActive // StateIdle represents a connection that has finished // handling a request and is in the keep-alive state, waiting // for a new request. Connections transition from StateIdle // to either StateActive or StateClosed. StateIdle // StateHijacked represents a hijacked connection. // This is a terminal state. It does not transition to StateClosed. StateHijacked // StateClosed represents a closed connection. // This is a terminal state. Hijacked connections do not // transition to StateClosed. StateClosed)
func (c ConnState) String() string
Cookie表示HTTP響應的Set-Cookie頭或HTTP請求的Cookie頭中發(fā)送的HTTP cookie。
type Cookie struct { Name string Value string Path string // optional Domain string // optional Expires time.Time // optional RawExpires string // for reading cookies only // MaxAge=0 means no 'Max-Age' attribute specified. // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' // MaxAge>0 means Max-Age attribute present and given in seconds MaxAge int Secure bool HttpOnly bool Raw string Unparsed []string // Raw text of unparsed attribute-value pairs}
func (c *Cookie) String() string
字符串返回用于Cookie標頭(如果僅設置了Name和Value)或Set-Cookie響應標頭(如果設置了其他字段)的Cookie的序列化。如果c為零或c.Name無效,則返回空字符串。
CookieJar管理HTTP請求中cookie的存儲和使用。
CookieJar的實現(xiàn)必須安全,以供多個goroutine同時使用。
net/http/cookiejar包提供了一個CookieJar實現(xiàn)。
type CookieJar interface { // SetCookies handles the receipt of the cookies in a reply for the // given URL. It may or may not choose to save the cookies, depending // on the jar's policy and implementation. SetCookies(u *url.URL, cookies []*Cookie) // Cookies returns the cookies to send in a request for the given URL. // It is up to the implementation to honor the standard cookie use // restrictions such as in RFC 6265. Cookies(u *url.URL) []*Cookie}
Dir使用限于特定目錄樹的本機文件系統(tǒng)實現(xiàn)FileSystem。
雖然FileSystem.Open方法采用'/' - 分隔的路徑,但Dir的字符串值是本地文件系統(tǒng)上的文件名,而不是URL,因此它由filepath.Separator分隔,而不一定是'/'。
請注意,Dir將允許訪問以句點開頭的文件和目錄,這可能會暴露敏感目錄(如.git目錄)或敏感文件(如.htpasswd)。要排除具有前導期的文件,請從服務器中刪除文件/目錄或創(chuàng)建自定義FileSystem實現(xiàn)。
空的Dir被視為“。”。
type Dir string
func (d Dir) Open(name string) (File, error)
File由FileSystem的Open方法返回,并可由FileServer實現(xiàn)提供。
這些方法的行為應該與* os.File中的方法相同。
type File interface { io.Closer io.Reader io.Seeker Readdir(count int) ([]os.FileInfo, error) Stat() (os.FileInfo, error)}
FileSystem實現(xiàn)對指定文件集合的訪問。無論主機操作系統(tǒng)慣例如何,文件路徑中的元素都用斜線('/', U+002F)字符分隔。
type FileSystem interface { Open(name string) (File, error)}
Flusher接口由ResponseWriters實現(xiàn),它允許HTTP處理器將緩沖數(shù)據(jù)刷新到客戶端。
默認的HTTP/1.x和HTTP/2 ResponseWriter實現(xiàn)支持Flusher,但ResponseWriter包裝可能不支持。處理程序應始終在運行時測試此功能。
請注意,即使對于支持Flush的ResponseWriters,如果客戶端通過HTTP代理連接,緩存的數(shù)據(jù)可能無法到達客戶端,直到響應完成。
type Flusher interface { // Flush sends any buffered data to the client. Flush()}
Handler響應HTTP請求。
ServeHTTP應該將回復頭文件和數(shù)據(jù)寫入ResponseWriter,然后返回。返回請求完成的信號;在完成ServeHTTP調用之后或同時完成使用ResponseWriter或從Request.Body中讀取是無效的。
根據(jù)HTTP客戶端軟件,HTTP協(xié)議版本以及客戶端與Go服務器之間的任何中介,在寫入ResponseWriter后,可能無法從Request.Body中讀取數(shù)據(jù)。謹慎的處理程序應先讀取Request.Body,然后回復。
除閱讀主體外,處理程序不應修改提供的請求。
如果ServeHTTP發(fā)生混亂,則服務器(ServeHTTP的調用者)認為恐慌的影響與活動請求分離。它恢復恐慌,將堆棧跟蹤記錄到服務器錯誤日志中,并根據(jù)HTTP協(xié)議關閉網(wǎng)絡連接或發(fā)送HTTP/2 RST_STREAM。要終止處理程序,以便客戶端看到中斷的響應,但服務器不記錄錯誤,請使用值ErrAbortHandler恐慌。
type Handler interface { ServeHTTP(ResponseWriter, *Request)}
func FileServer(root FileSystem) Handler
FileServer返回一個處理程序,該處理程序為root用戶提供文件系統(tǒng)內(nèi)容的HTTP請求。
要使用操作系統(tǒng)的文件系統(tǒng)實現(xiàn),請使用http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
作為一種特殊情況,返回的文件服務器將以“/index.html”結尾的任何請求重定向到相同的路徑,而沒有最終的“index.html”。
package mainimport ("log""net/http")func main() {// Simple static webserver: log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))}
package mainimport ("net/http")func main() {// To serve a directory on disk (/tmp) under an alternate URL// path (/tmpfiles/), use StripPrefix to modify the request// URL's path before the FileServer sees it: http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))}
func NotFoundHandler() Handler
NotFoundHandler返回一個簡單的請求處理程序,用于處理每個請求的“404頁未找到”答復。
func RedirectHandler(url string, code int) Handler
RedirectHandler返回一個請求處理程序,它使用給定的狀態(tài)碼將其收到的每個請求重定向到給定的url。
提供的代碼應該位于3xx范圍內(nèi),通常是StatusMovedPermanently,StatusFound或StatusSeeOther。
func StripPrefix(prefix string, h Handler) Handler
StripPrefix通過從請求URL的Path中移除給定的前綴并調用處理程序h來返回一個處理程序,該處理程序提供HTTP請求。StripPrefix通過回答HTTP 404找不到錯誤來處理對不以前綴開頭的路徑的請求。
package mainimport ("net/http")func main() {// To serve a directory on disk (/tmp) under an alternate URL// path (/tmpfiles/), use StripPrefix to modify the request// URL's path before the FileServer sees it: http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))}
func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
TimeoutHandler返回一個處理器,它在給定的時間限制內(nèi)運行h。
新的Handler調用h.ServeHTTP來處理每個請求,但是如果一個調用的運行時間超過其時間限制,處理程序會響應503服務不可用錯誤和其正文中的給定消息。(如果msg為空,將發(fā)送一個合適的默認消息。)在這樣的超時之后,h寫入其ResponseWriter將返回ErrHandlerTimeout。
TimeoutHandler將所有Handler緩沖區(qū)寫入內(nèi)存,并且不支持Hijacker或Flusher接口。
HandlerFunc類型是一個適配器,允許使用普通函數(shù)作為HTTP處理程序。如果f是具有適當簽名的函數(shù),則HandlerFunc(f)是調用f的Handler。
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
ServeHTTP calls f(w, r).
標題表示HTTP標題中的鍵值對。
type Header map[string][]string
func (h Header) Add(key, value string)
添加將關鍵字值對添加到標題。它附加到與鍵相關的任何現(xiàn)有值。
func (h Header) Del(key string)
Del刪除與鍵關聯(lián)的值。
func (h Header) Get(key string) string
獲取與給定鍵相關的第一個值。它不區(qū)分大小寫; textproto.CanonicalMIMEHeaderKey用于規(guī)范提供的密鑰。如果沒有與該鍵關聯(lián)的值,Get返回“”。要訪問密鑰的多個值或使用非規(guī)范密鑰,請直接訪問地圖。
func (h Header) Set(key, value string)
Set將與鍵關聯(lián)的標題條目設置為單個元素值。它取代了任何與鍵相關的現(xiàn)有值。
func (h Header) Write(w io.Writer) error
Write以格式寫入標題。
func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error
WriteSubset以連線格式寫入標題。如果exclude不為零,則不會寫入excludekey == true的鍵。
Hijacker接口由ResponseWriters實現(xiàn),它允許HTTP處理程序接管連接。
HTTP/1.x連接的默認ResponseWriter支持劫持程序,但HTTP/2連接故意不支持。ResponseWriter包裝器也可能不支持劫持程序。處理程序應始終在運行時測試此功能。
type Hijacker interface { // Hijack lets the caller take over the connection. // After a call to Hijack the HTTP server library // will not do anything else with the connection. // // It becomes the caller's responsibility to manage // and close the connection. // // The returned net.Conn may have read or write deadlines // already set, depending on the configuration of the // Server. It is the caller's responsibility to set // or clear those deadlines as needed. // // The returned bufio.Reader may contain unprocessed buffered // data from the client. // // After a call to Hijack, the original Request.Body should // not be used. Hijack() (net.Conn, *bufio.ReadWriter, error)}
package mainimport ("fmt""log""net/http")func main() { http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) { hj, ok := w.(http.Hijacker)if !ok { http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)return} conn, bufrw, err := hj.Hijack()if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError)return}// Don't forget to close the connection: defer conn.Close() bufrw.WriteString("Now we're speaking raw TCP. Say hi: ") bufrw.Flush() s, err := bufrw.ReadString('\n')if err != nil { log.Printf("error reading string: %v", err)return} fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s) bufrw.Flush()})}
ProtocolError表示HTTP協(xié)議錯誤。
Deprecated:并非與協(xié)議錯誤有關的http包中的所有錯誤都是ProtocolError 類型。
type ProtocolError struct { ErrorString string}
func (pe *ProtocolError) Error() string
PushOptions描述了Pusher.Push的選項。
type PushOptions struct { // Method specifies the HTTP method for the promised request. // If set, it must be "GET" or "HEAD". Empty means "GET". Method string // Header specifies additional promised request headers. This cannot // include HTTP/2 pseudo header fields like ":path" and ":scheme", // which will be added automatically. Header Header}
Pusher是ResponseWriters實現(xiàn)的接口,支持HTTP/2服務器推送。
type Pusher interface { // Push initiates an HTTP/2 server push. This constructs a synthetic // request using the given target and options, serializes that request // into a PUSH_PROMISE frame, then dispatches that request using the // server's request handler. If opts is nil, default options are used. // // The target must either be an absolute path (like "/path") or an absolute // URL that contains a valid host and the same scheme as the parent request. // If the target is a path, it will inherit the scheme and host of the // parent request. // // The HTTP/2 spec disallows recursive pushes and cross-authority pushes. // Push may or may not detect these invalid pushes; however, invalid // pushes will be detected and canceled by conforming clients. // // Handlers that wish to push URL X should call Push before sending any // data that may trigger a request for URL X. This avoids a race where the // client issues requests for X before receiving the PUSH_PROMISE for X. // // Push returns ErrNotSupported if the client has disabled push or if push // is not supported on the underlying connection. Push(target string, opts *PushOptions) error}
請求表示由服務器接收或由客戶端發(fā)送的HTTP請求。
客戶端和服務器使用情況的字段語義略有不同。除了下面字段的注釋之外,請參閱Request.Write和RoundTripper的文檔。
type Request struct { // Method specifies the HTTP method (GET, POST, PUT, etc.). // For client requests an empty string means GET. Method string // URL specifies either the URI being requested (for server // requests) or the URL to access (for client requests). // // For server requests the URL is parsed from the URI // supplied on the Request-Line as stored in RequestURI. For // most requests, fields other than Path and RawQuery will be // empty. (See RFC 2616, Section 5.1.2) // // For client requests, the URL's Host specifies the server to // connect to, while the Request's Host field optionally // specifies the Host header value to send in the HTTP // request. URL *url.URL // The protocol version for incoming server requests. // // For client requests these fields are ignored. The HTTP // client code always uses either HTTP/1.1 or HTTP/2. // See the docs on Transport for details. Proto string // "HTTP/1.0" ProtoMajor int // 1 ProtoMinor int // 0 // Header contains the request header fields either received // by the server or to be sent by the client. // // If a server received a request with header lines, // // Host: example.com // accept-encoding: gzip, deflate // Accept-Language: en-us // fOO: Bar // foo: two // // then // // Header = map[string][]string{ // "Accept-Encoding": {"gzip, deflate"}, // "Accept-Language": {"en-us"}, // "Foo": {"Bar", "two"}, // } // // For incoming requests, the Host header is promoted to the // Request.Host field and removed from the Header map. // // HTTP defines that header names are case-insensitive. The // request parser implements this by using CanonicalHeaderKey, // making the first character and any characters following a // hyphen uppercase and the rest lowercase. // // For client requests, certain headers such as Content-Length // and Connection are automatically written when needed and // values in Header may be ignored. See the documentation // for the Request.Write method. Header Header // Body is the request's body. // // For client requests a nil body means the request has no // body, such as a GET request. The HTTP Client's Transport // is responsible for calling the Close method. // // For server requests the Request Body is always non-nil // but will return EOF immediately when no body is present. // The Server will close the request body. The ServeHTTP // Handler does not need to. Body io.ReadCloser // GetBody defines an optional func to return a new copy of // Body. It is used for client requests when a redirect requires // reading the body more than once. Use of GetBody still // requires setting Body. // // For server requests it is unused. GetBody func() (io.ReadCloser, error) // ContentLength records the length of the associated content. // The value -1 indicates that the length is unknown. // Values >= 0 indicate that the given number of bytes may // be read from Body. // For client requests, a value of 0 with a non-nil Body is // also treated as unknown. ContentLength int64 // TransferEncoding lists the transfer encodings from outermost to // innermost. An empty list denotes the "identity" encoding. // TransferEncoding can usually be ignored; chunked encoding is // automatically added and removed as necessary when sending and // receiving requests. TransferEncoding []string // Close indicates whether to close the connection after // replying to this request (for servers) or after sending this // request and reading its response (for clients). // // For server requests, the HTTP server handles this automatically // and this field is not needed by Handlers. // // For client requests, setting this field prevents re-use of // TCP connections between requests to the same hosts, as if // Transport.DisableKeepAlives were set. Close bool // For server requests Host specifies the host on which the // URL is sought. Per RFC 2616, this is either the value of // the "Host" header or the host name given in the URL itself. // It may be of the form "host:port". For international domain // names, Host may be in Punycode or Unicode form. Use // golang.org/x/net/idna to convert it to either format if // needed. // // For client requests Host optionally overrides the Host // header to send. If empty, the Request.Write method uses // the value of URL.Host. Host may contain an international // domain name. Host string // Form contains the parsed form data, including both the URL // field's query parameters and the POST or PUT form data. // This field is only available after ParseForm is called. // The HTTP client ignores Form and uses Body instead. Form url.Values // PostForm contains the parsed form data from POST, PATCH, // or PUT body parameters. // // This field is only available after ParseForm is called. // The HTTP client ignores PostForm and uses Body instead. PostForm url.Values // MultipartForm is the parsed multipart form, including file uploads. // This field is only available after ParseMultipartForm is called. // The HTTP client ignores MultipartForm and uses Body instead. MultipartForm *multipart.Form // Trailer specifies additional headers that are sent after the request // body. // // For server requests the Trailer map initially contains only the // trailer keys, with nil values. (The client declares which trailers it // will later send.) While the handler is reading from Body, it must // not reference Trailer. After reading from Body returns EOF, Trailer // can be read again and will contain non-nil values, if they were sent // by the client. // // For client requests Trailer must be initialized to a map containing // the trailer keys to later send. The values may be nil or their final // values. The ContentLength must be 0 or -1, to send a chunked request. // After the HTTP request is sent the map values can be updated while // the request body is read. Once the body returns EOF, the caller must // not mutate Trailer. // // Few HTTP clients, servers, or proxies support HTTP trailers. Trailer Header // RemoteAddr allows HTTP servers and other software to record // the network address that sent the request, usually for // logging. This field is not filled in by ReadRequest and // has no defined format. The HTTP server in this package // sets RemoteAddr to an "IP:port" address before invoking a // handler. // This field is ignored by the HTTP client. RemoteAddr string // RequestURI is the unmodified Request-URI of the // Request-Line (RFC 2616, Section 5.1) as sent by the client // to a server. Usually the URL field should be used instead. // It is an error to set this field in an HTTP client request. RequestURI string // TLS allows HTTP servers and other software to record // information about the TLS connection on which the request // was received. This field is not filled in by ReadRequest. // The HTTP server in this package sets the field for // TLS-enabled connections before invoking a handler; // otherwise it leaves the field nil. // This field is ignored by the HTTP client. TLS *tls.ConnectionState // Cancel is an optional channel whose closure indicates that the client // request should be regarded as canceled. Not all implementations of // RoundTripper may support Cancel. // // For server requests, this field is not applicable. // // Deprecated: Use the Context and WithContext methods // instead. If a Request's Cancel field and context are both // set, it is undefined whether Cancel is respected. Cancel <-chan struct{} // Response is the redirect response which caused this request // to be created. This field is only populated during client // redirects. Response *Response // contains filtered or unexported fields}
func NewRequest(method, url string, body io.Reader) (*Request, error)
NewRequest返回給定方法,URL和可選主體的新請求。
如果提供的主體也是io.Closer,則返回的Request.Body將設置為body,并且將由客戶端方法Do,Post和PostForm以及Transport.RoundTrip關閉。
NewRequest返回適用于Client.Do或Transport.RoundTrip的請求。要創(chuàng)建與測試服務器處理程序一起使用的請求,請使用net/http/httptest軟件包中的NewRequest函數(shù),使用ReadRequest或手動更新請求字段。有關入站和出站請求字段之間的差異,請參閱請求類型的文檔。
如果body是* bytes.Buffer,* bytes.Reader或* strings.Reader類型,則返回的請求的ContentLength被設置為它的精確值(而不是-1),GetBody被填充(所以307和308重定向可以重放body),如果ContentLength為0,則Body設置為NoBody。
func ReadRequest(b *bufio.Reader) (*Request, error)
ReadRequest讀取并解析來自b的傳入請求。
func (r *Request) AddCookie(c *Cookie)
AddCookie向請求添加一個cookie。根據(jù)RFC 6265第5.4節(jié)的規(guī)定,AddCookie不會附加多個Cookie標題字段。這意味著所有的cookies(如果有的話)被寫入同一行,并以分號分隔。
func (r *Request) BasicAuth() (username, password string, ok bool)
如果請求使用HTTP基本認證,BasicAuth將返回請求的授權標頭中提供的用戶名和密碼。請參閱RFC 2617,第2部分。
func (r *Request) Context() context.Context
上下文返回請求的上下文。要更改上下文,請使用WithContext。
返回的上下文總是非零;它默認為后臺上下文。
對于傳出的客戶端請求,上下文控制取消。
對于傳入的服務器請求,當客戶端連接關閉,取消請求(使用HTTP/2)或ServeHTTP方法返回時,上下文將被取消。
func (r *Request) Cookie(name string) (*Cookie, error)
Cookie返回請求中提供的命名cookie或ErrNoCookie,如果未找到。如果多個cookie匹配給定名稱,則只會返回一個cookie。
func (r *Request) Cookies() []*Cookie
Cookies解析并返回隨請求發(fā)送的HTTP Cookie。
func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
FormFile返回提供的表單鍵的第一個文件。如有必要,F(xiàn)ormFile調用ParseMultipartForm和ParseForm。
func (r *Request) FormValue(key string) string
FormValue返回查詢命名組件的第一個值。POST和PUT正文參數(shù)優(yōu)先于URL查詢字符串值。如有必要,F(xiàn)ormValue調用ParseMultipartForm和ParseForm,并忽略這些函數(shù)返回的任何錯誤。如果鍵不存在,F(xiàn)ormValue返回空字符串。要訪問同一個鍵的多個值,請調用ParseForm,然后直接檢查Request.Form。
func (r *Request) MultipartReader() (*multipart.Reader, error)
如果這是multipart/form-data POST請求,則MultipartReader會返回MIME多部分閱讀器,否則返回nil并顯示錯誤。使用此函數(shù)而不是ParseMultipartForm將請求主體作為流處理。
func (r *Request) ParseForm() error
ParseForm填充r.Form和r.PostForm。
對于所有請求,ParseForm解析來自URL的原始查詢并更新r.Form。
對于POST,PUT和PATCH請求,它還將請求主體解析為表單并將結果放入r.PostForm和r.Form中。請求主體參數(shù)優(yōu)先于r.Form中的URL查詢字符串值。
對于其他HTTP方法,或者當Content-Type不是application/x-www-form-urlencoded時,請求體不會被讀取,并且r.PostForm被初始化為非零空值。
如果請求體的大小尚未被MaxBytesReader限制,則大小限制為10MB。
ParseMultipartForm自動調用ParseForm。ParseForm是冪等的。
func (r *Request) ParseMultipartForm(maxMemory int64) error
ParseMultipartForm將請求主體解析為multipart/form-data。對整個請求體進行解析,并將其文件部分的總共maxMemory字節(jié)存儲在內(nèi)存中,其余部分存儲在磁盤中的臨時文件中。如有必要,ParseMultipartForm會調用ParseForm。在一次調用ParseMultipartForm后,后續(xù)調用不起作用。
func (r *Request) PostFormValue(key string) string
PostFormValue返回POST或PUT請求主體的命名組件的第一個值。網(wǎng)址查詢參數(shù)被忽略。如有必要,PostFormValue調用ParseMultipartForm和ParseForm,并忽略這些函數(shù)返回的任何錯誤。如果鍵不存在,PostFormValue返回空字符串。
func (r *Request) ProtoAtLeast(major, minor int) bool
ProtoAtLeast報告請求中使用的HTTP協(xié)議是否至少major.minor。
func (r *Request) Referer() string
如果在請求中發(fā)送,Referer返回引用URL。
引用者在請求本身中拼寫錯誤,這是HTTP早期的錯誤。這個值也可以從Header映射中作為Header“Referer”獲取; 將其作為一種方法提供的好處是,編譯器可以診斷使用備用(正確的英文)拼寫req.Referrer()的程序,但無法診斷使用Header“Referrer”的程序。
func (r *Request) SetBasicAuth(username, password string)
SetBasicAuth將請求的授權標頭設置為使用帶有所提供的用戶名和密碼的HTTP基本認證。
使用HTTP基本身份驗證時,提供的用戶名和密碼未加密。
func (r *Request) UserAgent() string
如果在請求中發(fā)送,UserAgent會返回客戶端的用戶代理。
func (r *Request) WithContext(ctx context.Context) *Request
WithContext返回r的淺表副本,其上下文已更改為ctx。提供的ctx必須是非零。
func (r *Request) Write(w io.Writer) error
寫入有線格式的HTTP/1.1請求,這是標頭和正文。該方法會查詢請求的以下字段:
Host URLMethod (defaults to "GET")Header ContentLength TransferEncoding Body
如果Body存在,則Content-Length <= 0且TransferEncoding尚未設置為“identity”,Write將“Transfer-Encoding: chunked”添加到標頭。身體在發(fā)送后關閉。
func (r *Request) WriteProxy(w io.Writer) error
WriteProxy就像Write,但以HTTP代理的預期形式寫入請求。特別是,WriteProxy按照RFC 2616的5.1.2節(jié)(包括方案和主機)以絕對URI寫入請求的初始Request-URI行。無論哪種情況,WriteProxy還會使用r.Host或r.URL.Host寫入一個主機頭。
響應表示來自HTTP請求的響應。
type Response struct { Status string // e.g. "200 OK" StatusCode int // e.g. 200 Proto string // e.g. "HTTP/1.0" ProtoMajor int // e.g. 1 ProtoMinor int // e.g. 0 // Header maps header keys to values. If the response had multiple // headers with the same key, they may be concatenated, with comma // delimiters. (Section 4.2 of RFC 2616 requires that multiple headers // be semantically equivalent to a comma-delimited sequence.) When // Header values are duplicated by other fields in this struct (e.g., // ContentLength, TransferEncoding, Trailer), the field values are // authoritative. // // Keys in the map are canonicalized (see CanonicalHeaderKey). Header Header // Body represents the response body. // // The http Client and Transport guarantee that Body is always // non-nil, even on responses without a body or responses with // a zero-length body. It is the caller's responsibility to // close Body. The default HTTP client's Transport does not // attempt to reuse HTTP/1.0 or HTTP/1.1 TCP connections // ("keep-alive") unless the Body is read to completion and is // closed. // // The Body is automatically dechunked if the server replied // with a "chunked" Transfer-Encoding. Body io.ReadCloser // ContentLength records the length of the associated content. The // value -1 indicates that the length is unknown. Unless Request.Method // is "HEAD", values >= 0 indicate that the given number of bytes may // be read from Body. ContentLength int64 // Contains transfer encodings from outer-most to inner-most. Value is // nil, means that "identity" encoding is used. TransferEncoding []string // Close records whether the header directed that the connection be // closed after reading Body. The value is advice for clients: neither // ReadResponse nor Response.Write ever closes a connection. Close bool // Uncompressed reports whether the response was sent compressed but // was decompressed by the http package. When true, reading from // Body yields the uncompressed content instead of the compressed // content actually set from the server, ContentLength is set to -1, // and the "Content-Length" and "Content-Encoding" fields are deleted // from the responseHeader. To get the original response from // the server, set Transport.DisableCompression to true. Uncompressed bool // Trailer maps trailer keys to values in the same // format as Header. // // The Trailer initially contains only nil values, one for // each key specified in the server's "Trailer" header // value. Those values are not added to Header. // // Trailer must not be accessed concurrently with Read calls // on the Body. // // After Body.Read has returned io.EOF, Trailer will contain // any trailer values sent by the server. Trailer Header // Request is the request that was sent to obtain this Response. // Request's Body is nil (having already been consumed). // This is only populated for Client requests. Request *Request // TLS contains information about the TLS connection on which the // response was received. It is nil for unencrypted responses. // The pointer is shared between responses and should not be // modified. TLS *tls.ConnectionState}
func Get(url string) (resp *Response, err error)
將問題GET獲取到指定的URL。如果響應是以下重定向代碼之一,則Get遵循重定向,最多可重定向10次:
301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)
如果重定向太多或出現(xiàn)HTTP協(xié)議錯誤,則會返回錯誤。非2xx響應不會導致錯誤。
當err為零時,resp總是包含非零的resp.Body。來電者在完成閱讀后應關閉resp.Body。
Get是一個DefaultClient.Get的包裝器。
要使用自定義標題發(fā)出請求,請使用NewRequest和DefaultClient.Do。
package mainimport ("fmt""io/ioutil""log""net/http")func main() { res, err := http.Get("http://www.google.com/robots.txt")if err != nil { log.Fatal(err)} robots, err := ioutil.ReadAll(res.Body) res.Body.Close()if err != nil { log.Fatal(err)} fmt.Printf("%s", robots)}
func Head(url string) (resp *Response, err error)
Head向指定的URL發(fā)出HEAD。如果響應是以下重定向代碼之一,Head會遵循重定向,最多可重定向10次:
301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)
Head是DefaultClient.Head的包裝
func Post(url string, contentType string, body io.Reader) (resp *Response, err error)
發(fā)布POST到指定的URL。
調用者在完成閱讀后應關閉resp.Body。
如果提供的主體是io.Closer,則在請求后關閉。
Post是DefaultClient.Post的一個包裝。
要設置自定義標題,請使用NewRequest和DefaultClient.Do。
有關如何處理重定向的詳細信息,請參閱Client.Do方法文檔。
func PostForm(url string, data url.Values) (resp *Response, err error)
PostForm向指定的URL發(fā)布POST,并將數(shù)據(jù)的鍵和值作為請求主體進行URL編碼。
Content-Type頭部設置為application/x-www-form-urlencoded。要設置其他標題,請使用NewRequest和DefaultClient.Do。
當err為零時,resp總是包含非零的resp.Body。調用者在完成閱讀后應關閉resp.Body。
PostForm是DefaultClient.PostForm的封裝。
有關如何處理重定向的詳細信息,請參閱Client.Do方法文檔。
func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
ReadResponse讀取并返回來自r的HTTP響應。req參數(shù)可選地指定對應于此響應的請求。如果為零,則假定有GET請求。讀完resp.Body后,客戶必須調用resp.Body.Close。通話結束后,客戶可以檢查resp.Trailer以查找響應預告片中包含的key/value pairs。
func (r *Response) Cookies() []*Cookie
Cookies分析并返回Set-Cookie標題中設置的Cookie。
func (r *Response) Location() (*url.URL, error)
位置返回響應的“位置”標題的URL(如果存在)。相對重定向相對于響應的請求被解析。如果不存在位置標題,則返回ErrNoLocation。
func (r *Response) ProtoAtLeast(major, minor int) bool
ProtoAtLeast報告響應中使用的HTTP協(xié)議是否至少是major.minor。
func (r *Response) Write(w io.Writer) error
Write r以HTTP/1.x服務器響應格式寫入w,包括狀態(tài)行,標題,正文和可選的trailer。
該方法參考響應r的以下字段:
StatusCode ProtoMajor ProtoMinor Request.Method TransferEncoding Trailer Body ContentLength Header, values for non-canonical keys will have unpredictable behavior
響應主體在發(fā)送后關閉。
HTTP處理程序使用ResponseWriter接口來構造HTTP響應。
在Handler.ServeHTTP方法返回后,可能不會使用ResponseWriter。
type ResponseWriter interface { // Header returns the header map that will be sent by // WriteHeader. The Header map also is the mechanism with which // Handlers can set HTTP trailers. // // Changing the header map after a call to WriteHeader (or // Write) has no effect unless the modified headers are // trailers. // // There are two ways to set Trailers. The preferred way is to // predeclare in the headers which trailers you will later // send by setting the "Trailer" header to the names of the // trailer keys which will come later. In this case, those // keys of the Header map are treated as if they were // trailers. See the example. The second way, for trailer // keys not known to the Handler until after the first Write, // is to prefix the Header map keys with the TrailerPrefix // constant value. See TrailerPrefix. // // To suppress implicit response headers (such as "Date"), set // their value to nil. Header() Header // Write writes the data to the connection as part of an HTTP reply. // // If WriteHeader has not yet been called, Write calls // WriteHeader(http.StatusOK) before writing the data. If the Header // does not contain a Content-Type line, Write adds a Content-Type set // to the result of passing the initial 512 bytes of written data to // DetectContentType. // // Depending on the HTTP protocol version and the client, calling // Write or WriteHeader may prevent future reads on the // Request.Body. For HTTP/1.x requests, handlers should read any // needed request body data before writing the response. Once the // headers have been flushed (due to either an explicit Flusher.Flush // call or writing enough data to trigger a flush), the request body // may be unavailable. For HTTP/2 requests, the Go HTTP server permits // handlers to continue to read the request body while concurrently // writing the response. However, such behavior may not be supported // by all HTTP/2 clients. Handlers should read before writing if // possible to maximize compatibility. Write([]byte) (int, error) // WriteHeader sends an HTTP response header with status code. // If WriteHeader is not called explicitly, the first call to Write // will trigger an implicit WriteHeader(http.StatusOK). // Thus explicit calls to WriteHeader are mainly used to // send error codes. WriteHeader(int)}
HTTP Trailers是一組key/value pairs,如HTTP響應之后的headers,而不是之前。
package mainimport ("io""net/http")func main() { mux := http.NewServeMux() mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {// Before any call to WriteHeader or Write, declare// the trailers you will set during the HTTP// response. These three headers are actually sent in// the trailer. w.Header().Set("Trailer", "AtEnd1, AtEnd2") w.Header().Add("Trailer", "AtEnd3") w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header w.WriteHeader(http.StatusOK) w.Header().Set("AtEnd1", "value 1") io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n") w.Header().Set("AtEnd2", "value 2") w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.})}
RoundTripper是一個接口,表示執(zhí)行單個HTTP事務的能力,獲得給定請求的響應。
RoundTripper必須是安全的,以供多個goroutine同時使用。
type RoundTripper interface { // RoundTrip executes a single HTTP transaction, returning // a Response for the provided Request. // // RoundTrip should not attempt to interpret the response. In // particular, RoundTrip must return err == nil if it obtained // a response, regardless of the response's HTTP status code. // A non-nil err should be reserved for failure to obtain a // response. Similarly, RoundTrip should not attempt to // handle higher-level protocol details such as redirects, // authentication, or cookies. // // RoundTrip should not modify the request, except for // consuming and closing the Request's Body. // // RoundTrip must always close the body, including on errors, // but depending on the implementation may do so in a separate // goroutine even after RoundTrip returns. This means that // callers wanting to reuse the body for subsequent requests // must arrange to wait for the Close call before doing so. // // The Request's URL and Header fields must be initialized. RoundTrip(*Request) (*Response, error)}
DefaultTransport是Transport的默認實現(xiàn),由DefaultClient使用。它根據(jù)需要建立網(wǎng)絡連接,并將它們緩存以供隨后的調用重用。它按照$ HTTP_PROXY和$ NO_PROXY(或$ http_proxy和$ no_proxy)環(huán)境變量的指示使用HTTP代理。
var DefaultTransport RoundTripper = &Transport{ Proxy: ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second,}
func NewFileTransport(fs FileSystem) RoundTripper
NewFileTransport返回一個新的RoundTripper,為所提供的FileSystem提供服務。返回的RoundTripper會忽略其傳入請求中的URL主機以及請求的大多數(shù)其他屬性。
NewFileTransport的典型用例是使用Transport注冊“文件”協(xié)議,如下所示:
t := &http.Transport{}t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))c := &http.Client{Transport: t}res, err := c.Get("file:///etc/passwd")...
ServeMux是一個HTTP請求多路復用器。它將每個傳入請求的URL與注冊模式列表進行匹配,并調用與該URL最匹配的模式的處理程序。
模式命名固定的,根源化的路徑,如“/favicon.ico”,或根源子樹,如“/images/”(注意尾部斜線)。較長的模式優(yōu)先于較短的模式,因此,如果有處理程序注冊了“/images/”和“/images / thumbnails/”,后一個處理程序將被調用以“/images/thumbnails/”開頭的路徑,前者將接收“/images/”子樹中任何其他路徑的請求。
請注意,由于以斜杠結尾的模式命名了一個有根的子樹,因此模式“/”會匹配所有未被其他已注冊模式匹配的路徑,而不僅僅是具有Path ==“/”的URL。
如果一個子樹已經(jīng)注冊并且接收到一個請求,并且命名了子樹根而沒有結尾的斜杠,ServeMux會將該請求重定向到子樹根(添加尾部斜線)。此行為可以通過單獨注冊路徑而不使用結尾斜杠來覆蓋。例如,注冊“/images/”會導致ServeMux將“/images”的請求重定向到“/images/”,除非單獨注冊了“/images”。
模式可以有選擇地以主機名開頭,只限制與主機上的URL匹配。特定于主機的模式優(yōu)先于一般模式,因此處理程序可能會注冊兩種模式“/codesearch”和“codesearch.google.com/”,而不會接管“ http://www.google.com/”的請求”。
ServeMux還負責清理URL請求路徑,重定向任何包含的請求。或..元素或重復的斜杠到一個等效的,更干凈的URL。
type ServeMux struct { // contains filtered or unexported fields}
func NewServeMux() *ServeMux
NewServeMux分配并返回一個新的ServeMux。
func (mux *ServeMux) Handle(pattern string, handler Handler)
Handle為給定模式注冊處理程序。如果處理程序已經(jīng)存在模式,則處理恐慌。
代碼:
mux := http.NewServeMux()mux.Handle("/api/", apiHandler{})mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { // The "/" pattern matches everything, so we need to check // that we're at the root here. if req.URL.Path != "/" { http.NotFound(w, req) return } fmt.Fprintf(w, "Welcome to the home page!")})
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
HandleFunc為給定模式注冊處理函數(shù)。
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
Handler返回用于給定請求的處理程序,請參閱r.Method,r.Host和r.URL.Path。它總是返回一個非零處理程序。如果路徑不是其規(guī)范形式,則處理程序將是一個內(nèi)部生成的處理程序,該處理程序將重定向到規(guī)范路徑。如果主機包含端口,則在匹配處理程序時將忽略該端口。
CONNECT請求的路徑和主機未改變。
處理程序還返回匹配請求的注冊模式,或者在內(nèi)部生成的重定向的情況下,返回跟隨重定向后匹配的模式。
如果沒有適用于請求的注冊處理程序,則Handler返回“未找到頁面”處理程序和空白模式。
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
ServeHTTP將請求分派給其模式與請求URL最匹配的處理程序。
服務器定義運行HTTP服務器的參數(shù)。服務器的零值是有效的配置。
type Server struct { Addr string // TCP address to listen on, ":http" if empty Handler Handler // handler to invoke, http.DefaultServeMux if nil TLSConfig *tls.Config // optional TLS config, used by ServeTLS and ListenAndServeTLS // ReadTimeout is the maximum duration for reading the entire // request, including the body. // // Because ReadTimeout does not let Handlers make per-request // decisions on each request body's acceptable deadline or // upload rate, most users will prefer to use // ReadHeaderTimeout. It is valid to use them both. ReadTimeout time.Duration // ReadHeaderTimeout is the amount of time allowed to read // request headers. The connection's read deadline is reset // after reading the headers and the Handler can decide what // is considered too slow for the body. ReadHeaderTimeout time.Duration // WriteTimeout is the maximum duration before timing out // writes of the response. It is reset whenever a new // request's header is read. Like ReadTimeout, it does not // let Handlers make decisions on a per-request basis. WriteTimeout time.Duration // IdleTimeout is the maximum amount of time to wait for the // next request when keep-alives are enabled. If IdleTimeout // is zero, the value of ReadTimeout is used. If both are // zero, ReadHeaderTimeout is used. IdleTimeout time.Duration // MaxHeaderBytes controls the maximum number of bytes the // server will read parsing the request header's keys and // values, including the request line. It does not limit the // size of the request body. // If zero, DefaultMaxHeaderBytes is used. MaxHeaderBytes int // TLSNextProto optionally specifies a function to take over // ownership of the provided TLS connection when an NPN/ALPN // protocol upgrade has occurred. The map key is the protocol // name negotiated. The Handler argument should be used to // handle HTTP requests and will initialize the Request's TLS // and RemoteAddr if not already set. The connection is // automatically closed when the function returns. // If TLSNextProto is not nil, HTTP/2 support is not enabled // automatically. TLSNextProto map[string]func(*Server, *tls.Conn, Handler) // ConnState specifies an optional callback function that is // called when a client connection changes state. See the // ConnState type and associated constants for details. ConnState func(net.Conn, ConnState) // ErrorLog specifies an optional logger for errors accepting // connections and unexpected behavior from handlers. // If nil, logging goes to os.Stderr via the log package's // standard logger. ErrorLog *log.Logger // contains filtered or unexported fields}
func (srv *Server) Close() error
立即關閉關閉狀態(tài)StateNew,StateActive或StateIdle中的所有活動net.Listeners和任何連接。要正常關機,請使用關機。
關閉不會嘗試關閉(甚至不知道)任何被劫持的連接,例如WebSockets。
Close返回關閉服務器底層偵聽器返回的任何錯誤。
func (srv *Server) ListenAndServe() error
ListenAndServe監(jiān)聽TCP網(wǎng)絡地址srv.Addr,然后調用Serve處理傳入連接上的請求。接受的連接被配置為啟用TCP保持活動。如果srv.Addr為空,則使用“:http”。ListenAndServe總是返回一個非零錯誤。
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
ListenAndServeTLS偵聽TCP網(wǎng)絡地址srv.Addr,然后調用Serve處理傳入TLS連接上的請求。接受的連接被配置為啟用TCP保持活動。
如果服務器的TLSConfig.Certificates和TLSConfig.GetCertificate都不填充,則必須提供包含服務器的證書和匹配私鑰的文件名。如果證書由證書頒發(fā)機構簽署,則certFile應該是服務器證書,任何中間器和CA證書的串聯(lián)。
如果srv.Addr為空,則使用“:https”。
ListenAndServeTLS總是返回一個非零錯誤。
func (srv *Server) RegisterOnShutdown(f func())
RegisterOnShutdown注冊一個函數(shù)來調用Shutdown。這可以用于正常關閉經(jīng)過NPN/ALPN協(xié)議升級或已被劫持的連接。此功能應啟動特定于協(xié)議的正常關機,但不應等待關機完成。
func (srv *Server) Serve(l net.Listener) error
Serve接受Listener l上的傳入連接,為每個服務器創(chuàng)建一個新的服務程序。服務程序讀取請求,然后調用srv.Handler來回復它們。
對于HTTP/2支持,在調用Serve之前,應將srv.TLSConfig初始化為提供的偵聽器的TLS配置。如果srv.TLSConfig非零,并且在Config.NextProtos中不包含字符串“h2”,則不啟用HTTP/2支持。
始終返回非零錯誤。關機或關閉后,返回的錯誤是ErrServerClosed。
func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
ServeTLS接受Listener l上的傳入連接,為每個連接創(chuàng)建一個新的服務例程。服務程序讀取請求,然后調用srv.Handler來回復它們。
此外,如果服務器的TLSConfig.Certificates和TLSConfig.GetCertificate都未被填充,則必須提供包含服務器的證書和匹配私鑰的文件。如果證書由證書頒發(fā)機構簽署,則certFile應該是服務器的串聯(lián)證書,任何中間件和CA的證書。
對于HTTP/2支持,在調用Serve之前,應將srv.TLSConfig初始化為提供的偵聽器的TLS配置。如果srv.TLSConfig非零,并且在Config.NextProtos中不包含字符串“h2”,則不啟用HTTP/2支持。
ServeTLS總是返回一個非零錯誤。關機或關閉后,返回的錯誤是ErrServerClosed。
func (srv *Server) SetKeepAlivesEnabled(v bool)
SetKeepAlivesEnabled控制是否啟用HTTP保持活動。默認情況下,保持活動狀態(tài)始終處于啟用狀態(tài)。在關閉過程中,只有非常資源受限的環(huán)境或服務器才能禁用它們。
func (srv *Server) Shutdown(ctx context.Context) error
關機正常關閉服務器而不中斷任何活動連接。首先關閉所有打開的監(jiān)聽程序,然后關閉所有空閑連接,然后無限期地等待連接返回到空閑狀態(tài)然后關閉。如果提供的上下文在關閉完成之前到期,Shutdown將返回上下文的錯誤,否則返回關閉服務器的底層偵聽器返回的任何錯誤。
當調用Shutdown時,Serve,ListenAndServe和ListenAndServeTLS立即返回ErrServerClosed。確保程序不會退出,而是等待Shutdown返回。
關機不會嘗試關閉或等待被劫持的連接,如WebSockets。如果需要,Shutdown的調用者應該分別通知關閉的這種長期連接并等待它們關閉。
Transport是RoundTripper的一個實現(xiàn),它支持HTTP,HTTPS和HTTP代理(對于使用CONNECT的HTTP或HTTPS)。
默認情況下,傳輸緩存連接以供將來重新使用。訪問多臺主機時可能會留下許多開放連接??梢允褂脗鬏?shù)腃loseIdleConnections方法和MaxIdleConnsPerHost和DisableKeepAlives字段管理此行為。
運輸應該重用,而不是根據(jù)需要創(chuàng)建。運輸對于多個goroutines并發(fā)使用是安全的。
傳輸是用于發(fā)出HTTP和HTTPS請求的低級原語。對于高級功能(如Cookie和重定向),請參閱客戶端。
Transport對于HTTP URL使用HTTP/1.1,對于HTTPS URL使用HTTP/1.1或HTTP/2,具體取決于服務器是否支持HTTP/2以及如何配置Transport。DefaultTransport支持HTTP/2。要在傳輸上明確啟用HTTP/2,請使用golang.org/x/net/http2并調用ConfigureTransport。有關HTTP/2的更多信息,請參閱軟件包文檔。
type Transport struct { // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // // The proxy type is determined by the URL scheme. "http" // and "socks5" are supported. If the scheme is empty, // "http" is assumed. // // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*Request) (*url.URL, error) // DialContext specifies the dial function for creating unencrypted TCP connections. // If DialContext is nil (and the deprecated Dial below is also nil), // then the transport dials using package net. DialContext func(ctx context.Context, network, addr string) (net.Conn, error) // Dial specifies the dial function for creating unencrypted TCP connections. // // Deprecated: Use DialContext instead, which allows the transport // to cancel dials as soon as they are no longer needed. // If both are set, DialContext takes priority. Dial func(network, addr string) (net.Conn, error) // DialTLS specifies an optional dial function for creating // TLS connections for non-proxied HTTPS requests. // // If DialTLS is nil, Dial and TLSClientConfig are used. // // If DialTLS is set, the Dial hook is not used for HTTPS // requests and the TLSClientConfig and TLSHandshakeTimeout // are ignored. The returned net.Conn is assumed to already be // past the TLS handshake. DialTLS func(network, addr string) (net.Conn, error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. // If nil, the default configuration is used. // If non-nil, HTTP/2 support may not be enabled by default. TLSClientConfig *tls.Config // TLSHandshakeTimeout specifies the maximum amount of time waiting to // wait for a TLS handshake. Zero means no timeout. TLSHandshakeTimeout time.Duration // DisableKeepAlives, if true, prevents re-use of TCP connections // between different HTTP requests. DisableKeepAlives bool // DisableCompression, if true, prevents the Transport from // requesting compression with an "Accept-Encoding: gzip" // request header when the Request contains no existing // Accept-Encoding value. If the Transport requests gzip on // its own and gets a gzipped response, it's transparently // decoded in the Response.Body. However, if the user // explicitly requested gzip it is not automatically // uncompressed. DisableCompression bool // MaxIdleConns controls the maximum number of idle (keep-alive) // connections across all hosts. Zero means no limit. MaxIdleConns int // MaxIdleConnsPerHost, if non-zero, controls the maximum idle // (keep-alive) connections to keep per-host. If zero, // DefaultMaxIdleConnsPerHost is used. MaxIdleConnsPerHost int // IdleConnTimeout is the maximum amount of time an idle // (keep-alive) connection will remain idle before closing // itself. // Zero means no limit. IdleConnTimeout time.Duration // ResponseHeaderTimeout, if non-zero, specifies the amount of // time to wait for a server's response headers after fully // writing the request (including its body, if any). This // time does not include the time to read the response body. ResponseHeaderTimeout time.Duration // ExpectContinueTimeout, if non-zero, specifies the amount of // time to wait for a server's first response headers after fully // writing the request headers if the request has an // "Expect: 100-continue" header. Zero means no timeout and // causes the body to be sent immediately, without // waiting for the server to approve. // This time does not include the time to send the request header. ExpectContinueTimeout time.Duration // TLSNextProto specifies how the Transport switches to an // alternate protocol (such as HTTP/2) after a TLS NPN/ALPN // protocol negotiation. If Transport dials an TLS connection // with a non-empty protocol name and TLSNextProto contains a // map entry for that key (such as "h2"), then the func is // called with the request's authority (such as "example.com" // or "example.com:1234") and the TLS connection. The function // must return a RoundTripper that then handles the request. // If TLSNextProto is not nil, HTTP/2 support is not enabled // automatically. TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper // ProxyConnectHeader optionally specifies headers to send to // proxies during CONNECT requests. ProxyConnectHeader Header // MaxResponseHeaderBytes specifies a limit on how many // response bytes are allowed in the server's response // header. // // Zero means to use a default limit. MaxResponseHeaderBytes int64 // contains filtered or unexported fields}
func (t *Transport) CancelRequest(req *Request)
CancelRequest通過關閉其連接來取消正在進行的請求。只有在RoundTrip返回后才能調用CancelRequest。
已棄用:使用Request.WithContext來創(chuàng)建具有可取消上下文的請求。CancelRequest無法取消HTTP/2請求。
func (t *Transport) CloseIdleConnections()
CloseIdleConnections關閉以前連接的所有連接,但是現(xiàn)在處于“保持活動”狀態(tài)。它不會中斷當前正在使用的任何連接。
func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)
RegisterProtocol用方案注冊一個新的協(xié)議。運輸將使用給定的方案將請求傳遞給rt。模擬HTTP請求語義是rt的責任。
其他軟件包可以使用RegisterProtocol來提供“ftp”或“file”等協(xié)議方案的實現(xiàn)。
如果rt.RoundTrip返回ErrSkipAltProtocol,Transport將為該請求處理RoundTrip本身,就好像該協(xié)議未注冊一樣。
func (t *Transport) RoundTrip(req *Request) (*Response, error)
RoundTrip實現(xiàn)RoundTripper接口。
對于更高級別的HTTP客戶端支持(如處理Cookie和重定向),請參閱獲取,發(fā)布和客戶端類型。
Name | Synopsis |
---|---|
cgi | cgi包實現(xiàn)了RFC 3875中規(guī)定的CGI(通用網(wǎng)關接口) |
cookiejar | 包cookiejar實現(xiàn)了符合內(nèi)存RFC 6265的http.CookieJar。 |
fcgi | fcgi包實現(xiàn)FastCGI協(xié)議。 |
httptest | httptest包提供了用于HTTP測試的實用程序。 |
httptrace | 包httptrace提供跟蹤HTTP客戶端請求中的事件的機制。 |
httputil | 軟件包httputil提供HTTP實用程序功能,補充了net/http軟件包中較常見的功能。 |
pprof | 軟件包pprof通過其HTTP服務器運行時分析數(shù)據(jù)以pprof可視化工具預期的格式提供服務。 |