在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
http包提供了HTTP客户端和服务端的实现 一:http客户端的几种方法1、 func (c *Client) Get(url string) (resp *Response, err error) 2、func (c *Client) Head(url string) (resp *Response, err error) 3、func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error) 4、func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) 5、func (c *Client) Do(req *Request) (resp *Response, err error) 如果resp.body没有关闭,则Client底层RoundTripper将无法重用存在的TCP连接去服务接下来的请求,如果resp.body非nil,则必须对其进行关闭. 代码示例 1、http.Get package main import ( "fmt" "io/ioutil" "net/http" ) func main() { requestUrl := "http://www.baidu.com" response, err := http.Get(requestUrl) if err != nil { fmt.Println(err) } defer response.Body.Close() body, _ := ioutil.ReadAll(response.Body) fmt.Println(string(body)) } 2、http.Post package main import ( "bytes" "fmt" "io/ioutil" "net/http" "net/url" ) func main() { requestUrl := "http://www.baidu.com/" // request, err := http.Get(requestUrl) // request, err := http.Head(requestUrl) postValue := url.Values{ "username": {"hangmeimei"}, "address": {"anhui"}, "subject": {"world"}, "form": {"beij"}, } //request, err := http.PostForm(requestUrl, postValue) body := bytes.NewBufferString(postValue.Encode()) request, err := http.Post(requestUrl, "text/html", body) if err != nil { fmt.Println(err) } defer request.Body.Close() fmt.Println(request.StatusCode) if request.StatusCode == 200 { rb, err := ioutil.ReadAll(request.Body) if err != nil { fmt.Println(rb) } fmt.Println(string(rb)) } } 3、 http.Do package main import ( "fmt" "io/ioutil" "net/http" "strconv" ) func main() { client := &http.Client{} request, err := http.NewRequest("GET", "http://www.baidu.com", nil) if err != nil { fmt.Println(err) } cookie := &http.Cookie{Name: "Tom", Value: strconv.Itoa(123)} request.AddCookie(cookie) //向request中添加cookie //设置request的header request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") request.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3") request.Header.Set("Accept-Encoding", "gzip,deflate,sdch") request.Header.Set("Accept-Language", "zh-CN,zh;q=0.8") request.Header.Set("Cache-Control", "max-age=0") request.Header.Set("Connection", "keep-alive") response, err := client.Do(request) if err != nil { fmt.Println(err) return } defer response.Body.Close() fmt.Println(response.StatusCode) if response.StatusCode == 200 { r, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Println(err) } fmt.Println(string(r)) } }
二:建立web服务器package main import ( "net/http" ) func SayHello(w http.ResponseWriter, req *http.Request) { w.Write([]byte("Hello")) } func main() { http.HandleFunc("/hello", SayHello) http.ListenAndServe(":8080", nil) } 说明: http.ListenAndServe
参考: https://www.cnblogs.com/msnsj/p/4365186.html http://www.infoq.com/cn/articles/golang-standard-library-part02
|
请发表评论