Skip to content

Go

Start a Project

sh
go mod init example.com/project

Add Dependencies

sh
go get package_name

For a local module during development, add a replace directive to go.mod:

txt
replace example.com/cli => ../cli-parser

HTTP Request Template

go
client := &http.Client{}

req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
  // handle error
  return err
}

req.Header.Set("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
  // handle error
  return err
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
  // handle error
  return err
}

JSON Parsing Template

go
type Job struct {
  Title string `json:"title"`
}

type Result struct {
  Name      string `json:"name"`
  Surname   string `json:"surname,omitempty"`
  Education struct {
    University string `json:"university"`
  } `json:"education"`
  Job *Job `json:"job"`
}

var result Result

// Parse from a byte slice.
err := json.Unmarshal(data, &result)

// Parse directly from an io.Reader.
err = json.NewDecoder(reader).Decode(&result)