Skip to content

Instantly share code, notes, and snippets.

@ijt ijt/http_get.go
Last active Oct 28, 2019

Embed
What would you like to do?
Example of using http.Get in go (golang)
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s URL\n", os.Args[0])
os.Exit(1)
}
response, err := http.Get(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
_, err := io.Copy(os.Stdout, response.Body)
if err != nil {
log.Fatal(err)
}
}
@case

This comment has been minimized.

Copy link

case commented Oct 3, 2013

Thanks for sharing this — I think http needs to be het/http, and this line: response, _, err := http.Get("http://golang.org/") works if you remove the _: response, err := http.Get("http://golang.org/")

@brandly

This comment has been minimized.

Copy link

brandly commented Nov 12, 2013

Thanks for the tip, @case. I got this running but had to import net/http.

@sadhasivam

This comment has been minimized.

Copy link

sadhasivam commented Apr 6, 2014

golang 1.2.1. import ("net/http")
response, err := http.Get( "http://golang.org")

@tolinwei

This comment has been minimized.

Copy link

tolinwei commented Apr 24, 2014

Thanks for sharing!

@ryanseys

This comment has been minimized.

Copy link

ryanseys commented Apr 28, 2014

Thanks! This helped me! 😄 👍

@FrancisVarga

This comment has been minimized.

Copy link

FrancisVarga commented Jun 18, 2014

👍

@vvincirey

This comment has been minimized.

Copy link

vvincirey commented Jul 8, 2014

Got the below error when tried it in playground

Get http://golang.org/: dial tcp: stat /etc/resolv.conf: No such file or directory [process exited with non-zero status]
@thomasbratt

This comment has been minimized.

Copy link

thomasbratt commented Jul 16, 2014

You replace the printf/exit combination with: Log.Fatal;

http://golang.org/pkg/log/#Fatal

@varver

This comment has been minimized.

Copy link

varver commented Aug 22, 2014

problem in line 11
replace it with
response, err := http.Get("http://golang.org/")

@yashrajsingh

This comment has been minimized.

Copy link

yashrajsingh commented Sep 7, 2014

👍

@sughodke

This comment has been minimized.

Copy link

sughodke commented May 4, 2015

fmt.Printf("%s", err) --> fmt.Printf("%s\n", err)

@tuntapovski

This comment has been minimized.

Copy link

tuntapovski commented May 19, 2015

thanks for the example, i was looking for this.
but what a ugly language is this :S:S:S
it's definitely not for lazy people like me

@JoopClaireIT

This comment has been minimized.

Copy link

JoopClaireIT commented Jul 14, 2015

@daft117 actually it is, because it prevents you from making terrible mistakes coming from sloppiness ;)

@xcellardoor

This comment has been minimized.

Copy link

xcellardoor commented Nov 18, 2015

Thanks for sharing, has come in useful!

@MattMattV

This comment has been minimized.

Copy link

MattMattV commented Dec 10, 2015

Very useful ! Thank you ! 👍

@ablease

This comment has been minimized.

Copy link

ablease commented Feb 6, 2016

Hey thanks for this.

I noticed that if you simulate a situation where you cannot resolve the adress you are trying to 'get', the error handling on handling on line 13 isn't that useful. This is some example output.
%s (0x784698,0xc820076e10)

Using log.Fatal(err) seems to render the proper error. Maybe the log package wasnt a thing in go back when this example was made :)

@Rauk

This comment has been minimized.

Copy link

Rauk commented Mar 24, 2016

I wanted to know if there is any other way to read from response body apart from what has been mentioned. I'm new to Golang and just exploring other means and ways to do things.

@frankbolviken

This comment has been minimized.

Copy link

frankbolviken commented Apr 14, 2016

Hi,

So lets say I wanted to implement this as a rest endpoint. And in the method it would look up in a cache to see if the response was already cached. If cached, return cache, if not, do a new get and save that in the cache. How would a possible solution for this look like?

@AaronVasquez

This comment has been minimized.

Copy link

AaronVasquez commented May 9, 2016

I can't seem to get this to work with a url with https. Is there additional setup needed?

@doojin

This comment has been minimized.

Copy link

doojin commented May 26, 2016

Hello!
I also can't send a request for HTTPS urls.
What could be a problem?

@ijt

This comment has been minimized.

Copy link
Owner Author

ijt commented May 27, 2016

Hi all, sorry I didn't update this for so long. I forgot about it and didn't see any notifications for your posts. Anyway, it's updated now. Enjoy!

@amol9

This comment has been minimized.

Copy link

amol9 commented Jun 7, 2016

thanks, quickly got me running with go/http..

@jm-janzen

This comment has been minimized.

Copy link

jm-janzen commented Jul 30, 2016

Great! Exactly the kind of bare bones example I needed to see. Thanks for sharing this.

@Erichain

This comment has been minimized.

Copy link

Erichain commented Nov 13, 2016

Thanks for sharing, it's so great.

@Kundeshi

This comment has been minimized.

Copy link

Kundeshi commented Jan 9, 2017

This info was very helpful, however. Is there a way to pick out just the response status?

@bengadbois

This comment has been minimized.

Copy link

bengadbois commented Jan 25, 2017

The response status (200, 404, etc.) is available in response.StatusCode. You don't need to read the body for the status code.

@Naveennani777

This comment has been minimized.

Copy link

Naveennani777 commented Jul 21, 2017

Hi All,
I am not able to see content of get response from a server . Could you please let me know how to get the response .Am seeing hexadecimal values from output

Pasted my code below:
+++++++++++++++
package main
import (
"fmt"
"net/http"
"io"
"os"
// "encoding/json"

)

func main() {
url := "http://localhost:8080/api/v1/networks"
res, err := http.Get(url)
if err != nil {
panic(err)
}
fmt.Println("response from GET request" ,res)
fmt.Println("output of pnmid", res.Body)
defer res.Body.Close()
, err := io.Copy(os.Stdout, response.Body)
// fmt.Println("whole body",
)

body, err := ioutil.ReadAll(res.Body)
if err != nil {
	panic(err)
}
fmt.Println("response body" , res.Body)

Please help me on this to fix the issue.

@Naveennani777

This comment has been minimized.

Copy link

Naveennani777 commented Jul 21, 2017

I tried in below way and got output:

package main
import (
"fmt"
"net/http"
// "io"
// "os"
// "encoding/json"

)

func main() {
url := "http://localhost:3000/api/v1/subnets"
res, err := http.Get(url)
if err != nil {
panic(err)
}
fmt.Println("response from GET request" ,res)
fmt.Println("output of pnmid", res.Body)
defer res.Body.Close()
// , err := io.Copy(os.Stdout, response.Body)
// fmt.Println("whole body",
)

/* body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}*/
fmt.Println("response body" , res.Body)
// fmt.Println(body)
// var p Payload

// err := json.Unmarshal(body , &p)

}

After execution:

go run Sample_restcall.go:

response from GET request &{200 OK 200 HTTP/1.1 1 1 map[Access-Control-Allow-Origin:[*] Content-Type:[application/json; charset=utf-8] Set-Cookie:[dcbfef97e14c2a3cdf00a5
afc32d1e96=d9871f0ca4d0f07b0c6b84a4d79d8153; path=/; HttpOnly] X-Powered-By:[Express] Access-Control-Allow-Headers:[Content-Type] Access-Control-Allow-Methods:[PUT, GET,
POST, DELETE, OPTIONS] Content-Length:[676] Etag:[W/"2a4-JHwpbMIyxGxUzMU+0J4onQ"] Date:[Fri, 21 Jul 2017 15:24:47 GMT] Cache-Control:[private]] 0xc04203e300 676 [] fals
e false map[] 0xc042030400 }
output of pnmid &{0xc04203e2c0 {0 0} false 0x5cb870 0x5cb800}
response body &{0xc04203e2c0 {0 0} false 0x5cb870 0x5cb800}

I could see response status code as 200 , how to see response content and how to decode to normal json format.

@sibyakin

This comment has been minimized.

Copy link

sibyakin commented Aug 11, 2017

Naveennani777, you see what it is, slice of bytes, you have to convert it to string, try this:

        body, _ := ioutil.ReadAll(res.Body)
        text := string(body)
        fmt.Println(text)
@Naveennani777

This comment has been minimized.

Copy link

Naveennani777 commented Aug 31, 2017

Thanks alot sibyakin , Its working now.

@nurtureJamesTan

This comment has been minimized.

Copy link

nurtureJamesTan commented Dec 20, 2017

thank you :)

@pprasanthi

This comment has been minimized.

Copy link

pprasanthi commented May 10, 2018

Thank you :)

@chandankumar4

This comment has been minimized.

Copy link

chandankumar4 commented Nov 23, 2018

How to pass header in GET request

@otaviorojas

This comment has been minimized.

Copy link

otaviorojas commented Feb 27, 2019

How to pass header in GET request

@cbess

This comment has been minimized.

Copy link

cbess commented Oct 10, 2019

How to pass header in GET request

Here is an example:

client := &http.Client{}
apiURL := "https://myapi.url/data"
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
	return nil, err
}

// add header to request
req.Header.Add("authkey", "...")

// perform get request
res, err := client.Do(req)
@R4wm

This comment has been minimized.

Copy link

R4wm commented Oct 25, 2019

You dont need the else since your os.Exit'ing on condition of Line 12

@ijt

This comment has been minimized.

Copy link
Owner Author

ijt commented Oct 28, 2019

@R4wm, done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.