处理流程
Clinet -> Requests -> [Multiplexer(router) -> handler -> Response -> Clinet
HTTP服务端
http.HandleFunc("/", indexHandler) http.ListenAndServe("127.0.0.1:8000", nil) 或 server := &Server{Addr: addr, Handler: handler} server.ListenAndServe()
import ( "fmt" "net/http" ) func Hello(w http.ResponseWriter, r *http.Request) { fmt.Println("Hello World.") fmt.Fprintf(w, "Hello World.\n") } func main() { http.HandleFunc("/", Hello) err := http.ListenAndServe("0.0.0.0:6000", nil) if err != nil { fmt.Println("http listen failed.") } }
HTTP客户端
GET请求示例
package main import ( "fmt" "net/http" "log" "reflect" "bytes" ) func main() { resp, err := http.Get("http://www.baidu.com") if err != nil { log.Println(err) return } defer resp.Body.Close() //关闭链接 headers := resp.Header for k, v := range headers { fmt.Printf("k=%v, v=%v\n", k, v) //所有头信息 } fmt.Printf("resp status %s,statusCode %d\n", resp.Status, resp.StatusCode) fmt.Printf("resp Proto %s\n", resp.Proto) fmt.Printf("resp content length %d\n", resp.ContentLength) fmt.Printf("resp transfer encoding %v\n", resp.TransferEncoding) fmt.Printf("resp Uncompressed %t\n", resp.Uncompressed) fmt.Println(reflect.TypeOf(resp.Body)) buf := bytes.NewBuffer(make([]byte, 0, 512)) length, _ := buf.ReadFrom(resp.Body) fmt.Println(len(buf.Bytes())) fmt.Println(length) fmt.Println(string(buf.Bytes())) }
使用http.Do设置请求头、cookie等
package main import ( "net/http" "strings" "io/ioutil" "log" "fmt" ) func main() { client := &http.Client{} req, err := http.NewRequest("POST", "http://www.baidu.com", strings.NewReader("name=xxxx&passwd=xxxx")) if err != nil { fmt.Println(err) return } req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") //设置请求头信息 resp, err := client.Do(req) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Println(err) return } var res string res = string(body[:]) fmt.Println(res) }
POST请求示例
package main import ( "net/http" "strings" "fmt" "io/ioutil" ) func main() { resp, err := http.Post("http://www.baidu.com", "application/x-www-form-urlencoded", strings.NewReader("username=xxx&password=xxxx")) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) }
PostForm请求示例
package main import ( "net/http" "fmt" "io/ioutil" "net/url" ) func main() { postParam := url.Values{ "name": {"wd"}, "password": {"1234"}, } resp, err := http.PostForm("https://cn.bing.com/", postParam) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
数据结构算法与应用
塞尼 / 机械工业出版社 / 1999-3 / 49.00元
数据结构、算法与应用—C++语言描述(英文版),ISBN:9787111070177,作者:(美)塞尼 著一起来看看 《数据结构算法与应用》 这本书的介绍吧!