Show Menu
Cheatography

Golang Cheat Sheet (DRAFT) by

Useful tips or reminders for Go lang

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Read POST Request (appli­cat­ion­/json)

type FormData struct­{...}
var fd FormData

// Option 1: With json decoder
err := json.N­ewD­eco­der­(re­q.B­ody­).D­eco­de(­&fd)

// Option 2: With json unmarshal
body, err := io.Rea­dAl­l(r­eq.B­ody)
if err == nil {
    err = json.U­nma­rsh­al(­body, &fd)
}

Loop through an struct var

_v := reflect.ValueOf(v)
for _i := 0; _i < _v.NumField(); _i++ {
    if _v.Kind() != reflect.Struct {
        logrus.Error("Dump expects struct instead of " + _v.Kind().String())
        return
    }
    fmt.Printf("%s = %s\n", _v.Type().Field(_i).Name, _v.Field(_i))
}
 

Futures

c := make(chan string, 1)
go func() {c <- process()}(). // async
v := <- c // await

Scatter / Gather

// Scatter
c := make(chan result, 10)
for i := 0; i < cap(c); i++ {
    go func() {
        val, err := process()
        c <- result{val, err}
    }()
}

// Gather
collection := make(string, cap(c))
for i := 0; i < cap(c); i++ {
    res := <- c
    if res.err == nil {
        collection[i] = res.val
    }
}
 

Consume services with http.C­lient

req, err := http.N­ewR­equ­est­("PO­ST", <ur­l>, <bo­dy>)
req.He­ade­r.A­dd(­"­Con­ten­t-t­ype­", "­app­lic­ati­on/­jso­n")
...
// call req
client := &h­ttp.Cl­ien­t{T­imeout: 15 * time.S­econd}
res, err := client.Do­(req)
...
// handle response
data, err := ioutil.Re­adA­ll(­res.Body)
json.Unmarshal(data, &v)