Go Pkg Learn and Practice-HTTP
Last Update:2018-04-10
Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. The Go HTTP package contains the HTTP client and HTTP server implementations. The main documents are: ~~~client.gocookie.goheader.gohttp.gomethod.gorequest.goresponse.goserver.gotransport.go~~~server.go:--- ------We start with a simple HTTP server. Creating an HTTP service requires three steps: * Create Servermux: Associate a predefined list of URLs with Hanlder. * Create handler: responsible for processing HTTP requests and returning HTTP responses. * Listen for the given address and port to provide HTTP service. ~~~package mainimport ("FMT" "html" "Log" "Net/http") Func Foohandler (w http. Responsewriter, R *http. Request) {fmt. fprintf (W, "Hello,%q", HTML. Escapestring (R.url. Path))}func main () {mux: = http. Newservemux () Handler: = http. Handlerfunc (Foohandler) mux. Handle ("/foo", Handler) log. Fatal (http. Listenandserve (": 8080", MUX))}~~~servemux:~~~//servemux struct type servemux struct {mu sync. rwmutex//This map is used to store HTTP URL entries, and each erntry contains a handler//corresponding to the above example: M = {"/foo": Foohandler (Responsewriter, *request)} M map[string]muxentryhosts bool//whether any patterns contain hostnames}type muxentry struct {explicit Boolh Handlerpatt Ern string}func Newservemux () *servemux {return new (SERVEMUX) }func (Mux *servemux) match (Path string) (H Handler, pattern string) {//Find the corresponding Handlerfunc (MUX *servemux) According to the request Handle R (R *request) (H Handler, pattern string) {func (Mux *servemux) Handler (host, path string) (H Handler, pattern string) {// Distribute Request to Handler processing func (MUX *servemux) servehttp (w responsewriter, R *request) {//Register Handlerfunc (MUX *servemux) Handl E (Pattern string, handler handler) {func (Mux *servemux) Handlefunc (pattern string, handler func (Responsewriter, *request ) {~~~defaultservemux:~~~var Defaultservemux = &defaultservemuxvar defaultservemux ServeMuxfunc Handle (pattern string, Handler handler) {Defaultservemux.handle (pattern, handler)}func Handlefunc (pattern string, handler func ( Responsewriter, *request) {///The above example with Defaultservemux, can be simplified to: func main () {handler: = http. Handlerfunc (Foohandler) http. Handle ("/foo", Handler) log. Fatal (http. Listenandserve (": 8080", nil)} or Func main () {http. Handlefunc ("/foo", Foohandler) log. Fatal (http. Listenandserve (": 8080", nil))}~~~hAndler:~~~type Handler Interface {servehttp (Responsewriter, *request)}//F implements interface Handler Servehttptype handlerfunc func ( Responsewriter, *request) func (f Handlerfunc) servehttp (w responsewriter, R *request) {f (W, R)}//defined some processor func NotFound Handler () Handler {return Handlerfunc (NotFound)}func redirecthandler (URL string, code int) Handler {func Timeouthandler ( H Handler, dt time. Duration, msg String) Handler {~~~listenandserve:~~~//server struct type server struct {Addr string//TCP address to listen O N, ": http" if Emptyhandler Handler//Handler to invoke, HTTP. Defaultservemux if Niltlsconfig *tls. Config//optional TLS config, used by Servetls and listenandservetlsreadtimeout time. Durationreadheadertimeout time. Durationwritetimeout time. Durationidletimeout time. Durationmaxheaderbytes Inttlsnextproto Map[string]func (*server, *tls. Conn, Handler) connstate func (net. Conn, Connstate) errorlog *log. loggerdisablekeepalives int32//Accessed Atomically.inshutdown int32//accessed atomically (non-Zero means we ' re in Shutdown) nextprotoonce sync. Once//Guards setuphttp2_* Initnextprotoerr Error//result of HTTP2. Configureserver if USEDMU sync. Mutexlisteners map[net. Listener]struct{}activeconn Map[*conn]struct{}donechan Chan Struct{}onshutdown []func ()}//Create server, Call Listenandservefunc listenandserve (addr string, handler handler) error {server: = &server{addr:addr, Handler:handl Er}return server. Listenandserve ()}func listenandservetls (addr, CertFile, keyfile string, handler handler) error {server: = &server{ ADDR:ADDR, Handler:handler}return server. Listenandservetls (CertFile, keyfile)}//call net. Listen () for listener func (SRV *server) listenandserve () error {func (SRV *server) listenandservetls (CertFile, keyfile string) err or {//Then call server. Serve is responsible for processing request func (SRV *server) Serve (l net. Listener) Error {func (SRV *server) servetls (l net). Listener, CertFile, keyfile String) error {//Serve () call Accept to get the connection data and create Conn, go C.serve () Processing request func (SRV *server) Newconn (r WC net. Conn) *conn {/* Conn knotType conn struct {server *servercancelctx context. CANCELFUNCRWC Net. Connremoteaddr stringtlsstate *tls. Connectionstatewerr Errorr *connreaderbufr *bufio. READERBUFW *bufio. Writerlastmethod Stringcurreq Atomic. Value//Of *response (which have a Request in it) curstate Atomic. Value//Of Connstatemu sync. Mutexhijackedv bool}*///c.readrequest () read request, call handler Servehttp () func (c *conn) serve (CTX context. Context) {Other methods:func in Server (SRV *server) maxheaderbytes () int {func (SRV *server) initialreadlimitsize () Int64 {func (SRV *server) Close () Error {func (SRV *server) Shutdown (CTX context. Context) Error {func (SRV *server) Registeronshutdown (f func ()) {func (SRV *server) shouldconfigurehttp2forserve () bool {f UNC (SRV *server) setkeepalivesenabled (v bool) {func (SRV *server) setuphttp2_servetls () error {func (SRV *server) setupht Tp2_serve () Error {func (SRV *server) Oncesetnextprotodefaults_serve () {func (SRV *server) oncesetnextprotodefaults () { Conn other Methods:func (c *conn) hijacked () BoOL {func (c *conn) hijacklocked () (RWC net. Conn, buf *bufio. Readwriter, err Error) {func (c *conn) readrequest (CTX context. Context) (w *response, err Error) {func (c *conn) Finalflush () {func (c *conn) Close () {func (c *conn) closewriteandwait () {func (c *conn) setState (NC net. Conn, State connstate) {func (C *conn) serve (CTX context. Context) {~~~responsewrite:~~~type Responsewriter interface {Header () headerwrite ([]byte) (int, error) writeheader (int )}//response struct implements HTTP. Responsewritertype response struct {conn *connreq *request//Request for this responsereqbody io. Readclosercancelctx context. Cancelfunc//When servehttp exitswroteheader bool//reply header has been (logically) writtenwrotecontinue bool//+ C Ontinue response was writtenwants10keepalive bool//http/1.0 w/connection "keep-alive" wantsclose bool//HTTP request ha S Connection "close"//the string "Hello ..." in the example will be written in W *bufio. Writer//Buffers output in chunks to CHUNKWRITERCW Chunkwriterhandlerheader Headercalledheader bool//handler accessed Handlerheader via header//corresponding string length written int64//number of bytes written in Bodycontentlength Int64//explicitly-declared content-length; Or-1//Status Code status INT//status code passed to Writeheadercloseafterreply boolrequestbodylimithit booltrailers []stringha Ndlerdone Atomicbool//Set True when the handler Exitsdatebuf [Len (TimeFormat)]byteclenbuf [10]BYTESTATUSBUF [3]byteclos] Enotifych Chan booldidclosenotify Int32//Atomic (only 0->1 winner should send)}func (w *response) header () header {Fu NC (w *response) Write (data []byte) (n int, err error) {func (w *response) writeheader (code int) {~~~client.go:---------customer HTTP can be used directly at the end. Get, http. Post, for example: ~~~package mainimport "net/http" import "FMT" import "Io/ioutil" Func Main () {resp, err: = http. Get ("http://www.163.com") if err! = Nil {fmt. PRINTLN (Err) Return}defer resp. Body.close () body, err: = Ioutil. ReadAll (resp. Body) fmt. Println (String (body))}~~~~~~func Get (URL string) (Resp *response, err error) {func Post (url String, contentType string, body io. Reader) (Resp *response, err error) {func postform (URL string, data URL.) Values) (Resp *response, err error) {func Head (URL string) (Resp *response, err error) {func send (Ireq *request, RT Roundt Ripper, Deadline time. Time) (Resp *response, didtimeout func () bool, err Error) {//can do some control by creating a client type client struct {Transport Roundtripper Checkredirect func (req *request, via []*request) Errorjar cookiejartimeout time. Duration}func (c *client) Get (URL string) (Resp *response, err Error) {func (c *client) Post (URL string, ContentType Strin G, body io. Reader) (Resp *response, err Error) {func (c *client) postform (URL string, data URL. Values) (Resp *response, err Error) {func (c *client) Head (URL string) (Resp *response, err Error) {func (c *client) do (re Q *request) (*response, error) {func (c *client) Send (req *request, Deadline time. Time) (Resp *response, didtimeout func () bool, err error) {~~~request.go----------~~~type Request struct {Method StringUrl *Url. Urlproto string//"http/1.0" protomajor int//1ProtoMinor int//0Header headerbody io. Readclosergetbody func () (IO. Readcloser, error) contentlength int64transferencoding []stringclose boolhost stringform URL. Valuespostform URL. Valuesmultipartform *multipart. Formtrailer headerremoteaddr Stringrequesturi stringtls *tls. Connectionstatecancel <-chan struct{}response *responsectx context. Context}func newrequest (method, url string, body io. Reader) (*request, error) {func (R *request) context () context. Context {func (R *request) Withcontext (CTX context. Context) *request {func (R *request) Protoatleast (major, minor int) bool {func (R *request) useragent () string {func (R *r equest) cookies () []*cookie {func (R *request) Cookie (name string) (*cookie, error) {func (R *request) Addcookie (c *cookie {func (R *request) Referer () string {func (R *request) Multipartreader () (*multipart. Reader, error) {func (R *request) Multipartreader () (*multipart. Reader, error) {func (R *request) Ish2upgrade() bool {func (R *request) Write (w io. Writer) Error {func (R *request) writeproxy (w io). Writer) Error {func (req *request) write (w io. Writer, usingproxy bool, extraheaders Header, waitforcontinue func () bool) (err Error) {func (R *request) BasicAuth () (Use Rname, password string, OK bool) {func (R *request) Setbasicauth (username, password string) {func (R *request) Parseform () Error {func (R *request) parsemultipartform (maxmemory Int64) error {func (R *request) Formvalue (key String) string {func (R *request) Postformvalue (key String) string {func (R *request) formfile (key string) (multipart. File, *multipart. Fileheader, error) {func (R *request) expectscontinue () bool {func (R *request) wantshttp10keepalive () bool {func (R *requ EST) wantsclose () bool {func (R *request) Closebody () {func (R *request) isreplayable () bool {func (R *request) outgoingle Ngth () Int64 {~~~response.go-----------~~~type Response struct {Status string//e.g. "OK" StatusCode int/e.g. 200Pr Oto string//e.g. "Http/1.0 "Protomajor int//e.g. 1ProtoMinor int//e.g. 0Header headerbody io. Readclosercontentlength int64transferencoding []stringclose booluncompressed booltrailer HeaderRequest *RequestTLS * Tls. Connectionstate}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 {func (R *response) Closebody () {func readresponse (r *bufio. Reader, req *request) (*response, error) {~~~263 hits