Golang程序员Go

golang 基础(27)http

2019-04-27  本文已影响35人  zidea
golang_real.jpg

HTTP 编程

Http 可能使我们最熟悉的网络协议了吧,那么我们知道他全称吗?超文本传输协议,当初最开始写 html 时候看到这个名词有点 confusing。在 Go 语言标准库内建提供 net/http 包,涵盖了 HTTP 客户端和服务端的具体实现。

客户端请求

Get 请求

在 go 语言中实现简洁HTTP 客户端无需额外添加第三方包。

express eserver --pug --git --css less
cd eserver
npm install
npm start

这里用 express 简单创建了服务,来模拟客户端行为。

import(
    "net/http"
    "io"
    "os"
)

func main() {
    resp,err := http.Get("http://localhost:3000")
    if err != nil{
        return
    }
    defer resp.Body.Close()
    io.Copy(os.Stdout,resp.Body)
}

如果大家没有启动服务器,可以尝试请求百度一下

func main()  {
    resp,err := http.Get("http://www.baidu.com")
    if err != nil {
        panic(err)
    }

    defer resp.Body.Close()

    s, err := httputil.DumpResponse(resp, true) //[]byte
    if err != nil{
        panic(err)
    }

    fmt.Printf("%s\n",s)
}

我们可以使用httputil.DumpResponse将 resp 装换为 []byte 输出

request, err := http.NewRequest(
        http.MethodGet,
        "http://www.baidu.com",
        nil)
    request.Header.Add("User-Agent",
         "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1")
    resp,err := http.DefaultClient.Do(request);

    if err != nil {
        panic(err)
    }

对 request 和 http 进行一些控制,我们想让我们client访问百度的手机版

Post 请求
router.post('/',function(req,res,next){
  console.log(req.body);
  console.log(req.baseUrl)
  res.send("ok")
})
    resp, err := http.Post("http://localhost:3000/users",
        "application/x-www-form-urlencoded",strings.NewReader("name=zidea"))
        if err != nil {
            fmt.Println(err)
        }
     
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            // handle error
        }
     
        fmt.Println(string(body))

我们通常会发起表单请求,在 go 语言中为我们提供PostForm来轻松实现提交表单的请求

resp, err := http.PostForm("http://localhost:3000/users",url.Values{"title":{"angular"}, "author": {"zidea"}})
    if err != nil { 
        return
    }

自定义Client

在 go 语言中提供http.Gethttp.Post方法外,还提供一些方法让我们自定义请求体Request

    author := make(map[string]interface{})
    author["name"]="zidea"
    author["age"]=30

    bytesData, err := json.Marshal(author)
    if err != nil{
        fmt.Println(err.Error())
        return
    }

    reader := bytes.NewReader(bytesData)
    url := "http://localhost:3000/users"

    request, err := http.NewRequest("POST",url,reader)

    if err != nil{
        fmt.Println(err.Error())
        return
    }

    request.Header.Set("Content-Type", "application/json;charset=UTF-8")
    client := http.Client{}
    resp, err := client.Do(request)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    respBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    str := (*string)(unsafe.Pointer(&respBytes))
    fmt.Println(*str)
func Marshal(v interface{}) ([]byte, error)

Marshal这个方法接受接口而返回一个[]byte
具体可以参照 golang 网络编程(10)文本处理

func NewRequest(method, url string, body io.Reader) (*Request, error)

我们看 NewRequest 源码了解到,方法接受三个参数

func NewReader(b []byte) *Reader { return &Reader{b, 0, -1} }
    str := (*string)(unsafe.Pointer(&respBytes))
    fmt.Println(*str)

这段代码大家可能感觉陌生,这个有点接近底层,随后分享有关unsafe.Pointer用法。这里大家可以忽略他,仅认为这样做有利于内存优化而已。

上一篇 下一篇

猜你喜欢

热点阅读