0

How to prepare two HTTP requests via one client on Go without problems with memory?

I have the next code :

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
}

Both requests are working, and if use separately no errors. But if trying to use them both together (get ID from one and after do with this data request on another), I'm getting an error with memory

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

Please give ideas on how correct to use one httpClient for two requests? Thanks

mkopriva
  • 35,176
  • 4
  • 57
  • 71
  • 3
    You should never ignore errors. Which line in the example code causes the panic? (You can find the file and line of the error in the stacktrace, if you don't know how to parse the stacktrace please include it in the question) – mkopriva Mar 27 '21 at 18:59
  • 3
    It should also be noted that the code in the question is a mess. It has a bunch of careless compile time errors, and since to get the runtime panic the program first needs to compile and be executed, it is proof that the code in the question is not the actual code you want us to help you with. Please try to provide a [mcve] if you're looking for quick and accurate help. – mkopriva Mar 27 '21 at 19:12

0 Answers0