我们先看看标准库net/http如何处理一个请求。
import (
"fmt"
"log"
"net/http"
)
var count = 0
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
fmt.Printf("URL.Path = %q\n", r.URL.Path)
}
func counter(w http.ResponseWriter, r *http.Request) {
count++
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
fmt.Println(count)
}
代码块定义了两个不同的路由,分别是“/”和“/count”,分别绑定 handler 和 counter, 根据不同的HTTP请求会调用不同的处理函数。
调用“/”路由处理方法得到的结果是:
调用“/count”路由处理方法得到的结果是:
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://www.baidu.com")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(body))
}
执行程序获取到的结果是:
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
payload := strings.NewReader("data=example")
resp, err := http.Post("https://www.baidu.com", "application/x-www-form-urlencoded", payload)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(body))
}
执行程序获取到的结果是: