GoLang Cheatsheet

October 13, 2019

Parse JSON

type Data struct {
  Id string `json:"id"`
}
var data Data
json.Unmarshal("{ \"id\": \"123\" }", &data)

Serialize JSON

type Data struct {}
var data = Data{}
str, _ := json.Marshal(data)

Print a Struct

type Data struct {
  Id int
}
var data Data{Id: 123}
fmt.Printf("%+v\n", data)

Execute a command

out, _ := exec.Commmand("ls").Output()

Simple Server

func main() {
  http.HandleFunc(func (w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("ok"))
  })
  err := http.ListenAndServe(":1234", nil)
  if err != nil {
    fmt.Println(err)
  }
}

Read a File

res, _ := ioutil.ReadFile("/tmp/test.txt")
fmt.Println(string(res))

Write to File

res, _ := ioutil.WriteFile("/tmp/test.txt", []byte("Hello"), 0644)

Command Line Arguments

args := os.Args[1:]

Iterating Over Slices

func main() {
  numbers := []int{1, 2, 3}
  for x, y := range numbers {
    fmt.Println(x, y)
  }
}

Tickers

func main() {
  done := make(chan bool, 1)
  tick := time.Tick(1 * time.Second)
  timeout := time.After(5 * time.Second)
  go func() {
    for {
      select {
      case <-tick:
        fmt.Println("tick")
      case <-timeout:
        done <- true
        fmt.Println("timeout!")
        return  
      }
    }
  }()
  <-done
}

Get Request

func fetch() {
  res, _ := http.Get("https://jsonplaceholder.typicode.com/todos/1")
  body, _ := ioutil.ReadAll(res.Body)
  raw := string(body)
  return raw
}

Post Request

body := strings.NewReader("{ \"message\": \"ok\" }")
http.Post("http://requestbin.fullcontact.com/1hp80td1", "application/json", body)

Split a String

str := "ab cd ef"
arr := strings.Split(str, " ")