Search code examples
httpgourlhttp-status-code-404

Getting the status code from a get request in golang


I'm trying to get the http status code in goland.

I'm passing the authorization token as well.

This is what I tried so far:

func StatusCode(PAGE string, AUTH string) (r string){

    resp, err := http.NewRequest("GET", PAGE, nil)
    if err != nil {
        log.Fatal(err)
    }
    resp.Header.Set("Authorization", AUTH)

    fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))

    r := resp.StatusCode + http.StatusText(resp.StatusCode)
}

Basically I want to get this:

r = "200 OK"
or
r= "400 Bad request"

The previous code it´s complaining from resp.StatusCode and http.StatusText(resp.StatusCode)


Solution

  • There are two problems. The first is that the application uses the request as the response. Execute the request to get the response.

    The second problem is that resp.StatusCode + http.StatusText(resp.StatusCode) does not compile because operand types are mismatched. The value resp.StatusCode is an int. The value of http.StatusText(resp.StatusCode) is a string. Go does not have the implicit conversion of numbers to strings that would make this work the way you expect.

    Use r := resp.Status if you want the status string as sent from the server.

    Use r := fmt.Sprintf("%d %s", resp.StatusCode, http.StatusText(resp.StatusCode)) to construct a status string from the server's status code and the Go's status strings.

    Here's the code:

    func StatusCode(PAGE string, AUTH string) (r string) {
        // Setup the request.
        req, err := http.NewRequest("GET", PAGE, nil)
        if err != nil {
            log.Fatal(err)
        }
        req.Header.Set("Authorization", AUTH)
    
        // Execute the request.
        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            return err.Error()
        }
        
        // Close response body as required.
        defer resp.Body.Close()
    
        fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))
    
        return resp.Status
        // or fmt.Sprintf("%d %s", resp.StatusCode, http.StatusText(resp.StatusCode))
    }