Golang Useful Functions Cheatsheet

Tags : go golang google gist

GET Request with net/http
url := "https://www.domain/endpoint"

resp, err := http.Get(url)
if err != nil {
	// Handle error
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)

// Response Status:      resp.Status -> "200 OK"
// Response Status Code: resp.StatusCode -> 200
// Response Body:        string(body)
POST Request with net/http
url := "https://www.domain/endpoint"

var jsonPayload = []byte(`{"key":"value"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload))
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    // Handle error
}
defer resp.Body.Close()

body, _ := ioutil.ReadAll(resp.Body)

// Response Status:      resp.Status -> "200 OK"
// Response Status Code: resp.StatusCode -> 200
// Response Body:        string(body)
Start server
package main

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

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello %s", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Recover in a goroutine
defer func() {
    if r := recover(); r != nil {
        // Do something with r
    }
}()
Rewind response body
body, _ := ioutil.ReadAll(resp.Body)
// Do something with the body...
// Rewind
resp.Body = ioutil.NopCloser(bytes.NewBuffer(body))
Middleware Wrapper
package web

type Middleware func(Handler) Handler

func wrapMiddleware(mw []Middleware, handler Handler) Handler {
    for i := len(mw) - 1; i >= 0; i-- {
        h := mw[i]
        if h != nil {
            handler = h(handler)
        }
    }
    return handler
}
Mock HTTP calls in tests using httptest.NewServer
ts := httptest.NewServer(
    http.HandlerFunc(
        func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintln(w, "Mock the response here")
        },
    ),
)
defer ts.Close()

res, err := http.Get(ts.URL)
if err != nil {
    log.Fatal(err)
}
mockRes, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
    log.Fatal(err)
}