处理流程
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))
}
有疑问加站长微信联系(非本文作者)