Go語言net/http 解讀.

Http包提供實現HTTP客戶端和服務端的方法與函數。

Get、Head、Post、PostForm配合使用實現HTTP請求:

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客戶端的headers、重定向方案和其餘設定。需要建立一個Client:

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)

爲了控制代理、安全套接層設置、保持鏈接、壓縮和其餘設定。需要建立一個Transport:

tr := &http.Transport{

     TLSClientConfig:    &tls.Config{RootCAs: pool},

     DisableCompression: true,

}

client := &http.Client{Transport: tr}

resp, err := client.Get("https://example.com")

Client和Transport可以安全的進行多線程的併發。所以爲了提升效率應該一次創建屢次使用。

ListenAndServe依據提供的地址和handler建立一個HTTP Server。Handler一般是nil。nil表示使用DefaultServeMux。

可以使用Handle和HandleFunc給DefaultServeMux加入新的handler: 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)) 不少其餘的對服務端行爲的控制需要經過建立Server來實現: s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) 索引 Constants Variables 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 string, certFile string, 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, urlStr 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 SetCookie(w ResponseWriter, cookie *Cookie) func StatusText(code int) string type Client func (c *Client) Do(req *Request) (resp *Response, err 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, bodyType string, body io.Reader) (resp *Response, err error) func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) 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 (err *ProtocolError) Error() string type Request func NewRequest(method, urlStr string, body io.Reader) (*Request, error) func ReadRequest(b *bufio.Reader) (req *Request, err error) func (r *Request) AddCookie(c *Cookie) 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() (err 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) 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, bodyType 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) (resp *Response, err 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) ListenAndServe() error func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error func (srv *Server) Serve(l net.Listener) error type Transport func (t *Transport) CloseIdleConnections() func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) Examples FileServer Get Hijacker Package files chunked.go client.go cookie.go doc.go filetransport.go fs.go header.go jar.go lex.go request.go response.go server.go sniff.go status.go transfer.go transport.go 常量 const ( StatusContinue = 100 StatusSwitchingProtocols = 101 StatusOK = 200 StatusCreated = 201 StatusAccepted = 202 StatusNonAuthoritativeInfo = 203 StatusNoContent = 204 StatusResetContent = 205 StatusPartialContent = 206 StatusMultipleChoices = 300 StatusMovedPermanently = 301 StatusFound = 302 StatusSeeOther = 303 StatusNotModified = 304 StatusUseProxy = 305 StatusTemporaryRedirect = 307 StatusBadRequest = 400 StatusUnauthorized = 401 StatusPaymentRequired = 402 StatusForbidden = 403 StatusNotFound = 404 StatusMethodNotAllowed = 405 StatusNotAcceptable = 406 StatusProxyAuthRequired = 407 StatusRequestTimeout = 408 StatusConflict = 409 StatusGone = 410 StatusLengthRequired = 411 StatusPreconditionFailed = 412 StatusRequestEntityTooLarge = 413 StatusRequestURITooLong = 414 StatusUnsupportedMediaType = 415 StatusRequestedRangeNotSatisfiable = 416 StatusExpectationFailed = 417 StatusTeapot = 418 StatusInternalServerError = 500 StatusNotImplemented = 501 StatusBadGateway = 502 StatusServiceUnavailable = 503 StatusGatewayTimeout = 504 StatusHTTPVersionNotSupported = 505 ) 以上都是RFC 2616規定的HTTP狀態碼 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB DefaultMaxHeaderBytes是HTTP請求頭的最大讚成值,可以經過設定Server.MaxHeaderBytes來重寫。 const DefaultMaxIdleConnsPerHost = 2 DefaultMaxIdleConnsPerHost是Transport默認的單位地址最大空暇鏈接值。html

const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" TimeFormat是使用時間的格式。當分析或者結合HTTP頭的時間數據時,用來分拆(Parse)和格式化(time.time.Format)時間。類似time.RFC1123但硬編碼爲GMT做爲時間域。 變量 var ( ErrHeaderTooLong = &ProtocolError{"header too long"} ErrShortBody = &ProtocolError{"entity body too short"} ErrNotSupported = &ProtocolError{"feature not supported"} ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"} ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"} ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"} ErrMissingBoundary = &ProtocolError{"no multipart boundary param Content-Type"} ) var ( ErrWriteAfterFlush = errors.New("Conn.Write called after Flush") ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body") ErrHijacked = errors.New("Conn has been hijacked") ErrContentLength = errors.New("Conn.Write wrote more than the declared Content-Length") ) HTTP服務端聲明的錯誤信息。web

var DefaultClient = &Client{} DefaultClient是默認的Client,供Get、Head、Post等操做使用。算法

var DefaultServeMux = NewServeMux() DefaultServeMux是默認的ServeMux。供Server使用。 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed request Body") 當請求體被關閉後讀取它時,返回ErrBodyReadAfterClose。通常在某個HTTP handler運行了請求體的ResponseWriter的WriteHeader或Write方法後。再次讀取請求體時,就會致使這個錯誤。 var ErrHandlerTimeout = errors.New("http: Handler timeout") 當ResponseWriter的Write操做呼叫的handler發生超時後,就會返回ErrHandlerTimeout。 var ErrLineTooLong = errors.New("header line too long") var ErrMissingFile = errors.New("http: no such file") 當提供的文件地址出現錯誤(不是文件地址或者文件不存在)時,FormFile函數將返回ErrMissingFile。 var ErrNoCookie = errors.New("http: named cookie not present") var ErrNoLocation = errors.New("http: no Location header in response") func CanonicalHeaderKey func CanonicalHeaderKey(s string) string CanonicalHeaderKey返回字符串s的標準格式。函數將單詞的首字母和連字符後的首字母轉爲大寫,其他都轉爲小寫。好比,"accept-encoding"的標準版是"Accept-Encoding"。安全

func DetectContentType func DetectContentType(data []byte) string DetectContentType使用http://mimesniff.spec.whatwg.org/ 描寫敘述的算法來肯定給定數據的內容類型(Content-Type)。cookie

它最多評估開始的512字節。本函數必定會返回有效的多用途互聯網郵件擴展(MIME)類型:假設函數沒法肯定明白的類型。它返回"application/octet-stream"。 func Error func Error(w ResponseWriter, error string, code int) Error函數向請求返回HTTP錯誤碼和具體的錯誤信息。 func Handle func Handle(pattern string, handler Handler) Handle爲DefaultServeMux中給定的模式(pattern)註冊反應器(handler)。ServeMux的說明文檔解說了pattern是怎樣工做的。 func HandleFunc func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) HandleFunc爲DefaultServeMux中給定的模式(pattern)註冊反應函數(handler function)。 func ListenAndServe func ListenAndServe(addr string, handler Handler) error ListenAndServe監聽TCP網絡地址並且呼叫具備handler的Server對在進入鏈接發出的請求做出反應。網絡

Handler一般是nil,此時使用DefaultServeMux。 一個簡單的server樣例: package main import ( "io" "net/http" "log" ) // hello world, the web server func HelloServer(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, world!\n") } func main() { http.HandleFunc("/hello", HelloServer) err := http.ListenAndServe(":12345", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } func ListenAndServeTLS func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error ListenAndServeTLS和ListenAndServe做用一致,但它要求HTTPS鏈接。多線程

此外。必須提供包括證書的文件和與服務檯(server)匹配的私鑰。假設證書是權威機構簽發的,則證書文件必須是服務檯證書緊跟CA證書的級聯。 一個簡單的server樣例: 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) if err != nil { log.Fatal(err) } } 可以使用crypto/tls文件夾下的generate_cert.go來生成cert.pem和key.pem。 func MaxBytesReader func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser MaxBytesReader類似於io.LimitReader但被設計用來限定接收的請求體的大小。不一樣於io.LimitReader,MaxBytesReader的返回值是一個ReadCloser。當讀取超過限制時會返回non-EOF錯誤並且當它的關閉方法調用時會關閉潛在的讀取者(函數/進程)。 MaxBytesReader保護客戶端避免偶然或者惡意發送的長數據請求致使的server資源的浪費。 func NotFound func NotFound(w ResponseWriter, r *Request) NotFound對請求返回一個HTTP 404 未發現資源的錯誤(寫入ResponseWriter)。 func ParseHTTPVersion func ParseHTTPVersion(vers string) (major, minor int, ok bool) ParseHTTPVersion函數分析並分解HTTP版本號字符串。"HTTP/1.0"返回(1, 0, true)。 func ParseTime func ParseTime(text string) (t time.Time, err error) ParseTime嘗試HTTP/1.1支持的三種格式TimeFormat、time.RFC850、time.ANSIC的每一種來分解時間頭(好比 Date: header)。併發

func ProxyFromEnvironment func ProxyFromEnvironment(req *Request) (*url.URL, error) ProxyFromEnvironment依據環境變量$HTTP_PROXY和$NO_PROXY (或$http_proxy和$no_proxy)返回給定request的代理url。假設全局代理非法會返回錯誤。app

假設環境沒有設置代理或者設置的代理不能用於給出的request則返回空(nil)url和空錯誤碼。 func ProxyURL func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) ProxyURL返回一個代理函數,這個代理函數(通常在Transport中使用)接受請求,並老是返回一個(代理後的)地址。 func Redirect func Redirect(w ResponseWriter, r *Request, urlStr string, code int) Redirect返回request一個與請求地址有關的重定向地址。 func Serve func Serve(l net.Listener, handler Handler) error Serve接受Listener l接收到的HTTP鏈接,併爲每一個鏈接建立一個新的線程。服務線程會讀取每一個請求,調用handler作出迴應。函數

Handler參數一般是nil,此時使用DefaultServeMux。 func ServeContent func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) ServeContent使用提供的ReadSeeker的內容反饋給請求。本函數相對io.Copy的主要長處是它可以較好的操做隨機請求、設定MIME類型。操做If-Modified-Since請求。 假設reponse的header的內容類型行未設定。本函數首先嚐試從name的文件擴展名進行判斷,假設失敗則讀取ReadSeeker的第一數據段發送給DetectContentType函數判斷。此外name參數是沒用的,特定狀況下它可以是空的並且從不會加入reponse中。 假設modtime參數非零,ServeContent會在response的header中包括一個包括該參數的Last-Modified行。

假設request的header包括If-Modified-Since行,ServeContent使用modtime參數來肯定使用應該發送全部內容。 content參數的Seek方法必須有效:ServeContent經過移位到結尾來肯定content的大小。 假設呼叫者設定了w's ETag header,ServeContent將經過它,使用If-Range和If-None-Match(header中的參數行)來處理request。

注意:os.File包實現了io.ReadSeeker接口。 func ServeFile func ServeFile(w ResponseWriter, r *Request, name string) ServeFile對請求返回name參數指定的文件的內容。 func SetCookie func SetCookie(w ResponseWriter, cookie *Cookie) SetCookie給提供的ResponseWeriter的頭部加入cookie。

func StatusText func StatusText(code int) string StatusText返回HTTP狀態碼的文本信息,假設狀態碼未知返回空字符串。

相關文章
相關標籤/搜索