Go語言net/http 解讀.

來源:互聯網
上載者:User

標籤:second   ast   傳回值   sse   連網   oct   指定   requested   esc   

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())索引ConstantsVariablesfunc CanonicalHeaderKey(s string) stringfunc DetectContentType(data []byte) stringfunc 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) errorfunc ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) errorfunc MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloserfunc 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) errorfunc 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) stringtype 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() stringtype CookieJartype Dir func (d Dir) Open(name string) (File, error)type Filetype FileSystemtype Flushertype 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) Handlertype 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) errortype Hijackertype ProtocolError func (err *ProtocolError) Error() stringtype 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) errortype 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) errortype ResponseWritertype RoundTripper func NewFileTransport(fs FileSystem) RoundTrippertype 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) errortype Transport func (t *Transport) CloseIdleConnections() func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) func (t *Transport) RoundTrip(req *Request) (resp *Response, err error)ExamplesFileServerGetHijackerPackage fileschunked.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 MBDefaultMaxHeaderBytes是HTTP要求標頭的最大同意值,能夠通過設定Server.MaxHeaderBytes來重寫。const DefaultMaxIdleConnsPerHost = 2DefaultMaxIdleConnsPerHost是Transport預設的單位地址最大空暇串連值。

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服務端聲明的錯誤資訊。

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 CanonicalHeaderKeyfunc CanonicalHeaderKey(s string) stringCanonicalHeaderKey返回字串s的標準格式。函數將單詞的首字母和連字號後的首字母轉為大寫,其餘都轉為小寫。比如,"accept-encoding"的標準版是"Accept-Encoding"。

func DetectContentTypefunc DetectContentType(data []byte) stringDetectContentType使用http://mimesniff.spec.whatwg.org/ 描寫敘述的演算法來確定給定資料的內容類型(Content-Type)。

它最多評估開始的512位元組。本函數一定會返回有效多用途互連網郵件擴充(MIME)類型:假設函數無法確定明白的類型。它返回"application/octet-stream"。func Errorfunc Error(w ResponseWriter, error string, code int)Error函數向請求返回HTTP錯誤碼和具體的錯誤資訊。func Handlefunc Handle(pattern string, handler Handler)Handle為DefaultServeMux中給定的模式(pattern)注冊反應器(handler)。ServeMux的說明文檔解說了pattern是怎樣工作的。func HandleFuncfunc HandleFunc(pattern string, handler func(ResponseWriter, *Request))HandleFunc為DefaultServeMux中給定的模式(pattern)注冊反應函數(handler function)。func ListenAndServefunc ListenAndServe(addr string, handler Handler) errorListenAndServe監聽TCP網路地址而且呼叫具有handler的Server對在進入串連發出的請求作出反應。

Handler通常是nil,此時使用DefaultServeMux。一個簡單的server範例:package main import ( "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) err := http.ListenAndServe(":12345", nil) if err != nil { log.Fatal("ListenAndServe: ", err) }}func ListenAndServeTLSfunc ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) errorListenAndServeTLS和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 MaxBytesReaderfunc MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloserMaxBytesReader相似於io.LimitReader但被設計用來限定接收的請求體的大小。不同於io.LimitReader,MaxBytesReader的傳回值是一個ReadCloser。當讀取超過限制時會返回non-EOF錯誤而且當它的關閉方法調用時會關閉潛在的讀取者(函數/進程)。MaxBytesReader保護用戶端避免偶然或者惡意發送的長資料請求導致的server資源的浪費。func NotFoundfunc NotFound(w ResponseWriter, r *Request)NotFound對請求返回一個HTTP 404 未發現資源的錯誤(寫入ResponseWriter)。func ParseHTTPVersionfunc ParseHTTPVersion(vers string) (major, minor int, ok bool)ParseHTTPVersion函數分析並分解HTTP版本號碼字串。"HTTP/1.0"返回(1, 0, true)。func ParseTimefunc ParseTime(text string) (t time.Time, err error)ParseTime嘗試HTTP/1.1支援的三種格式TimeFormat、time.RFC850、time.ANSIC的每一種來分解時間頭(比如 Date: header)。

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

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

Handler參數通常是nil,此時使用DefaultServeMux。func ServeContentfunc 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 ServeFilefunc ServeFile(w ResponseWriter, r *Request, name string)ServeFile對請求返回name參數指定的檔案的內容。func SetCookiefunc SetCookie(w ResponseWriter, cookie *Cookie)SetCookie給提供的ResponseWeriter的頭部加入cookie。

func StatusTextfunc StatusText(code int) stringStatusText返回HTTP狀態代碼的文本資訊,假設狀態代碼未知返回Null 字元串。


Go語言net/http 解讀.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.