處理流程
Client -> Requests -> [Multiplexer(router) -> handler -> Response -> Client
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.
")
}
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
", k, v) //所有頭資訊
}
fmt.Printf("resp status %s,statusCode %d
", resp.Status, resp.StatusCode)
fmt.Printf("resp Proto %s
", resp.Proto)
fmt.Printf("resp content length %d
", resp.ContentLength)
fmt.Printf("resp transfer encoding %v
", resp.TransferEncoding)
fmt.Printf("resp Uncompressed %t
", 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))
}