Categories
Uncategorized

Golang: Make HTTP requests

A simple GET request can be made like this:

package main

import (
    "net/http"
    "ioutil"
)

func main() {
    // Make a get request
    rs, err := http.Get("https://google.com")
    // Process response
    if err != nil {
        panic(err) // More idiomatic way would be to print the error and die unless it's a serious error
    }
    defer rs.Body.Close()

    bodyBytes, err := ioutil.ReadAll(rs.Body)
    if err != nil {
        panic(err)
    }

    bodyString := string(bodyBytes)
}

POST request:

import (
    "bytes"
)
func main() {
    body := []byte("key1=val1&key2=val2")
    rs, err := http.Post("http://someurl.com", "body/type", bytes.NewBuffer(body))
    // Code to process response (written in Get request snippet) goes here

    // Simulating a form post is done like this:
    rs, err := http.PostForm("http://example.com/form",
                            url.Values{"key": {"Value"}, "id": {"123"}})
    // Code to process response (written in Get request snippet) goes here
}

If more control is needed, like specifying headers, cookies, etc:

// ...
client := &http.Client{}
req, err := http.NewRequest("GET", "http://example.com", nil)
req.Header.Add("If-None-Match", `some value`)
resp, err := client.Do(req)
// Code to process response

By Moazzam

Moazzam is a software developer working in the big apple. He has over a decade of experience in development. While most of his work involves developing web applications, he does development for Android and Windows Mobile in his spare time.

3 replies on “Golang: Make HTTP requests”

Awesome! Thank you so much for publishing your concise, well-explained code; as a beginner Go amateur programmer, sometimes the official Go language documentation is cryptic and lacks good examples…

Thank you for your nice, self explanatory example. Just doing python and now want to learn Go from scratch…

Leave a Reply

Your email address will not be published. Required fields are marked *