Golang 通过一个客户端发出两个 HTTP 请求

时间:2021-03-27 18:57:34

标签: go go-http

如何在 Go 上通过一个客户端准备两个 HTTP 请求而不会出现内存问题?

我有下一个代码:

func moduleView(url string) {
    var module Module
    httpClient := &http.Client{}
    moduleId, listHttpResponseCode := findEntity(httpClient, url)
    request, _ := http.NewRequest("GET", fmt.Sprintf("%s/api/getById/%s", coreURL, module.ID), nil)
    response, _ := httpClient.Do(request)
    statusOK := response.StatusCode >= 200 && response.StatusCode < 300
    if !statusOK {
        fmt.Println("Unable to get by name module: ", response.Status)
    } else {
        responseBody, _ := ioutil.ReadAll(response.Body)
        json.Unmarshal([]byte(strings.TrimSuffix(string(responseBody), "\n")), &module)
        fmt.Printf(module)
    }
    return nil
}

func findEntity(httpClient *http.Client, url string) int {
    var module Module
    request, _ := http.NewRequest("GET", fmt.Sprintf("%s/api/getByName", url), nil)
    response, _ := httpClient.Do(request)
    responseBody, _ := ioutil.ReadAll(response.Body)
    json.Unmarshal([]byte(strings.TrimSuffix(string(responseBody), "\n")), &module)
    statusOK := response.StatusCode >= 200 && response.StatusCode < 300
    if !statusOK {
        return Module{}, response.StatusCode
    }
    return module, response.StatusCode
}

两个请求都在工作,如果单独使用没有错误。 但是,如果尝试同时使用它们(从一个获取 ID,然后在另一个上处理此数据请求),我会收到内存错误

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x38 pc=0x1334022]

请提供有关将一个 httpClient 用于两个请求的正确性的想法?谢谢

0 个答案:

没有答案