ruk·si

🐹 Go
Sending HTTP Requests

Updated at 2015-08-30 00:27

Basic HTTP request. Remember to close request body after read and check for nil response.

package main

import (
    "io/ioutil"
    "net/http"
    "strings"
)

func assert(condition bool) {
    if !condition {
        panic("assert failed")
    }
}

func check(err error) {
    if err != nil {
        panic(err)
    }
}

func main() {
    resp, err := http.Get("http://www.google.com")
    if resp != nil {
        defer resp.Body.Close()
    }
    check(err)
    body, err := ioutil.ReadAll(resp.Body)
    check(err)
    assert(strings.HasPrefix(string(body), "<!doctype html"))
}

Consider closing requests right after a response. Important if doing a lot of requests to different HTTP servers. But it's a good practice to keep connections open if you are doing multiple requests to the same server.

package main

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

func main() {
    req, err := http.NewRequest("GET", "http://golang.org", nil)
    if err != nil {
        fmt.Println(err)
        return
    }

    req.Close = true // or req.Header.Add("Connection", "close")

    resp, err := http.DefaultClient.Do(req)
    if resp != nil {
        defer resp.Body.Close()
    }

    if err != nil {
        fmt.Println(err)
        return
    }

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(len(string(body)))
}

Sources