七叶笔记 » golang编程 » Golang Http 请求和获取实现

Golang Http 请求和获取实现

golang请求网页,使用net/http包中的client提供的方法实现。

Go Http客户端

get请求

resp, err := http.Get(“”)

body, err := ioutil.ReadAll(resp.Body)

post请求

resp, err := http.Post(“”,”application/x-www-form-urlencoded”,strings.NewReader(“name=xx”))

body, err := ioutil.ReadAll(resp.Body)

http.PostForm

resp, err := http.PostForm(“”,url.Values{“key”: {“Value”}, “id”: {“123”}})

有时需要在请求的时候设置头参数、 Cookie 之类的数据,就可以使用http.Do方法。

req, err := http.NewRequest(“POST”, “”, strings.NewReader(“name=xx”))

req. Header .Set(“Content-Type”, “application/x-www-form-urlencoded”)

req.Header.Set(“Cookie”, “name=anny”)

resp, err := client.Do(req)

Go Http服务器端

Go处理 HTTP 请求:ServeMux 和 Handler

ServrMux 本质上是一个 HTTP 请求路由器。它把收到的请求与一组预先定义的 URL 路径列表做对比,然后在匹配到路径的时候调用关联的处理器(Handler)。

Handler 处理器负责输出HTTP响应的头和正文。

案例:

func main() {

mux := http.NewServeMux()

rh := http.RedirectHandler(“”, 307)

mux.Handle(“/foo”, rh)

log .Println(“Listening…”)

http.ListenAndServe(“:3000”, mux)

}

在浏览器中访问 ,你应该能发现请求已经成功的重定向到百度了

自定义处理器案例:

package main

import (

“log”

“net/http”

“time”

)

type timeHandler struct {

Format string

}

func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http. Request ) {

tm := time.Now().Format(th.format)

w.Write([] byte (“The time is: ” + tm))

}

func main() {

mux := http.NewServeMux()

th := &timeHandler{format: time.RFC1123}

mux.Handle(“/time”, th)

log.Println(“Listening…”)

http.ListenAndServe(“:3000”, mux)

}

相关文章