资源描述:
《Go语言网络编程-v002.pdf》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、Go语言网络编程why404@七牛云存储2012/07/211OverviewSocketHTTPRPCJSONJSON-RPCWebDevlopment2Socket编程3HTTP编程HTTPClientHTTPServer4HTTPClientMethodshttp.Gethttp.Posthttp.PostFormhttp.Head(*http.Client).Do5http.Getfunc(c*Client)Get(urlstring)(r*Response,errerror)resp,err:=http.G
2、et("http://example.com/")iferr!=nil{//handleerror…return}deferresp.Body.close()io.Copy(os.Stdout,resp.Body)//Getisawrapperaroundhttp.DefaultClient.Get6http.Postfunc(c*Client)Post(urlstring,bodyTypestring,bodyio.Reader)(r*Response,errerror)resp,err:=http.Post("h
3、ttp://example.com/upload","image/jpeg",&imageDataBuf)iferr!=nil{//handleerror…return}ifresp.StatusCode!=http.StatusOK{//handleerror…return}//…//Postisawrapperaroundhttp.DefaultClient.Post7http.PostFormfunc(c*Client)PostForm(urlstring,dataurl.Values)(r*Response,
4、errerror)resp,err:=http.PostForm("http://example.com/posts",url.Values{"title":{"articletitle"},"content":{"articlebody"}})iferr!=nil{//handleerror…return}//…//PostFormisawrapperaroundhttp.DefaultClient.PostForm8http.Headfunc(c*Client)Head(urlstring)(r*Response
5、,errerror)resp,err:=http.Head("http://example.com/")//Headisawrapperaroundhttp.DefaultClient.Head9(*http.Client).Dofunc(c*Client)Do(req*Request)(resp*Response,errerror)req,err:=http.NewRequest("GET","http://example.com",nil)//...req.Header.Add("User-Agent","Gob
6、ookCustomUser-Agent")client:=&http.Client{//...}resp,err:=client.Do(req)//...10HTTPServer处理http请求自定义http.Server11处理http请求funcListenAndServe(addrstring,handlerHandler)errorhttp.Handle("/foo",fooHandler)http.HandleFunc("/bar",func(whttp.ResponseWriter,r*http.Requ
7、est){fmt.Fprintf(w,"Hello,%q",html.EscapeString(r.URL.Path))})log.Fatal(http.ListenAndServe(":8080",nil))//http.Handle或http.HandleFunc缺省注入http.DefaultServeMux12自定义http.Servers:=&http.Server{Addr:":8080",Handler:myHandler,ReadTimeout:10*time.Second,WriteTimeout:
8、10*time.Second,MaxHeaderBytes:1<<20,}log.Fatal(s.ListenAndServe())13HTTP高级话题14自定义http.Client//inthe“net/http”packagevarDefaultClient=&Client{}//so..http.Get==http.DefaultCli