go的net/http用法

http包提供了HTTP客户端和服务端的实现

一:http客户端的几种方法

1、 func (c *Client) Get(url string) (resp *Response, err error)
说明: 利用get方法请求指定的url,Get请求指定的页面信息,并返回实体主体

2、func (c *Client) Head(url string) (resp *Response, err error)
说明:利用head方法请求指定的url,Head只返回页面的首部

3、func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
说明:利用post方法请求指定的URl,如果body也是一个io.Closer,则在请求之后关闭它

4、func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
说明:利用post方法请求指定的url,利用data的key和value作为请求体.

5、func (c *Client) Do(req *Request) (resp *Response, err error)
说明:Do发送http请求并且返回一个http响应,遵守client的策略,如重定向,cookies以及auth等.当调用者读完resp.body之后应该关闭它,

如果resp.body没有关闭,则Client底层RoundTripper将无法重用存在的TCP连接去服务接下来的请求,如果resp.body非nil,则必须对其进行关闭.
通常来说,经常使用Get,Post,或者PostForm来替代Do

代码示例

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 == {
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()}
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 == {
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.HandleFunc
往DefaultServeMux的map[string]muxEntry中增加对应的handler和路由规则

http.ListenAndServe
启动一个http服务器,监听8080端口
上面的代码中蕴含着http服务器处理http的流程,有时间可以看源码分析分析

参考:

https://www.cnblogs.com/msnsj/p/4365186.html

http://www.infoq.com/cn/articles/golang-standard-library-part02

上一篇:(Problem 33)Digit canceling fractions


下一篇:(Problem 73)Counting fractions in a range