Go Language net/http interpretation.

Source: Internet
Author: User
Tags key string setcookie

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) to control HTTP client headers, redirection schemes, 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 the transport can safely perform multithreading concurrently, 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 a nil,nil that uses Defaultservemux. You can use Handle and handlefunc to add a 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) more control over the service-side behavior is required by creating the server: 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 Pa Rsetime (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) O     Pen (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 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 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) (*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, 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 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 () 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) Examplesfileservergeth Ijackerpackage fileschunked.go client.go cookie.go doc.go filetransport.go fs.go header.go jar.go lex.go request.go respo Nse.go server.go sniff.go status.go transfer.go transport.go Const const (statuscontinue = statusswitching protocols = 101 Statusok = statuscreated = 201 Statusaccepted = 20 2 Statusnonauthoritativeinfo = 203 Statusnocontent = 204 Statusresetcontent = 205 Statuspar     tialcontent = 206 Statusmultiplechoices = 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 statusconf    Lict = 409 Statusgone = 410 statuslengthrequired = 411            statuspreconditionfailed = 412 Statusrequestentitytoolarge = 413 Statusrequesturitoolong            = 414 Statusunsupportedmediatype = 415 statusrequestedrangenotsatisfiable = 416 statusexpectationfailed = 417 Statusteapot = 418 Statusinternalservererror = Statusnotimplemente D = 501 StatUsbadgateway = 502 Statusserviceunavailable = 503 Statusgatewaytimeout = 504 Statushtt pversionnotsupported = 505) above is the HTTP status code specified in RFC 2616 const DEFAULTMAXHEADERBYTES = 1 <<//1 mbdefaultmaxheaderbytes is the maximum allowable value for the HTTP request header, which can be overridden by setting server.maxheaderbytes. Const DEFAULTMAXIDLECONNSPERHOST = 2DefaultMaxIdleConnsPerHost is the transport default Unit address maximum idle 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 to 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 "} 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 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. This error is typically caused when the request body is read again after an HTTP handler executes the Responsewriter Writeheader or write method of the request body. 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 (Content-type) of a given data. It evaluates up to 512 bytes at the beginning. This function must return a valid Multipurpose Internet Mail Extension (MIME) Type: If the function cannot determine an explicit type, it returns "Application/octet-stream". Func errorfunc Error (w responsewriter, error string, code int) The Error function returns an HTTP error code and detailed error information to the request. Func handlefunc Handle (pattern string, handler handler) Handle registers the reactor (DEFAULTSERVEMUX) for the given pattern (pattern) in handler. Servemux's documentation explains how pattern works. Func handlefuncfunc Handlefunc (pattern string, handler func (Responsewriter, *request)) Handlefunc for a given pattern (pattern) in Defaultservemux(handler function). 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. Handler is generally nil, when using Defaultservemux. A simple server example: 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 contains the certificate and the private key that matches the service desk (server). If 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 example: import ("Log" "Net/http") Func handler (W http. Responsewriter, req *http. Request) {W.header (). Set ("Content-type", "Text/plain") W.write ([]byte ("The" This was an 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 directory 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 that returns a non-eof error when the read exceeds the limit and closes the potential reader (function/process) 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 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. Ansic each to decompose the time header (e.g. 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). If the global agent is illegal, an error is returned. Returns an empty (nil) URL and an empty error code 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 every request and calls handler to respond. The handler parameter is generally nil, at which point the Defaultservemux is used. 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, set MIME types, and manipulate if-modified-since requests. If the content type row of the Reponse header is not set, the function first attempts to infer from the name's file extension, and if it fails, the first data segment of the read Readseeker is sent to the Detectcontenttype function for judgment. In addition the name parameter is useless, in particular cases it can be empty andNever join the reponse. If the modtime parameter is nonzero, Servecontent contains a last-modified row that contains the parameter in the header of the response. If the header of the request contains if-modified-since rows, Servecontent uses the Modtime parameter to determine that the use should send the entire content. The Seek method of the content parameter must be valid: Servecontent determines the size of the content by shifting to the end. If the caller sets the W's ETag Header,servecontent will pass it, use If-range and If-none-match (the parameter 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 parameter. 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 if the status code is unknown and returns an empty string.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.