Kristina
Kristina

Reputation: 4522

Get Request in Golang

this is a textbook example I try to put in use.

I get "BAD" as a result, it means that resp is nil, though I don't know how to fix it.

package main

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

func main() {

    resp, _ := http.Get("http://example.com/")

    if resp != nil {
        body, _ := ioutil.ReadAll(resp.Body)

        fmt.Println(string(body))

        resp.Body.Close()
    } else {
        fmt.Println("BAD")
    }
}

Upvotes: 0

Views: 790

Answers (1)

dlsniper
dlsniper

Reputation: 7477

I would recommend to check your Internet settings first, as I cannot reproduce the problem.

Also, error handling in Go is crucial, so change your code to the one below and see if you get any error when making the request.

package main

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

func main() {

    resp, err := http.Get("http://example.com/")
    if err != nil {
        log.Fatalln(err)
    }

    if resp != nil {
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatalln(err)
        }

        fmt.Println(string(body))

        resp.Body.Close()
    } else {
        fmt.Println("BAD")
    }
}

Upvotes: 2

Related Questions