关于net/http库
我们先看看标准库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”路由处理方法得到的结果是:

发送get请求并获取响应
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))
}执行程序获取到的结果是:

发送post请求并获取响应
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))
}执行程序获取到的结果是:

到此这篇关于golang中的net/http库基本使用详解的文章就介绍到这了,更多相关golang net/http库内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论