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

Posted

in

by

Tags:

Comments

3 responses to “Golang: Make HTTP requests”

  1. Gwyneth Llewelyn Avatar

    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…

  2. Naomi Avatar
    Naomi

    Hi! How to change the GET and POS requests to use http2?

  3. kholidfu Avatar
    kholidfu

    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 *