Skip to content

Go cheatsheet

Basic usage

Initialize application

go mod init your-app-name

Install packages

go mod tidy

Build application

go build

Build file

go build main.go

hello world

package main

import "fmt"

func main() {
  message := hello("world")
  fmt.Println(message)
}

func hello(name string) string {
  return "Hello, " + name + "!"
}

Variables

Variable declaration

var a = "string"
var b, c int = 1, 2
var d = true
var e int

// declare and initialize
f := "apple"

Send HTTP POST request with hashicorp/go-retryablehttp, retry 3 times if return code is different than 200, disable logging:

url := "<URL>"
body := []byte(pass)
r, _ := retryablehttp.NewRequest("POST", url, bytes.NewBuffer(body))

client := retryablehttp.NewClient()
client.Logger = nil
client.RetryMax = 3
client.CheckRetry = func(ctx context.Context, resp *http.Response, err error) (bool, error) {
  ok, e := retryablehttp.DefaultRetryPolicy(ctx, resp, err)
  if !ok && resp.StatusCode != http.StatusOK {
    return true, nil
  }
  return ok, e
}

_, err = client.Do(r)

References