Golang 通过一个客户端发出两个 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,fmt.Sprintf("%s/api/getByName",url),_ := httpClient.Do(request)
    responseBody,_ := IoUtil.ReadAll(response.Body)
    json.Unmarshal([]byte(strings.Trimsuffix(string(responseBody),&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 用于两个请求的正确性的想法?谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)