第十一章 http标准库和其他标准库

时间:2022-07-25
本文章向大家介绍第十一章 http标准库和其他标准库,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

其实这一章的内容, 我们在之前的测试章节都已经涉及过了.

一. 模拟一个http服务端

package main

import "net/http"

type handler int

func (h *handler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
    writer.Write([]byte("abc"))
}

func main() {
    h := new(handler)
    http.ListenAndServe(":8889", h)
}

这就模拟了一个服务端, 我们可以网客户端发各种各样的数据.

二. 模拟一个http客户端

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    resp, err := http.Get("http://localhost:8889")
    if err != nil {
        panic("error")
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

这样就把刚刚服务端发送的abc读取出来了

三. 发送带有header的http请求

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    // 使用自定义的request
    request, err := http.NewRequest(http.MethodGet, "http://localhost:8889", nil)
    if err != nil {
        panic("error")
    }
    // 添加一个ua, 这样服务端吧ua取出来, 就可以展示出来了
    request.Header.Add("ua", "ua")
    resp, err := http.DefaultClient.Do(request)
    //resp, err := http.Get("http://localhost:8889")
    if err != nil {
        panic("error")
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

四. 第四个讲的是pprof, 我之前在测试的时候已经详细研究过pprof用来监控web服务的性能, 这里就不在描述了,

给出一个连接: https://www.cnblogs.com/ITPower/articles/12324659.html

https://www.cnblogs.com/ITPower/articles/12317631.html

五. 其他标准库, 这里也是一代而过, 讲的并不详细, 学完这门课, 我们在集中精力研究各个标准库