Go Language net/http interpretation.

Source: Internet
Author: User
Tags key string setcookie

Tag:second   ast    return value    sse    networking     oct    specify    requested   esc   

The HTTP package provides methods and functions to implement the HTTP client and server. , Post, postform use to implement HTTP requests: 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"}}) after the end of use, the client's response body should be closed: resp, err: = http. Get ("http://example.com/") if err! = Nil {//handle Error}defer resp. Body.close () body, err: = Ioutil. ReadAll (resp. Body) in order to control the HTTP client's headers, redirection scheme, and other settings. You need to create a 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) to control agents, Secure Sockets Layer settings, maintain connections, compression, and other settings. You need to create a transport:tr: = &http. transport{tlsclientconfig: &tls. Config{rootcas:pool}, Disablecompression:true,}client: = &http. CLIENT{TRANSPORT:TR}RESP, Err: = client. The Get ("https://example.com") client and transport are able to safely perform multi-threaded concurrency. BecauseThis should be used more than once in order to improve efficiency. Listenandserve creates an HTTP Server based on the provided address and handler. Handler is usually nil. Nil means using Defaultservemux.

Ability to use Handle and Handlefunc to add new Handler:http.Handle ("/foo", Foohandler) http to Defaultservemux. 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)) a lot of other control over the behavior of the server needs to be done by creating servers: s: = &http. server{Addr: ": 8080", Handler:myhandler, Readtimeout:10 * time. Second, Writetimeout:10 * time. Second, Maxheaderbytes:1 << 20,}log. Fatal (S.listenandserve ()) index Constantsvariablesfunc Canonicalheaderkey (s string) Stringfunc detectcontenttype (data [] BYTE) Stringfunc error (w responsewriter, error string, code int) Func Handle (pattern string, handler handler) Func Handlefun C (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 Parsetim E (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 (n Ame string) (File, error) type Filetype filesystemtype flushertype Handler func fileserver (root FileSystem) Handler F UNC Notfoundhandler () Handler func redirecthandler (URL string, code int) Handler func stripprefix (prefix string, h H Andler) 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 F UNC (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 Requ EST 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) (*coo Kie, 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, E RR 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 Fun C Newservemux () *servemux func (Mux *servemux) Handle (pattern string, handler handler) func (Mux *servemux) handlefu NC (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 () The 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 stri Ng, RT Roundtripper) func (t *transport) roundtrip (req *request) (resp *response, err Error) Examplesfileservergethijack Erpackage fileschunked.go client.go cookie.go doc.go filetransport.go fs.go header.go jar.go lex.go request.go response.g o server.go sniff.go status.go transfer.go transport.go Const const (statuscontinue = Statusswitchingproto cols = 101 Statusok = statuscreated = 201 Statusaccepted = 202 Statusnonauthoritativeinfo = 203 Statusnocontent = 204 Statusresetcontent = 205 Statuspartialc ontent = 206 Statusmultiplechoices = statusmovedpermanently = 301 Statusfound = 302 S Tatusseeother = 303 Statusnotmodified = 304 Statususeproxy = 305 Statustemporaryredirect = 307 Statusbadrequest = statusunauthorized = 401 Statuspaymentrequired = 402 Status Forbidden = 403 Statusnotfound = 404 statusmethodnotallowed = 405 statusnotacceptable = 406 statusproxyauthrequired = 407 Statusrequesttimeout = 408 Statusconflict = 409 Statusgone = 410 statuslengthrequired = 411 Statuspreconditionfailed = 412 Statusrequestentitytoolarge = 413 statusrequ Esturitoolong = 414 Statusunsupportedmediatype = 415 Statusrequestedrangenotsatisfiable = 416 statusexpectationfailed = 417 Statusteapot = 418 Statusinternalservererror = 50 0 statusnotimplemented = 501 Statusbadgateway = 502 Statusserviceunavailable = 503 Statusgatewaytimeout = 504 statushttpversionnotsupported = 505) above is the HTTP status code specified in RFC 2616 const DEFAULTMAXHEADERBYTES = 1 << 20//1 Mbdefaultmaxheaderbytes is the maximum consent value of the HTTP request header and can be overridden by setting the server.maxheaderbytes. Const DEFAULTMAXIDLECONNSPERHOST = 2DefaultMaxIdleConnsPerHost is the transport default Unit address maximum spare connection value.

Const TIMEFORMAT = "Mon, 2006 15:04:05 GMT" TimeFormat is a format for the use of time. Used to split (parse) and format (Time.time.Format) time when parsing or combining the time data of an HTTP header. Similar time. RFC1123 but hard-coded to GMT as the time domain. Variable var (errheadertoolong = &protocolerror{"header Too Long"} Errshortbody = &protocolerror {"Entity body Too Short"} errnotsupported = &protocolerror{"feature not Supported"} Errunexpectedtrailer = &protocolerror{"tra Iler header without chunked transfer encoding "} Errmissingcontentlength = &protocolerror{" Missing contentlength in HEAD response "} Errnotmultipart = &protocolerror{" request Content-type isn ' t multipart/form-data "} Errmi Ssingboundary = &protocolerror{"No multipart boundary param Content-type"}) var (errwriteafterflush = ERRORS.N EW ("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 service-side declared error message.

var defaultclient = &client{}defaultclient is the default Client and is used for operations such as, post, and so on.

var Defaultservemux = Newservemux () Defaultservemux is the default Servemux. For use by the server. var errbodyreadafterclose = errors. New ("Http:invalid read on closed request Body") returns Errbodyreadafterclose when the requested body is read after it is closed. Typically after an HTTP handler has run the Responsewriter Writeheader or write method of the request body. This error is caused when the request body is read again. var errhandlertimeout = errors. New ("Http:handler timeout") returns Errhandlertimeout when the Handler of Responsewriter's write call takes a timeout. var errlinetoolong = errors. New ("header line too long") var errmissingfile = errors. New ("Http:no such file") The Formfile function returns Errmissingfile when the supplied file address is wrong (not the file address or the file does not exist). 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 returns the standard format of the string S. The function converts the first letter of the word and the first letter of the hyphen to uppercase, and the rest to lowercase. For example, the standard version of "Accept-encoding" is "accept-encoding".

Func detectcontenttypefunc detectcontenttype (data []byte) Stringdetectcontenttype use HTTP// mimesniff.spec.whatwg.org/describes the algorithm to determine the content type of the given data (Content-type).

It evaluates up to 512 bytes at the beginning. This function must return a valid Multipurpose Internet Mail Extension (MIME) Type: Suppose the function cannot determine the type of understanding. It returns "Application/octet-stream". Func errorfunc Error (w responsewriter, error string, code int) The Error function returns an HTTP error code and a specific error message to the request. Func handlefunc Handle (pattern string, handler handler) Handle for a given pattern (pattern) in Defaultservemux (handler). Servemux's documentation explains how pattern works. Func handlefuncfunc Handlefunc (pattern string, handler func (Responsewriter, *request)) Handlefunc a response function (handler function) for a given pattern (pattern) in Defaultservemux. Func listenandservefunc listenandserve (addr string, handler handler) The Errorlistenandserve listens to the TCP network address and calls the server with handler to respond to requests made in the incoming connection.

The

Handler is usually nil, and Defaultservemux is used at this time. A simple Server sample: Package main import ("io" "net/http" "Log")//Hello World, the Web Serverfunc helloserver (w htt P.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 St Ring, Handler handler) ERRORLISTENANDSERVETLS and Listenandserve Act the same, but it requires an HTTPS connection.

In addition You must provide the file that includes the certificate and the private key that matches the service desk (server). Assuming that the certificate is issued by an authoritative authority, the certificate file must be a service desk certificate that is immediately cascaded with the CA certificate. A simple Server sample: Import ("Log" "Net/http") Func handler (W http. Responsewriter, req *http. Request) {W.header (). Set ("Content-type", "Text/plain") W.write ([]byte ("This is a example server.\n")} Func Main () {http. Handlefunc ("/", handler) log. Printf ("About-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)}} can use Generate_cert.go under the Crypto/tls folder to generate Cert.pem and KEY.PEM. Func maxbytesreaderfunc Maxbytesreader (w responsewriter, R io. Readcloser, n Int64) io. Readclosermaxbytesreader is similar to Io.limitreader but is designed to limit the size of the received request body. is different from IO. The return value of Limitreader,maxbytesreader is a readcloser. A non-eof error is returned when the read exceeds the limit, and a potential reader (function/process) is closed when its Close method is called. Maxbytesreader protects the client from wasted server resources caused by accidental or maliciously transmitted long data requests. Func notfoundfunc NotFound (w responsewriter, R *request) NotFound an error (write responsewriter) for the request to return an HTTP 404 resource not found. Func ParsehttpversiOnfunc parsehttpversion (vers string) (major, minor int, OK bool) parsehttpversion function parses and decomposes the HTTP version number string. "http/1.0" returns (1, 0, true). Func parsetimefunc parsetime (text string) (t time. Time, err error) Parsetime attempts to http/1.1 three formats supported by TimeFormat, time. RFC850, time. Each of the ansic to decompose the time head (such as Date:header).

Func proxyfromenvironmentfunc proxyfromenvironment (req *request) (*url. URL, error) proxyfromenvironment returns the proxy URL for the given request based on the environment variables $http_proxy and $no_proxy (or $http_proxy and $no_proxy). Assume that the global agent is illegal to return an error.

The null (nil) URL and the empty error code are returned if the environment does not have a proxy set or if the proxy set cannot be used for the given request. Func proxyurlfunc Proxyurl (Fixedurl *url. URL) func (*request) (*url. URL, error) Proxyurl returns an agent function, which is typically used in transport, to accept the request and always returns a (post-proxy) address. Func redirectfunc Redirect (w responsewriter, R *request, urlstr string, code int) Redirect returns request for a redirect address related to the requested address. Func servefunc Serve (l net. Listener, Handler handler) Errorserve accept the HTTP connection received by Listener L and create a new thread for each connection. The service thread reads each request and calls handler to respond.

Handler is usually nil, and Defaultservemux is used at this time. Func servecontentfunc servecontent (w responsewriter, req *request, name string, Modtime time. Time, Content io. Readseeker) Servecontent uses the content provided by the Readseeker to provide feedback to the request. This function is relative to IO. The main advantage of copy is that it can manipulate random requests and set MIME types. Operation If-modified-since Request. Assume that the content type row for the header of Reponse is not set. This function first tries to judge from name's file extension, assuming that it fails to read the first data segment of Readseeker sent to the Detectcontenttype function. In addition, the name parameter is useless, and in certain cases it can be empty and will never be added to the reponse. Assuming that the Modtime parameter is nonzero, Servecontent includes a last-modified row in the header of response that includes the number of references.

Assuming that the header of the request includes if-modified-since rows, Servecontent uses Modtime to determine that all content should be sent using. The Seek method of the content parameter must be valid: Servecontent determines the size of the content by shifting to the end. Suppose the caller sets the W's ETag Header,servecontent will pass through it, using If-range and If-none-match (the reference line in the header) to process the request.

Note: OS. The file package implements the Io.readseeker interface. Func servefilefunc Servefile (w responsewriter, R *request, name string) Servefile the contents of the file specified by the request return name. Func setcookiefunc Setcookie (w responsewriter, Cookie *cookie) Setcookie adds a cookie to the provided Responseweriter header.

Func statustextfunc statustext (code int) Stringstatustext returns the text information of the HTTP status code, assuming that the status code is unknown to return an empty string.


Go Language net/http interpretation.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.