首页 > 代码库 > Go语言net/http 解读.
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默认的单位地址最大空暇连接值。
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 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)。
它最多评估開始的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。假设全局代理非法会返回错误。
假设环境没有设置代理或者设置的代理不能用于给出的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状态码的文本信息,假设状态码未知返回空字符串。
Go语言net/http 解读.