亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

directory search
archive archive/tar archive/zip bufio bufio(緩存) builtin builtin(內(nèi)置包) bytes bytes(包字節(jié)) compress compress/bzip2(壓縮/bzip2) compress/flate(壓縮/flate) compress/gzip(壓縮/gzip) compress/lzw(壓縮/lzw) compress/zlib(壓縮/zlib) container container/heap(容器數(shù)據(jù)結(jié)構(gòu)heap) container/list(容器數(shù)據(jù)結(jié)構(gòu)list) container/ring(容器數(shù)據(jù)結(jié)構(gòu)ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(數(shù)據(jù)庫/sql) database/sql/driver(數(shù)據(jù)庫/sql/driver) debug debug/dwarf(調(diào)試/dwarf) debug/elf(調(diào)試/elf) debug/gosym(調(diào)試/gosym) debug/macho(調(diào)試/macho) debug/pe(調(diào)試/pe) debug/plan9obj(調(diào)試/plan9obj) encoding encoding(編碼) encoding/ascii85(編碼/ascii85) encoding/asn1(編碼/asn1) encoding/base32(編碼/base32) encoding/base64(編碼/base64) encoding/binary(編碼/binary) encoding/csv(編碼/csv) encoding/gob(編碼/gob) encoding/hex(編碼/hex) encoding/json(編碼/json) encoding/pem(編碼/pem) encoding/xml(編碼/xml) errors errors(錯(cuò)誤) expvar expvar flag flag(命令行參數(shù)解析flag包) fmt fmt go go/ast(抽象語法樹) go/build go/constant(常量) go/doc(文檔) go/format(格式) go/importer go/parser go/printer go/scanner(掃描儀) go/token(令牌) go/types(類型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(圖像) image/color(顏色) image/color/palette(調(diào)色板) image/draw(繪圖) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系統(tǒng)) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路徑) plugin plugin(插件) reflect reflect(反射) regexp regexp(正則表達(dá)式) regexp/syntax runtime runtime(運(yùn)行時(shí)) runtime/debug(調(diào)試) runtime/internal/sys runtime/pprof runtime/race(競(jìng)爭(zhēng)) runtime/trace(執(zhí)行追蹤器) sort sort(排序算法) strconv strconv(轉(zhuǎn)換) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系統(tǒng)調(diào)用) testing testing(測(cè)試) testing/iotest testing/quick text text/scanner(掃描文本) text/tabwriter text/template(定義模板) text/template/parse time time(時(shí)間戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
characters

  • import "net/http"

  • 概述

  • 索引

  • 示例

  • 子目錄

概述

http包提供HTTP客戶端和服務(wù)器實(shí)現(xiàn)。

Get,Head,Post和PostForm發(fā)出HTTP(或HTTPS)請(qǐng)求:

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"}})

客戶必須在完成后關(guān)閉響應(yīng)主體:

resp, err := http.Get("http://example.com/")if err != nil {// handle error}defer resp.Body.Close()body, err := ioutil.ReadAll(resp.Body)// ...

要控制HTTP客戶端標(biāo)題,重定向策略和其他設(shè)置,請(qǐng)創(chuàng)建一個(gè)客戶端:

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配置,?;睿瑝嚎s和其他設(shè)置,請(qǐng)創(chuàng)建一個(gè)傳輸:

tr := &http.Transport{
	MaxIdleConns:       10,
	IdleConnTimeout:    30 * time.Second,
	DisableCompression: true,}client := &http.Client{Transport: tr}resp, err := client.Get("https://example.com")

客戶端和傳輸對(duì)于多個(gè)goroutine并發(fā)使用是安全的,并且效率應(yīng)該只創(chuàng)建一次并重新使用。

ListenAndServe啟動(dòng)一個(gè)具有給定地址和處理程序的HTTP服務(wù)器。處理程序通常為零,這意味著使用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)建自定義服務(wù)器,可以更好地控制服務(wù)器的行為:

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時(shí)對(duì)HTTP/2協(xié)議有透明的支持。必須禁用HTTP/2的程序可以通過將Transport.TLSNextProto(對(duì)于客戶端)或Server.TLSNextProto(對(duì)于服務(wù)器)設(shè)置為非零空映射來實(shí)現(xiàn)?;蛘?,當(dāng)前支持以下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包的傳輸和服務(wù)器都自動(dòng)為簡(jiǎn)單配置啟用HTTP/2支持。要為更復(fù)雜的配置啟用HTTP/2,使用較低級(jí)別的HTTP/2功能或使用Go的http2軟件包的較新版本,請(qǐng)直接導(dǎo)入“golang.org/x/net/http2”并使用其配置傳輸和/或ConfigureServer功能。通過golang.org/x/net/http2軟件包手動(dòng)配置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注冊(cè)的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請(qǐng)求中頭部允許的最大大小。這可以通過設(shè)置Server.MaxHeaderBytes來覆蓋。

const DefaultMaxHeaderBytes = 1 << 20 // 1 MB

DefaultMaxIdleConnsPerHost是Transport的MaxIdleConnsPerHost的默認(rèn)值。

const DefaultMaxIdleConnsPerHost = 2

TimeFormat是在HTTP頭中生成時(shí)間時(shí)使用的時(shí)間格式。它就像time.RFC1123一樣,但是將GMT編碼為時(shí)區(qū)。格式化的時(shí)間必須以UTC格式生成正確的格式。

有關(guān)解析此時(shí)間格式的信息,請(qǐng)參閱ParseTime。

const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TrailerPrefix是ResponseWriter.Header映射鍵的奇幻的前綴,如果存在,它表示映射條目實(shí)際上是用于響應(yīng)預(yù)告片的,而不是響應(yīng)標(biāo)頭。在ServeHTTP呼叫結(jié)束并且值在trailers中發(fā)送后,該前綴被剝離。

該機(jī)制僅適用于在寫入標(biāo)題之前未知的trailers。如果在寫入標(biāo)題之前,一套trailers是固定的或已知的,則優(yōu)選正常的trailers機(jī)制:

https://golang.org/pkg/net/http/#ResponseWriter
https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
const TrailerPrefix = "Trailer:"

變量

var (        // 推送法返回 ErrNotSupported        // 實(shí)現(xiàn)來指示 HTTP\/2 推送支持不是        // 可用。
        ErrNotSupported = &ProtocolError{"feature not supported"}        // ErrUnexpectedTrailer 由傳輸返回, 當(dāng)服務(wù)器        // 答復(fù)與拖車頭, 但沒有塊答復(fù)。
        ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"}        // ErrMissingBoundary 是按請(qǐng)求返回的. MultipartReader 當(dāng)        // 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服務(wù)器使用的錯(cuò)誤。

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 是一個(gè)上下文鍵。可用于 HTTP        // 具有上下文的處理程序。WithValue 訪問服務(wù)器,        // 已啟動(dòng)處理程序。關(guān)聯(lián)的值將為        // 類型 * 服務(wù)器。
        ServerContextKey = &contextKey{"http-server"}        // LocalAddrContextKey 是一個(gè)上下文鍵??捎糜?nbsp;       // 帶有上下文的 HTTP 處理程序。WithValue 訪問地址        // 連接到達(dá)的本地地址。        // 關(guān)聯(lián)的值將為類型網(wǎng)。地址.
        LocalAddrContextKey = &contextKey{"local-addr"})

DefaultClient是默認(rèn)的客戶端,由Get,Head和Post使用。

var DefaultClient = &Client{}

DefaultServeMux是Serve使用的默認(rèn)ServeMux。

var DefaultServeMux = &defaultServeMux

ErrAbortHandler是中止處理程序的標(biāo)志性恐慌值。雖然ServeHTTP的任何恐慌都會(huì)中止對(duì)客戶端的響應(yīng),但使用ErrAbortHandler進(jìn)行恐慌也會(huì)禁止將堆棧跟蹤記錄到服務(wù)器的錯(cuò)誤日志中。

var ErrAbortHandler = errors.New("net/http: abort Handler")

在正文關(guān)閉后讀取Request或Response Body時(shí)返回ErrBodyReadAfterClose。這通常發(fā)生在HTTP處理程序在其ResponseWriter上調(diào)用WriteHeader或Write之后讀取主體時(shí)。

var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")

在超時(shí)的處理程序中的ResponseWriter Write調(diào)用上返回ErrHandlerTimeout。

var ErrHandlerTimeout = errors.New("http: Handler timeout")

當(dāng)讀取格式不正確的分塊編碼的請(qǐng)求或響應(yīng)主體時(shí),返回ErrLineTooLong。

var ErrLineTooLong = internal.ErrLineTooLong

當(dāng)提供的文件字段名稱不存在于請(qǐng)求中或文件字段中時(shí),F(xiàn)ormFile將返回ErrMissingFile。

var ErrMissingFile = errors.New("http: no such file")

當(dāng)找不到cookie時(shí),ErrNoCookie通過Request的Cookie方法返回。

var ErrNoCookie = errors.New("http: named cookie not present")

當(dāng)沒有位置標(biāo)題時(shí),ErrNoLocation由Response's Location方法返回。

var ErrNoLocation = errors.New("http: no Location header in response")

在調(diào)用Shutdown或Close之后,服務(wù)器的Serve,ServeTLS,ListenAndServe和ListenAndServeTLS方法會(huì)返回ErrServerClosed。

var ErrServerClosed = errors.New("http: Server closed")

ErrSkipAltProtocol是由Transport.RegisterProtocol定義的一個(gè)sentinel錯(cuò)誤值。

var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")

Client.CheckRedirect鉤子可以返回ErrUseLastResponse來控制重定向的處理方式。如果返回,則不會(huì)發(fā)送下一個(gè)請(qǐng)求,并且返回其最新的響應(yīng),并且其主體未關(guān)閉。

var ErrUseLastResponse = errors.New("net/http: use last response")

NoBody是一個(gè)沒有字節(jié)的io.ReadCloser。閱讀始終返回EOF和關(guān)閉總是返回零。它可用于傳出的客戶端請(qǐng)求中,以明確表示請(qǐng)求具有零字節(jié)。但是,另一種方法是簡(jiǎn)單地將Request.Body設(shè)置為零。

var NoBody = noBody{}

func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

CanonicalHeaderKey返回標(biāo)題密鑰的規(guī)范格式。規(guī)范化將第一個(gè)字母和連字符后面的任何字母轉(zhuǎn)換為大寫;其余的都轉(zhuǎn)換為小寫。例如,“accept-encoding”的規(guī)范密鑰是“Accept-Encoding”。如果s包含空格或無效標(biāo)題字段字節(jié),則不做任何修改就返回。

func DetectContentType

func DetectContentType(data []byte) string

DetectContentType實(shí)現(xiàn)http://mimesniff.spec.whatwg.org/中描述的算法來確定給定數(shù)據(jù)的內(nèi)容類型。它至多會(huì)考慮前512個(gè)字節(jié)的數(shù)據(jù)。DetectContentType始終返回一個(gè)有效的MIME類型:如果無法確定更具體的MIME類型,則返回“application/octet-stream”。

func Error

func Error(w ResponseWriter, error string, code int)

錯(cuò)誤以指定的錯(cuò)誤消息和HTTP代碼答復(fù)請(qǐng)求。它不以其他方式結(jié)束請(qǐng)求;調(diào)用者應(yīng)該確保沒有進(jìn)一步寫入w。錯(cuò)誤信息應(yīng)該是純文本。

func Handle

func Handle(pattern string, handler Handler)

Handle將給定模式的處理程序注冊(cè)到DefaultServeMux中。ServeMux的文檔解釋了模式如何匹配。

func HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc在DefaultServeMux中為給定模式注冊(cè)處理函數(shù)。ServeMux的文檔解釋了模式如何匹配。

func ListenAndServe

func ListenAndServe(addr string, handler Handler) error

ListenAndServe偵聽TCP網(wǎng)絡(luò)地址addr,然后使用處理程序調(diào)用Serve來處理傳入連接上的請(qǐng)求。接受的連接被配置為啟用TCP保持活動(dòng)。Handler通常為零,在這種情況下使用DefaultServeMux。

一個(gè)簡(jiǎn)單的示例服務(wù)器是:

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總是返回一個(gè)非零錯(cuò)誤。

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

ListenAndServeTLS的作用與ListenAndServe完全相同,只不過它需要HTTPS連接。此外,必須提供包含服務(wù)器證書和匹配私鑰的文件。如果證書由證書頒發(fā)機(jī)構(gòu)簽署,則certFile應(yīng)該是服務(wù)器證書,任何中間器和CA證書的串聯(lián)。

一個(gè)簡(jiǎn)單的示例服務(wù)器是:

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總是返回一個(gè)非零錯(cuò)誤。

func MaxBytesReader

func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser

MaxBytesReader與io.LimitReader類似,但是用于限制傳入請(qǐng)求體的大小。與io.LimitReader相反,MaxBytesReader的結(jié)果是一個(gè)ReadCloser,它為超出限制的Read返回一個(gè)非EOF錯(cuò)誤,并在其Close方法被調(diào)用時(shí)關(guān)閉底層的閱讀器。

MaxBytesReader可防止客戶端意外或惡意發(fā)送大量請(qǐng)求并浪費(fèi)服務(wù)器資源。

func NotFound

func NotFound(w ResponseWriter, r *Request)

NotFound使用HTTP 404找不到錯(cuò)誤來回復(fù)請(qǐng)求。

func ParseHTTPVersion

func ParseHTTPVersion(vers string) (major, minor int, ok bool)

ParseHTTPVersion分析HTTP版本字符串?!癏TTP/1.0”返回(1, 0, true)。

func ParseTime

func ParseTime(text string) (t time.Time, err error)

ParseTime分析時(shí)間標(biāo)題(例如Date: header),嘗試HTTP/1.1允許的三種格式:TimeFormat,time.RFC850和time.ANSIC。

func ProxyFromEnvironment

func ProxyFromEnvironment(req *Request) (*url.URL, error)

ProxyFromEnvironment返回用于給定請(qǐng)求的代理的URL,如環(huán)境變量HTTP_PROXY,HTTPS_PROXY和NO_PROXY(或其小寫版本)所示。對(duì)于https請(qǐng)求,HTTPS_PROXY優(yōu)先于HTTP_PROXY。

環(huán)境值可以是完整的URL或“host:port”,在這種情況下,假設(shè)“http”方案。如果值是不同的形式,則返回錯(cuò)誤。

如果沒有在環(huán)境中定義代理,或者代理不應(yīng)該用于給定請(qǐng)求(如NO_PROXY所定義),則返回零URL和零錯(cuò)誤。

作為一種特殊情況,如果req.URL.Host是“l(fā)ocalhost”(帶或不帶端口號(hào)),則會(huì)返回一個(gè)零URL和零錯(cuò)誤。

func ProxyURL

func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)

ProxyURL返回一個(gè)總是返回相同URL的代理函數(shù)(用于傳輸)。

func Redirect

func Redirect(w ResponseWriter, r *Request, url string, code int)

將重定向到url的請(qǐng)求重定向到請(qǐng)求,url可能是相對(duì)于請(qǐng)求路徑的路徑。

提供的代碼應(yīng)該位于3xx范圍內(nèi),通常是StatusMovedPermanently,StatusFound或StatusSeeOther。

func Serve

func Serve(l net.Listener, handler Handler) error

Serve接受偵聽器l上的傳入HTTP連接,為每個(gè)服務(wù)器創(chuàng)建一個(gè)新的服務(wù)程序。服務(wù)程序讀取請(qǐng)求,然后調(diào)用處理程序來回復(fù)它們。Handler通常為零,在這種情況下使用DefaultServeMux。

func ServeContent

func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)

ServeContent使用提供的ReadSeeker中的內(nèi)容答復(fù)請(qǐng)求。ServeContent優(yōu)于io.Copy的主要好處是它正確處理Range請(qǐng)求,設(shè)置MIME類型,并處理If-Match,If-Unmodified-Since,If-None-Match,If-Modified-Since和If-Range要求。

如果未設(shè)置響應(yīng)的Content-Type標(biāo)頭,則ServeContent首先嘗試從名稱的文件擴(kuò)展名中推導(dǎo)出該類型,如果失敗,則返回讀取內(nèi)容的第一個(gè)塊并將其傳遞給DetectContentType。這個(gè)名字是沒有用的;特別是它可以是空的,并且不會(huì)在響應(yīng)中發(fā)送。

如果modtime不是零時(shí)間或Unix紀(jì)元,則ServeContent將其包含在響應(yīng)中的Last-Modified標(biāo)頭中。如果請(qǐng)求包含If-Modified-Since標(biāo)頭,則ServeContent使用modtime決定是否需要發(fā)送內(nèi)容。

內(nèi)容的Seek方法必須工作:ServeContent使用搜索到內(nèi)容的結(jié)尾來確定其大小。

如果調(diào)用者已經(jīng)根據(jù)RFC 7232第2.3節(jié)設(shè)置了w的ETag頭,則ServeContent使用它來處理使用If-Match,If-None-Match或If-Range的請(qǐng)求。

請(qǐng)注意* os.File實(shí)現(xiàn)了io.ReadSeeker接口。

func ServeFile

func ServeFile(w ResponseWriter, r *Request, name string)

ServeFile使用指定文件或目錄的內(nèi)容答復(fù)請(qǐng)求。

如果提供的文件或目錄名稱是相對(duì)路徑,則相對(duì)于當(dāng)前目錄進(jìn)行解釋并可能上升到父目錄。如果提供的名稱是從用戶輸入構(gòu)建的,則應(yīng)在調(diào)用ServeFile之前對(duì)其進(jìn)行消毒。作為預(yù)防措施,ServeFile將拒絕r.URL.Path包含“..”路徑元素的請(qǐng)求。

作為一種特殊情況,ServeFile將r.URL.Path以“/index.html”結(jié)尾的任何請(qǐng)求重定向到相同的路徑,而沒有最終的“index.html”。要避免這種重定向,請(qǐng)修改路徑或使用ServeContent。

func ServeTLS

func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error

Serve接受listener l上的傳入HTTPS連接,為每個(gè)服務(wù)器創(chuàng)建一個(gè)新的服務(wù)程序。服務(wù)程序讀取請(qǐng)求,然后調(diào)用處理程序來回復(fù)它們。

Handler通常為零,在這種情況下使用DefaultServeMux。

此外,必須提供包含服務(wù)器證書和匹配私鑰的文件。如果證書由證書頒發(fā)機(jī)構(gòu)簽署,則certFile應(yīng)該是服務(wù)器證書,任何中間器和CA證書的串聯(lián)。

func SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie)

SetCookie將一個(gè)Set-Cookie頭添加到提供的ResponseWriter的頭文件中。提供的cookie必須具有有效的名稱。無效的Cookie可能會(huì)悄悄丟棄。

func StatusText

func StatusText(code int) string

StatusText返回HTTP狀態(tài)碼的文本。如果代碼未知,它將返回空字符串。

type Client

客戶端是一個(gè)HTTP客戶端。其零值(DefaultClient)是使用DefaultTransport的可用客戶端。

客戶端的傳輸通常具有內(nèi)部狀態(tài)(緩存的TCP連接),因此客戶端應(yīng)該被重用,而不是根據(jù)需要?jiǎng)?chuàng)建??蛻舳丝梢园踩赜啥鄠€(gè)goroutine并發(fā)使用。

客戶端比RoundTripper(比如Transport)更高級(jí),并且還處理諸如cookie和重定向之類的HTTP細(xì)節(jié)。

在重定向之后,客戶端將轉(zhuǎn)發(fā)在初始請(qǐng)求中設(shè)置的所有標(biāo)頭,除了:

?將“Authorization”,“WWW-Authenticate”和“Cookie”等敏感標(biāo)頭轉(zhuǎn)發(fā)給不受信任的目標(biāo)時(shí)。在重定向到不是子域匹配的域或初始域的完全匹配時(shí),這些標(biāo)頭將被忽略。例如,從“foo.com”到“foo.com”或“sub.foo.com”的重定向?qū)⑥D(zhuǎn)發(fā)敏感標(biāo)題,但重定向到“bar.com”則不會(huì)。

?轉(zhuǎn)發(fā)“Cookie”標(biāo)頭時(shí)使用非零 cookie Jar。由于每個(gè)重定向可能會(huì)改變cookie jar的狀態(tài),重定向可能會(huì)改變初始請(qǐng)求中設(shè)置的cookie。轉(zhuǎn)發(fā)“Cookie”標(biāo)頭時(shí),任何突變的Cookie都將被忽略,并期望Jar將插入這些帶有更新值的突變cookie(假設(shè)該匹配的來源)。如果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 (*Client) Do

func (c *Client) Do(req *Request) (*Response, error)

不要發(fā)送HTTP請(qǐng)求,并按照客戶端上配置的策略(例如redirects, cookies,auth)返回HTTP響應(yīng)。

如果由客戶端策略(如CheckRedirect)引起,或者無法說出HTTP(如網(wǎng)絡(luò)連接問題),則返回錯(cuò)誤。非2xx狀態(tài)碼不會(huì)導(dǎo)致錯(cuò)誤。

如果返回的錯(cuò)誤為零,則Response將包含一個(gè)非零體,用戶需要關(guān)閉。如果Body尚未關(guān)閉,則客戶端的底層RoundTripper(通常是Transport)可能無法重新使用持久性TCP連接到服務(wù)器以進(jìn)行后續(xù)“保持活動(dòng)”請(qǐng)求。

如果非零,請(qǐng)求主體將被底層傳輸關(guān)閉,即使出現(xiàn)錯(cuò)誤。

出錯(cuò)時(shí),可以忽略任何響應(yīng)。非零錯(cuò)誤的非零響應(yīng)僅在CheckRedirect失敗時(shí)發(fā)生,即使返回的Response.Body已經(jīng)關(guān)閉。

通常會(huì)使用Get,Post或PostForm來代替Do.

如果服務(wù)器回復(fù)重定向,則客戶端首先使用CheckRedirect函數(shù)確定是否應(yīng)該遵循重定向。如果允許,301,302或303重定向會(huì)導(dǎo)致后續(xù)請(qǐng)求使用HTTP方法GET(如果原始請(qǐng)求是HEAD,則為HEAD),但不包含主體。只要定義了Request.GetBody函數(shù),307或308重定向就會(huì)保留原始的HTTP方法和主體。NewRequest函數(shù)自動(dòng)為通用標(biāo)準(zhǔn)庫體類型設(shè)置GetBody。

func (*Client) Get

func (c *Client) Get(url string) (resp *Response, err error)

將問題GET獲取到指定的URL。如果響應(yīng)是以下重定向代碼之一,則在調(diào)用客戶端的CheckRedirect函數(shù)后,Get遵循重定向:

301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)

如果客戶端的CheckRedirect功能失敗或者出現(xiàn)HTTP協(xié)議錯(cuò)誤,則返回錯(cuò)誤。非2xx響應(yīng)不會(huì)導(dǎo)致錯(cuò)誤。

當(dāng)err為零時(shí),resp總是包含非零的resp.Body。來電者在完成閱讀后應(yīng)關(guān)閉resp.Body。

要使用自定義標(biāo)題發(fā)出請(qǐng)求,請(qǐng)使用NewRequest和Client.Do。

func (*Client) Head

func (c *Client) Head(url string) (resp *Response, err error)

Head向指定的URL發(fā)出HEAD。如果響應(yīng)是以下重定向代碼之一,則Head在調(diào)用客戶端的CheckRedirect函數(shù)后遵循重定向:

301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)

func (*Client) Post

func (c *Client) Post(url string, contentType string, body io.Reader) (resp *Response, err error)

發(fā)布POST到指定的URL。

調(diào)用者在完成閱讀后應(yīng)關(guān)閉resp.Body。

如果提供的主體是io.Closer,則在請(qǐng)求后關(guān)閉。

要設(shè)置自定義標(biāo)題,請(qǐng)使用NewRequest和Client.Do。

有關(guān)如何處理重定向的詳細(xì)信息,請(qǐng)參閱Client.Do方法文檔。

func (*Client) PostForm

func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

PostForm向指定的URL發(fā)布POST,并將數(shù)據(jù)的鍵和值作為請(qǐng)求主體進(jìn)行URL編碼。

Content-Type頭部設(shè)置為application/x-www-form-urlencoded。要設(shè)置其他標(biāo)題,請(qǐng)使用NewRequest和DefaultClient.Do。

當(dāng)err為零時(shí),resp總是包含非零的resp.Body。調(diào)用者在完成閱讀后應(yīng)關(guān)閉resp.Body。

有關(guān)如何處理重定向的詳細(xì)信息,請(qǐng)參閱Client.Do方法文檔。

type CloseNotifier

CloseNotifier接口由ResponseWriters實(shí)現(xiàn),它允許檢測(cè)基礎(chǔ)連接何時(shí)消失。

如果客戶端在響應(yīng)準(zhǔn)備好之前斷開連接,則可以使用此機(jī)制取消服務(wù)器上的長(zhǎng)時(shí)間操作。

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}

type ConnState

ConnState表示客戶端連接到服務(wù)器的狀態(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 (ConnState) String

func (c ConnState) String() string

type Cookie

Cookie表示HTTP響應(yīng)的Set-Cookie頭或HTTP請(qǐng)求的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 (*Cookie) String

func (c *Cookie) String() string

字符串返回用于Cookie標(biāo)頭(如果僅設(shè)置了Name和Value)或Set-Cookie響應(yīng)標(biāo)頭(如果設(shè)置了其他字段)的Cookie的序列化。如果c為零或c.Name無效,則返回空字符串。

type CookieJar

CookieJar管理HTTP請(qǐng)求中cookie的存儲(chǔ)和使用。

CookieJar的實(shí)現(xiàn)必須安全,以供多個(gè)goroutine同時(shí)使用。

net/http/cookiejar包提供了一個(gè)CookieJar實(shí)現(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}

type Dir

Dir使用限于特定目錄樹的本機(jī)文件系統(tǒng)實(shí)現(xiàn)FileSystem。

雖然FileSystem.Open方法采用'/' - 分隔的路徑,但Dir的字符串值是本地文件系統(tǒng)上的文件名,而不是URL,因此它由filepath.Separator分隔,而不一定是'/'。

請(qǐng)注意,Dir將允許訪問以句點(diǎn)開頭的文件和目錄,這可能會(huì)暴露敏感目錄(如.git目錄)或敏感文件(如.htpasswd)。要排除具有前導(dǎo)期的文件,請(qǐng)從服務(wù)器中刪除文件/目錄或創(chuàng)建自定義FileSystem實(shí)現(xiàn)。

空的Dir被視為“?!?。

type Dir string

func (Dir) Open

func (d Dir) Open(name string) (File, error)

type File

File由FileSystem的Open方法返回,并可由FileServer實(shí)現(xiàn)提供。

這些方法的行為應(yīng)該與* os.File中的方法相同。

type File interface {
        io.Closer
        io.Reader
        io.Seeker        Readdir(count int) ([]os.FileInfo, error)        Stat() (os.FileInfo, error)}

type FileSystem

FileSystem實(shí)現(xiàn)對(duì)指定文件集合的訪問。無論主機(jī)操作系統(tǒng)慣例如何,文件路徑中的元素都用斜線('/', U+002F)字符分隔。

type FileSystem interface {        Open(name string) (File, error)}

type Flusher

Flusher接口由ResponseWriters實(shí)現(xiàn),它允許HTTP處理器將緩沖數(shù)據(jù)刷新到客戶端。

默認(rèn)的HTTP/1.x和HTTP/2 ResponseWriter實(shí)現(xiàn)支持Flusher,但ResponseWriter包裝可能不支持。處理程序應(yīng)始終在運(yùn)行時(shí)測(cè)試此功能。

請(qǐng)注意,即使對(duì)于支持Flush的ResponseWriters,如果客戶端通過HTTP代理連接,緩存的數(shù)據(jù)可能無法到達(dá)客戶端,直到響應(yīng)完成。

type Flusher interface {        // Flush sends any buffered data to the client.        Flush()}

type Handler

Handler響應(yīng)HTTP請(qǐng)求。

ServeHTTP應(yīng)該將回復(fù)頭文件和數(shù)據(jù)寫入ResponseWriter,然后返回。返回請(qǐng)求完成的信號(hào);在完成ServeHTTP調(diào)用之后或同時(shí)完成使用ResponseWriter或從Request.Body中讀取是無效的。

根據(jù)HTTP客戶端軟件,HTTP協(xié)議版本以及客戶端與Go服務(wù)器之間的任何中介,在寫入ResponseWriter后,可能無法從Request.Body中讀取數(shù)據(jù)。謹(jǐn)慎的處理程序應(yīng)先讀取Request.Body,然后回復(fù)。

除閱讀主體外,處理程序不應(yīng)修改提供的請(qǐng)求。

如果ServeHTTP發(fā)生混亂,則服務(wù)器(ServeHTTP的調(diào)用者)認(rèn)為恐慌的影響與活動(dòng)請(qǐng)求分離。它恢復(fù)恐慌,將堆棧跟蹤記錄到服務(wù)器錯(cuò)誤日志中,并根據(jù)HTTP協(xié)議關(guān)閉網(wǎng)絡(luò)連接或發(fā)送HTTP/2 RST_STREAM。要終止處理程序,以便客戶端看到中斷的響應(yīng),但服務(wù)器不記錄錯(cuò)誤,請(qǐng)使用值ErrAbortHandler恐慌。

type Handler interface {        ServeHTTP(ResponseWriter, *Request)}

func FileServer

func FileServer(root FileSystem) Handler

FileServer返回一個(gè)處理程序,該處理程序?yàn)閞oot用戶提供文件系統(tǒng)內(nèi)容的HTTP請(qǐng)求。

要使用操作系統(tǒng)的文件系統(tǒng)實(shí)現(xiàn),請(qǐng)使用http.Dir:

http.Handle("/", http.FileServer(http.Dir("/tmp")))

作為一種特殊情況,返回的文件服務(wù)器將以“/index.html”結(jié)尾的任何請(qǐng)求重定向到相同的路徑,而沒有最終的“index.html”。

示例

package mainimport ("log""net/http")func main() {// Simple static webserver:
	log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))}

示例(StripPrefix)

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

func NotFoundHandler() Handler

NotFoundHandler返回一個(gè)簡(jiǎn)單的請(qǐng)求處理程序,用于處理每個(gè)請(qǐng)求的“404頁未找到”答復(fù)。

func RedirectHandler

func RedirectHandler(url string, code int) Handler

RedirectHandler返回一個(gè)請(qǐng)求處理程序,它使用給定的狀態(tài)碼將其收到的每個(gè)請(qǐng)求重定向到給定的url。

提供的代碼應(yīng)該位于3xx范圍內(nèi),通常是StatusMovedPermanently,StatusFound或StatusSeeOther。

func StripPrefix

func StripPrefix(prefix string, h Handler) Handler

StripPrefix通過從請(qǐng)求URL的Path中移除給定的前綴并調(diào)用處理程序h來返回一個(gè)處理程序,該處理程序提供HTTP請(qǐng)求。StripPrefix通過回答HTTP 404找不到錯(cuò)誤來處理對(duì)不以前綴開頭的路徑的請(qǐng)求。

示例

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

func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler

TimeoutHandler返回一個(gè)處理器,它在給定的時(shí)間限制內(nèi)運(yùn)行h。

新的Handler調(diào)用h.ServeHTTP來處理每個(gè)請(qǐng)求,但是如果一個(gè)調(diào)用的運(yùn)行時(shí)間超過其時(shí)間限制,處理程序會(huì)響應(yīng)503服務(wù)不可用錯(cuò)誤和其正文中的給定消息。(如果msg為空,將發(fā)送一個(gè)合適的默認(rèn)消息。)在這樣的超時(shí)之后,h寫入其ResponseWriter將返回ErrHandlerTimeout。

TimeoutHandler將所有Handler緩沖區(qū)寫入內(nèi)存,并且不支持Hijacker或Flusher接口。

type HandlerFunc

HandlerFunc類型是一個(gè)適配器,允許使用普通函數(shù)作為HTTP處理程序。如果f是具有適當(dāng)簽名的函數(shù),則HandlerFunc(f)是調(diào)用f的Handler。

type HandlerFunc func(ResponseWriter, *Request)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP calls f(w, r).

type Header

標(biāo)題表示HTTP標(biāo)題中的鍵值對(duì)。

type Header map[string][]string

func (Header) Add

func (h Header) Add(key, value string)

添加將關(guān)鍵字值對(duì)添加到標(biāo)題。它附加到與鍵相關(guān)的任何現(xiàn)有值。

func (Header) Del

func (h Header) Del(key string)

Del刪除與鍵關(guān)聯(lián)的值。

func (Header) Get

func (h Header) Get(key string) string

獲取與給定鍵相關(guān)的第一個(gè)值。它不區(qū)分大小寫; textproto.CanonicalMIMEHeaderKey用于規(guī)范提供的密鑰。如果沒有與該鍵關(guān)聯(lián)的值,Get返回“”。要訪問密鑰的多個(gè)值或使用非規(guī)范密鑰,請(qǐng)直接訪問地圖。

func (Header) Set

func (h Header) Set(key, value string)

Set將與鍵關(guān)聯(lián)的標(biāo)題條目設(shè)置為單個(gè)元素值。它取代了任何與鍵相關(guān)的現(xiàn)有值。

func (Header) Write

func (h Header) Write(w io.Writer) error

Write以格式寫入標(biāo)題。

func (Header) WriteSubset

func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error

WriteSubset以連線格式寫入標(biāo)題。如果exclude不為零,則不會(huì)寫入excludekey == true的鍵。

type Hijacker

Hijacker接口由ResponseWriters實(shí)現(xiàn),它允許HTTP處理程序接管連接。

HTTP/1.x連接的默認(rèn)ResponseWriter支持劫持程序,但HTTP/2連接故意不支持。ResponseWriter包裝器也可能不支持劫持程序。處理程序應(yīng)始終在運(yùn)行時(shí)測(cè)試此功能。

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()})}

type ProtocolError

ProtocolError表示HTTP協(xié)議錯(cuò)誤。

Deprecated:并非與協(xié)議錯(cuò)誤有關(guān)的http包中的所有錯(cuò)誤都是ProtocolError 類型。

type ProtocolError struct {
        ErrorString string}

func (*ProtocolError) Error

func (pe *ProtocolError) Error() string

type PushOptions

PushOptions描述了Pusher.Push的選項(xiàng)。

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}

type Pusher

Pusher是ResponseWriters實(shí)現(xiàn)的接口,支持HTTP/2服務(wù)器推送。

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}

type Request

請(qǐng)求表示由服務(wù)器接收或由客戶端發(fā)送的HTTP請(qǐng)求。

客戶端和服務(wù)器使用情況的字段語義略有不同。除了下面字段的注釋之外,請(qǐng)參閱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

func NewRequest(method, url string, body io.Reader) (*Request, error)

NewRequest返回給定方法,URL和可選主體的新請(qǐng)求。

如果提供的主體也是io.Closer,則返回的Request.Body將設(shè)置為body,并且將由客戶端方法Do,Post和PostForm以及Transport.RoundTrip關(guān)閉。

NewRequest返回適用于Client.Do或Transport.RoundTrip的請(qǐng)求。要?jiǎng)?chuàng)建與測(cè)試服務(wù)器處理程序一起使用的請(qǐng)求,請(qǐng)使用net/http/httptest軟件包中的NewRequest函數(shù),使用ReadRequest或手動(dòng)更新請(qǐng)求字段。有關(guān)入站和出站請(qǐng)求字段之間的差異,請(qǐng)參閱請(qǐng)求類型的文檔。

如果body是* bytes.Buffer,* bytes.Reader或* strings.Reader類型,則返回的請(qǐng)求的ContentLength被設(shè)置為它的精確值(而不是-1),GetBody被填充(所以307和308重定向可以重放body),如果ContentLength為0,則Body設(shè)置為NoBody。

func ReadRequest

func ReadRequest(b *bufio.Reader) (*Request, error)

ReadRequest讀取并解析來自b的傳入請(qǐng)求。

func (*Request) AddCookie

func (r *Request) AddCookie(c *Cookie)

AddCookie向請(qǐng)求添加一個(gè)cookie。根據(jù)RFC 6265第5.4節(jié)的規(guī)定,AddCookie不會(huì)附加多個(gè)Cookie標(biāo)題字段。這意味著所有的cookies(如果有的話)被寫入同一行,并以分號(hào)分隔。

func (*Request) BasicAuth

func (r *Request) BasicAuth() (username, password string, ok bool)

如果請(qǐng)求使用HTTP基本認(rèn)證,BasicAuth將返回請(qǐng)求的授權(quán)標(biāo)頭中提供的用戶名和密碼。請(qǐng)參閱RFC 2617,第2部分。

func (*Request) Context

func (r *Request) Context() context.Context

上下文返回請(qǐng)求的上下文。要更改上下文,請(qǐng)使用WithContext。

返回的上下文總是非零;它默認(rèn)為后臺(tái)上下文。

對(duì)于傳出的客戶端請(qǐng)求,上下文控制取消。

對(duì)于傳入的服務(wù)器請(qǐng)求,當(dāng)客戶端連接關(guān)閉,取消請(qǐng)求(使用HTTP/2)或ServeHTTP方法返回時(shí),上下文將被取消。

func (*Request) Cookie

func (r *Request) Cookie(name string) (*Cookie, error)

Cookie返回請(qǐng)求中提供的命名cookie或ErrNoCookie,如果未找到。如果多個(gè)cookie匹配給定名稱,則只會(huì)返回一個(gè)cookie。

func (*Request) Cookies

func (r *Request) Cookies() []*Cookie

Cookies解析并返回隨請(qǐng)求發(fā)送的HTTP Cookie。

func (*Request) FormFile

func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile返回提供的表單鍵的第一個(gè)文件。如有必要,F(xiàn)ormFile調(diào)用ParseMultipartForm和ParseForm。

func (*Request) FormValue

func (r *Request) FormValue(key string) string

FormValue返回查詢命名組件的第一個(gè)值。POST和PUT正文參數(shù)優(yōu)先于URL查詢字符串值。如有必要,F(xiàn)ormValue調(diào)用ParseMultipartForm和ParseForm,并忽略這些函數(shù)返回的任何錯(cuò)誤。如果鍵不存在,F(xiàn)ormValue返回空字符串。要訪問同一個(gè)鍵的多個(gè)值,請(qǐng)調(diào)用ParseForm,然后直接檢查Request.Form。

func (*Request) MultipartReader

func (r *Request) MultipartReader() (*multipart.Reader, error)

如果這是multipart/form-data POST請(qǐng)求,則MultipartReader會(huì)返回MIME多部分閱讀器,否則返回nil并顯示錯(cuò)誤。使用此函數(shù)而不是ParseMultipartForm將請(qǐng)求主體作為流處理。

func (*Request) ParseForm

func (r *Request) ParseForm() error

ParseForm填充r.Form和r.PostForm。

對(duì)于所有請(qǐng)求,ParseForm解析來自URL的原始查詢并更新r.Form。

對(duì)于POST,PUT和PATCH請(qǐng)求,它還將請(qǐng)求主體解析為表單并將結(jié)果放入r.PostForm和r.Form中。請(qǐng)求主體參數(shù)優(yōu)先于r.Form中的URL查詢字符串值。

對(duì)于其他HTTP方法,或者當(dāng)Content-Type不是application/x-www-form-urlencoded時(shí),請(qǐng)求體不會(huì)被讀取,并且r.PostForm被初始化為非零空值。

如果請(qǐng)求體的大小尚未被MaxBytesReader限制,則大小限制為10MB。

ParseMultipartForm自動(dòng)調(diào)用ParseForm。ParseForm是冪等的。

func (*Request) ParseMultipartForm

func (r *Request) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm將請(qǐng)求主體解析為multipart/form-data。對(duì)整個(gè)請(qǐng)求體進(jìn)行解析,并將其文件部分的總共maxMemory字節(jié)存儲(chǔ)在內(nèi)存中,其余部分存儲(chǔ)在磁盤中的臨時(shí)文件中。如有必要,ParseMultipartForm會(huì)調(diào)用ParseForm。在一次調(diào)用ParseMultipartForm后,后續(xù)調(diào)用不起作用。

func (*Request) PostFormValue

func (r *Request) PostFormValue(key string) string

PostFormValue返回POST或PUT請(qǐng)求主體的命名組件的第一個(gè)值。網(wǎng)址查詢參數(shù)被忽略。如有必要,PostFormValue調(diào)用ParseMultipartForm和ParseForm,并忽略這些函數(shù)返回的任何錯(cuò)誤。如果鍵不存在,PostFormValue返回空字符串。

func (*Request) ProtoAtLeast

func (r *Request) ProtoAtLeast(major, minor int) bool

ProtoAtLeast報(bào)告請(qǐng)求中使用的HTTP協(xié)議是否至少major.minor。

func (*Request) Referer

func (r *Request) Referer() string

如果在請(qǐng)求中發(fā)送,Referer返回引用URL。

引用者在請(qǐng)求本身中拼寫錯(cuò)誤,這是HTTP早期的錯(cuò)誤。這個(gè)值也可以從Header映射中作為Header“Referer”獲取; 將其作為一種方法提供的好處是,編譯器可以診斷使用備用(正確的英文)拼寫req.Referrer()的程序,但無法診斷使用Header“Referrer”的程序。

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string)

SetBasicAuth將請(qǐng)求的授權(quán)標(biāo)頭設(shè)置為使用帶有所提供的用戶名和密碼的HTTP基本認(rèn)證。

使用HTTP基本身份驗(yàn)證時(shí),提供的用戶名和密碼未加密。

func (*Request) UserAgent

func (r *Request) UserAgent() string

如果在請(qǐng)求中發(fā)送,UserAgent會(huì)返回客戶端的用戶代理。

func (*Request) WithContext

func (r *Request) WithContext(ctx context.Context) *Request

WithContext返回r的淺表副本,其上下文已更改為ctx。提供的ctx必須是非零。

func (*Request) Write

func (r *Request) Write(w io.Writer) error

寫入有線格式的HTTP/1.1請(qǐng)求,這是標(biāo)頭和正文。該方法會(huì)查詢請(qǐng)求的以下字段:

Host
URLMethod (defaults to "GET")Header
ContentLength
TransferEncoding
Body

如果Body存在,則Content-Length <= 0且TransferEncoding尚未設(shè)置為“identity”,Write將“Transfer-Encoding: chunked”添加到標(biāo)頭。身體在發(fā)送后關(guān)閉。

func (*Request) WriteProxy

func (r *Request) WriteProxy(w io.Writer) error

WriteProxy就像Write,但以HTTP代理的預(yù)期形式寫入請(qǐng)求。特別是,WriteProxy按照RFC 2616的5.1.2節(jié)(包括方案和主機(jī))以絕對(duì)URI寫入請(qǐng)求的初始Request-URI行。無論哪種情況,WriteProxy還會(huì)使用r.Host或r.URL.Host寫入一個(gè)主機(jī)頭。

type Response

響應(yīng)表示來自HTTP請(qǐng)求的響應(yīng)。

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

func Get(url string) (resp *Response, err error)

將問題GET獲取到指定的URL。如果響應(yīng)是以下重定向代碼之一,則Get遵循重定向,最多可重定向10次:

301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)

如果重定向太多或出現(xiàn)HTTP協(xié)議錯(cuò)誤,則會(huì)返回錯(cuò)誤。非2xx響應(yīng)不會(huì)導(dǎo)致錯(cuò)誤。

當(dāng)err為零時(shí),resp總是包含非零的resp.Body。來電者在完成閱讀后應(yīng)關(guān)閉resp.Body。

Get是一個(gè)DefaultClient.Get的包裝器。

要使用自定義標(biāo)題發(fā)出請(qǐng)求,請(qǐng)使用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

func Head(url string) (resp *Response, err error)

Head向指定的URL發(fā)出HEAD。如果響應(yīng)是以下重定向代碼之一,Head會(huì)遵循重定向,最多可重定向10次:

301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)

Head是DefaultClient.Head的包裝

func Post

func Post(url string, contentType string, body io.Reader) (resp *Response, err error)

發(fā)布POST到指定的URL。

調(diào)用者在完成閱讀后應(yīng)關(guān)閉resp.Body。

如果提供的主體是io.Closer,則在請(qǐng)求后關(guān)閉。

Post是DefaultClient.Post的一個(gè)包裝。

要設(shè)置自定義標(biāo)題,請(qǐng)使用NewRequest和DefaultClient.Do。

有關(guān)如何處理重定向的詳細(xì)信息,請(qǐng)參閱Client.Do方法文檔。

func PostForm

func PostForm(url string, data url.Values) (resp *Response, err error)

PostForm向指定的URL發(fā)布POST,并將數(shù)據(jù)的鍵和值作為請(qǐng)求主體進(jìn)行URL編碼。

Content-Type頭部設(shè)置為application/x-www-form-urlencoded。要設(shè)置其他標(biāo)題,請(qǐng)使用NewRequest和DefaultClient.Do。

當(dāng)err為零時(shí),resp總是包含非零的resp.Body。調(diào)用者在完成閱讀后應(yīng)關(guān)閉resp.Body。

PostForm是DefaultClient.PostForm的封裝。

有關(guān)如何處理重定向的詳細(xì)信息,請(qǐng)參閱Client.Do方法文檔。

func ReadResponse

func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)

ReadResponse讀取并返回來自r的HTTP響應(yīng)。req參數(shù)可選地指定對(duì)應(yīng)于此響應(yīng)的請(qǐng)求。如果為零,則假定有GET請(qǐng)求。讀完resp.Body后,客戶必須調(diào)用resp.Body.Close。通話結(jié)束后,客戶可以檢查resp.Trailer以查找響應(yīng)預(yù)告片中包含的key/value pairs。

func (*Response) Cookies

func (r *Response) Cookies() []*Cookie

Cookies分析并返回Set-Cookie標(biāo)題中設(shè)置的Cookie。

func (*Response) Location

func (r *Response) Location() (*url.URL, error)

位置返回響應(yīng)的“位置”標(biāo)題的URL(如果存在)。相對(duì)重定向相對(duì)于響應(yīng)的請(qǐng)求被解析。如果不存在位置標(biāo)題,則返回ErrNoLocation。

func (*Response) ProtoAtLeast

func (r *Response) ProtoAtLeast(major, minor int) bool

ProtoAtLeast報(bào)告響應(yīng)中使用的HTTP協(xié)議是否至少是major.minor。

func (*Response) Write

func (r *Response) Write(w io.Writer) error

Write r以HTTP/1.x服務(wù)器響應(yīng)格式寫入w,包括狀態(tài)行,標(biāo)題,正文和可選的trailer。

該方法參考響應(yīng)r的以下字段:

StatusCode
ProtoMajor
ProtoMinor
Request.Method
TransferEncoding
Trailer
Body
ContentLength
Header, values for non-canonical keys will have unpredictable behavior

響應(yīng)主體在發(fā)送后關(guān)閉。

type ResponseWriter

HTTP處理程序使用ResponseWriter接口來構(gòu)造HTTP響應(yīng)。

在Handler.ServeHTTP方法返回后,可能不會(huì)使用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)}

示例(Trailers)

HTTP Trailers是一組key/value pairs,如HTTP響應(yīng)之后的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.})}

type RoundTripper

RoundTripper是一個(gè)接口,表示執(zhí)行單個(gè)HTTP事務(wù)的能力,獲得給定請(qǐng)求的響應(yīng)。

RoundTripper必須是安全的,以供多個(gè)goroutine同時(shí)使用。

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的默認(rèn)實(shí)現(xiàn),由DefaultClient使用。它根據(jù)需要建立網(wǎng)絡(luò)連接,并將它們緩存以供隨后的調(diào)用重用。它按照$ 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

func NewFileTransport(fs FileSystem) RoundTripper

NewFileTransport返回一個(gè)新的RoundTripper,為所提供的FileSystem提供服務(wù)。返回的RoundTripper會(huì)忽略其傳入請(qǐng)求中的URL主機(jī)以及請(qǐng)求的大多數(shù)其他屬性。

NewFileTransport的典型用例是使用Transport注冊(cè)“文件”協(xié)議,如下所示:

t := &http.Transport{}t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))c := &http.Client{Transport: t}res, err := c.Get("file:///etc/passwd")...

type ServeMux

ServeMux是一個(gè)HTTP請(qǐng)求多路復(fù)用器。它將每個(gè)傳入請(qǐng)求的URL與注冊(cè)模式列表進(jìn)行匹配,并調(diào)用與該URL最匹配的模式的處理程序。

模式命名固定的,根源化的路徑,如“/favicon.ico”,或根源子樹,如“/images/”(注意尾部斜線)。較長(zhǎng)的模式優(yōu)先于較短的模式,因此,如果有處理程序注冊(cè)了“/images/”和“/images / thumbnails/”,后一個(gè)處理程序?qū)⒈徽{(diào)用以“/images/thumbnails/”開頭的路徑,前者將接收“/images/”子樹中任何其他路徑的請(qǐng)求。

請(qǐng)注意,由于以斜杠結(jié)尾的模式命名了一個(gè)有根的子樹,因此模式“/”會(huì)匹配所有未被其他已注冊(cè)模式匹配的路徑,而不僅僅是具有Path ==“/”的URL。

如果一個(gè)子樹已經(jīng)注冊(cè)并且接收到一個(gè)請(qǐng)求,并且命名了子樹根而沒有結(jié)尾的斜杠,ServeMux會(huì)將該請(qǐng)求重定向到子樹根(添加尾部斜線)。此行為可以通過單獨(dú)注冊(cè)路徑而不使用結(jié)尾斜杠來覆蓋。例如,注冊(cè)“/images/”會(huì)導(dǎo)致ServeMux將“/images”的請(qǐng)求重定向到“/images/”,除非單獨(dú)注冊(cè)了“/images”。

模式可以有選擇地以主機(jī)名開頭,只限制與主機(jī)上的URL匹配。特定于主機(jī)的模式優(yōu)先于一般模式,因此處理程序可能會(huì)注冊(cè)兩種模式“/codesearch”和“codesearch.google.com/”,而不會(huì)接管“ http://www.google.com/”的請(qǐng)求”。

ServeMux還負(fù)責(zé)清理URL請(qǐng)求路徑,重定向任何包含的請(qǐng)求?;?.元素或重復(fù)的斜杠到一個(gè)等效的,更干凈的URL。

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

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux分配并返回一個(gè)新的ServeMux。

func (*ServeMux) Handle

func (mux *ServeMux) Handle(pattern string, handler Handler)

Handle為給定模式注冊(cè)處理程序。如果處理程序已經(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 (*ServeMux) HandleFunc

func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc為給定模式注冊(cè)處理函數(shù)。

func (*ServeMux) Handler

func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)

Handler返回用于給定請(qǐng)求的處理程序,請(qǐng)參閱r.Method,r.Host和r.URL.Path。它總是返回一個(gè)非零處理程序。如果路徑不是其規(guī)范形式,則處理程序?qū)⑹且粋€(gè)內(nèi)部生成的處理程序,該處理程序?qū)⒅囟ㄏ虻揭?guī)范路徑。如果主機(jī)包含端口,則在匹配處理程序時(shí)將忽略該端口。

CONNECT請(qǐng)求的路徑和主機(jī)未改變。

處理程序還返回匹配請(qǐng)求的注冊(cè)模式,或者在內(nèi)部生成的重定向的情況下,返回跟隨重定向后匹配的模式。

如果沒有適用于請(qǐng)求的注冊(cè)處理程序,則Handler返回“未找到頁面”處理程序和空白模式。

func (*ServeMux) ServeHTTP

func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP將請(qǐng)求分派給其模式與請(qǐng)求URL最匹配的處理程序。

type Server

服務(wù)器定義運(yùn)行HTTP服務(wù)器的參數(shù)。服務(wù)器的零值是有效的配置。

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 (*Server) Close

func (srv *Server) Close() error

立即關(guān)閉關(guān)閉狀態(tài)StateNew,StateActive或StateIdle中的所有活動(dòng)net.Listeners和任何連接。要正常關(guān)機(jī),請(qǐng)使用關(guān)機(jī)。

關(guān)閉不會(huì)嘗試關(guān)閉(甚至不知道)任何被劫持的連接,例如WebSockets。

Close返回關(guān)閉服務(wù)器底層偵聽器返回的任何錯(cuò)誤。

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe監(jiān)聽TCP網(wǎng)絡(luò)地址srv.Addr,然后調(diào)用Serve處理傳入連接上的請(qǐng)求。接受的連接被配置為啟用TCP保持活動(dòng)。如果srv.Addr為空,則使用“:http”。ListenAndServe總是返回一個(gè)非零錯(cuò)誤。

func (*Server) ListenAndServeTLS

func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS偵聽TCP網(wǎng)絡(luò)地址srv.Addr,然后調(diào)用Serve處理傳入TLS連接上的請(qǐng)求。接受的連接被配置為啟用TCP保持活動(dòng)。

如果服務(wù)器的TLSConfig.Certificates和TLSConfig.GetCertificate都不填充,則必須提供包含服務(wù)器的證書和匹配私鑰的文件名。如果證書由證書頒發(fā)機(jī)構(gòu)簽署,則certFile應(yīng)該是服務(wù)器證書,任何中間器和CA證書的串聯(lián)。

如果srv.Addr為空,則使用“:https”。

ListenAndServeTLS總是返回一個(gè)非零錯(cuò)誤。

func (*Server) RegisterOnShutdown

func (srv *Server) RegisterOnShutdown(f func())

RegisterOnShutdown注冊(cè)一個(gè)函數(shù)來調(diào)用Shutdown。這可以用于正常關(guān)閉經(jīng)過NPN/ALPN協(xié)議升級(jí)或已被劫持的連接。此功能應(yīng)啟動(dòng)特定于協(xié)議的正常關(guān)機(jī),但不應(yīng)等待關(guān)機(jī)完成。

func (*Server) Serve

func (srv *Server) Serve(l net.Listener) error

Serve接受Listener l上的傳入連接,為每個(gè)服務(wù)器創(chuàng)建一個(gè)新的服務(wù)程序。服務(wù)程序讀取請(qǐng)求,然后調(diào)用srv.Handler來回復(fù)它們。

對(duì)于HTTP/2支持,在調(diào)用Serve之前,應(yīng)將srv.TLSConfig初始化為提供的偵聽器的TLS配置。如果srv.TLSConfig非零,并且在Config.NextProtos中不包含字符串“h2”,則不啟用HTTP/2支持。

始終返回非零錯(cuò)誤。關(guān)機(jī)或關(guān)閉后,返回的錯(cuò)誤是ErrServerClosed。

func (*Server) ServeTLS

func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error

ServeTLS接受Listener l上的傳入連接,為每個(gè)連接創(chuàng)建一個(gè)新的服務(wù)例程。服務(wù)程序讀取請(qǐng)求,然后調(diào)用srv.Handler來回復(fù)它們。

此外,如果服務(wù)器的TLSConfig.Certificates和TLSConfig.GetCertificate都未被填充,則必須提供包含服務(wù)器的證書和匹配私鑰的文件。如果證書由證書頒發(fā)機(jī)構(gòu)簽署,則certFile應(yīng)該是服務(wù)器的串聯(lián)證書,任何中間件和CA的證書。

對(duì)于HTTP/2支持,在調(diào)用Serve之前,應(yīng)將srv.TLSConfig初始化為提供的偵聽器的TLS配置。如果srv.TLSConfig非零,并且在Config.NextProtos中不包含字符串“h2”,則不啟用HTTP/2支持。

ServeTLS總是返回一個(gè)非零錯(cuò)誤。關(guān)機(jī)或關(guān)閉后,返回的錯(cuò)誤是ErrServerClosed。

func (*Server) SetKeepAlivesEnabled

func (srv *Server) SetKeepAlivesEnabled(v bool)

SetKeepAlivesEnabled控制是否啟用HTTP保持活動(dòng)。默認(rèn)情況下,保持活動(dòng)狀態(tài)始終處于啟用狀態(tài)。在關(guān)閉過程中,只有非常資源受限的環(huán)境或服務(wù)器才能禁用它們。

func (*Server) Shutdown

func (srv *Server) Shutdown(ctx context.Context) error

關(guān)機(jī)正常關(guān)閉服務(wù)器而不中斷任何活動(dòng)連接。首先關(guān)閉所有打開的監(jiān)聽程序,然后關(guān)閉所有空閑連接,然后無限期地等待連接返回到空閑狀態(tài)然后關(guān)閉。如果提供的上下文在關(guān)閉完成之前到期,Shutdown將返回上下文的錯(cuò)誤,否則返回關(guān)閉服務(wù)器的底層偵聽器返回的任何錯(cuò)誤。

當(dāng)調(diào)用Shutdown時(shí),Serve,ListenAndServe和ListenAndServeTLS立即返回ErrServerClosed。確保程序不會(huì)退出,而是等待Shutdown返回。

關(guān)機(jī)不會(huì)嘗試關(guān)閉或等待被劫持的連接,如WebSockets。如果需要,Shutdown的調(diào)用者應(yīng)該分別通知關(guān)閉的這種長(zhǎng)期連接并等待它們關(guān)閉。

type Transport

Transport是RoundTripper的一個(gè)實(shí)現(xiàn),它支持HTTP,HTTPS和HTTP代理(對(duì)于使用CONNECT的HTTP或HTTPS)。

默認(rèn)情況下,傳輸緩存連接以供將來重新使用。訪問多臺(tái)主機(jī)時(shí)可能會(huì)留下許多開放連接??梢允褂脗鬏?shù)腃loseIdleConnections方法和MaxIdleConnsPerHost和DisableKeepAlives字段管理此行為。

運(yùn)輸應(yīng)該重用,而不是根據(jù)需要?jiǎng)?chuàng)建。運(yùn)輸對(duì)于多個(gè)goroutines并發(fā)使用是安全的。

傳輸是用于發(fā)出HTTP和HTTPS請(qǐng)求的低級(jí)原語。對(duì)于高級(jí)功能(如Cookie和重定向),請(qǐng)參閱客戶端。

Transport對(duì)于HTTP URL使用HTTP/1.1,對(duì)于HTTPS URL使用HTTP/1.1或HTTP/2,具體取決于服務(wù)器是否支持HTTP/2以及如何配置Transport。DefaultTransport支持HTTP/2。要在傳輸上明確啟用HTTP/2,請(qǐng)使用golang.org/x/net/http2并調(diào)用ConfigureTransport。有關(guān)HTTP/2的更多信息,請(qǐng)參閱軟件包文檔。

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 (*Transport) CancelRequest

func (t *Transport) CancelRequest(req *Request)

CancelRequest通過關(guān)閉其連接來取消正在進(jìn)行的請(qǐng)求。只有在RoundTrip返回后才能調(diào)用CancelRequest。

已棄用:使用Request.WithContext來創(chuàng)建具有可取消上下文的請(qǐng)求。CancelRequest無法取消HTTP/2請(qǐng)求。

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections關(guān)閉以前連接的所有連接,但是現(xiàn)在處于“保持活動(dòng)”狀態(tài)。它不會(huì)中斷當(dāng)前正在使用的任何連接。

func (*Transport) RegisterProtocol

func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)

RegisterProtocol用方案注冊(cè)一個(gè)新的協(xié)議。運(yùn)輸將使用給定的方案將請(qǐng)求傳遞給rt。模擬HTTP請(qǐng)求語義是rt的責(zé)任。

其他軟件包可以使用RegisterProtocol來提供“ftp”或“file”等協(xié)議方案的實(shí)現(xiàn)。

如果rt.RoundTrip返回ErrSkipAltProtocol,Transport將為該請(qǐng)求處理RoundTrip本身,就好像該協(xié)議未注冊(cè)一樣。

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *Request) (*Response, error)

RoundTrip實(shí)現(xiàn)RoundTripper接口。

對(duì)于更高級(jí)別的HTTP客戶端支持(如處理Cookie和重定向),請(qǐng)參閱獲取,發(fā)布和客戶端類型。

子目錄

Name

Synopsis

cgi

cgi包實(shí)現(xiàn)了RFC 3875中規(guī)定的CGI(通用網(wǎng)關(guān)接口)

cookiejar

包c(diǎn)ookiejar實(shí)現(xiàn)了符合內(nèi)存RFC 6265的http.CookieJar。

fcgi

fcgi包實(shí)現(xiàn)FastCGI協(xié)議。

httptest

httptest包提供了用于HTTP測(cè)試的實(shí)用程序。

httptrace

包httptrace提供跟蹤HTTP客戶端請(qǐng)求中的事件的機(jī)制。

httputil

軟件包httputil提供HTTP實(shí)用程序功能,補(bǔ)充了net/http軟件包中較常見的功能。

pprof

軟件包pprof通過其HTTP服務(wù)器運(yùn)行時(shí)分析數(shù)據(jù)以pprof可視化工具預(yù)期的格式提供服務(wù)。

Previous article: Next article: