Go语言网络编程-v002.pdf
上传人:qw****27 上传时间:2024-09-12 格式:PDF 页数:19 大小:6.7MB 金币:15 举报 版权申诉
预览加载中,请您耐心等待几秒...

Go语言网络编程-v002.pdf

Go语言网络编程-v002.pdf

预览

免费试读已结束,剩余 9 页请下载文档后查看

15 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

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.Get("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("http://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,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,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","GobookCustomUser-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.Request){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:1