Go language cheat sheet

Overview

Summary of processing that I often forget even though I write go and use it often If you remember, add them one by one

Context

https://pkg.go.dev/context

A context is a structure that manages the environment, scope, timeout, etc. in a tree format. It's a very important concept in writing go.

import (
    "context"
)

ctx := context.Background()

ctx, cancel := context.WithCancel(ctx)
defer cancel()

store

package main

import "context"
import "log"

func main() {
	ctx := context.Background()
	ctx = context.WithValue(ctx, "silly", "work")

	value := ctx.Value("silly")
 // The return value is interface {}, so you need to cast the value
	str, ok := value.(string)
	if !ok {
		log.Println("value not found")
	}

	log.Printf("value found: '%s'", str)

 // This is the abbreviation above
	str, ok = ctx.Value("silly").(string)
	log.Printf("re value found: '%s'", str)
}

Time-out processing

package main

import (
	"context"
	"time"
	"log"
)

func main(){
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, time.Second * 1)
	defer cancel()

	go func(){
		// too many time function
		time.Sleep(time.Second * 10)
	}()

	<-ctx.Done()

	log.Println("done")
}

Environment variable

If you have a small number of variables to refer to, you can use os.Getenv () normally.

import "os"

debug := os.Getenv("DEBUG")

If you want default values ​​or required values ​​like DB settings, it is convenient to use https://github.com/caarlos0/env/

package main

import (
	"log"

	"github.com/caarlos0/env/v6"
)

type DatabaseConfig struct {
	UserName string `env:"DB_USER,required"`
	Password string `env:"DB_PASSWORD,required"`
	Host     string `env:"DB_HOST" envDefault:"localhost"`
	Port     string `env:"DB_PORT" envDefault:"3306"`
	DBName   string `env:"DB_NAME"`
}

func main() {
	cfg := new(DatabaseConfig)

	if err := env.Parse(cfg); err != nil {
		log.Printf("%+v\n", err)
	}

	log.Printf("%+v\n", cfg)
}

JSON

package main

import "encoding/json"

type Valiable struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

func load(obj []byte) (*Valiable, error) {
	valiable := new(Valiable)
	err := json.Unmarshal(obj, valiable)

	return valiable, err
}

func dump(valiable *Valiable) ([]byte, error) {
	return json.Marshal(valiable)
}

func main() {
	object := []byte(`{"key": "egg", "value": "spam"}`)

	// to struct
	valiable, _ := load(object)

	// to []byte
	obj, _ := dump(valiable)

	_ = obj
}

io

Read file

package main

import (
	"os"
	"log"
	"io/ioutil"
)

func main() {
	file, err := os.Open("test.bin")
	if err != nil {
 // no such file or permission error
 // If you omit this handling, there is nothing wrong with it
		log.Fatal(err)
	}
 // Write a close defer at this timing
	defer file.Close()

 // Rough work to read everything with [] bytes
	b, err := ioutil.ReadAll(file)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(b)


 /// A great guy who does the whole flow from open to Readall
	content, err := ioutil.ReadFile("test.bin")
	if err != nil {
		log.Fatal(err)
	}
	log.Println(content)
}

log

https://pkg.go.dev/log https://pkg.go.dev/fmt

There are many examples of using fmt for standard output, but since it is not thread-safe, if goroutin is used a lot, the output may be mixed. It is safer to use log in actual operation

package main

import (
	"errors"
	"log"
)

func main() {
	log.Println("spam")                     // 2021/01/19 18:47:35 spam
	log.Println("egg", "bacon", "and spam") // 2021/01/19 18:51:04 egg bacon and spam

 // Printf is the same as fmt
	log.Printf("I'm a %s It's Ok", "Lumberjack") // 2021/01/19 19:53:54 I'm a Lumberjack It's Ok
	log.Printf("int: %d", 253)                   // 2021/01/19 19:51:39 int: 253
	log.Printf("hex: 0x%x", 253)                 // 2021/01/19 19:51:39 hex: 0xfd
	log.Printf("oct: 0o%o", 253)                 // 2021/01/19 19:51:39 oct: 0o375
	log.Printf("bin: 0b%b", 253)                 // 2021/01/19 19:51:39 bin: 0b11111101

	s := struct {
		ID   int
		Name string
	}{123, "Graham"}

 // Useful when dumping structures
	log.Printf("%+v", s) // 2021/01/19 19:50:00 {ID:123 Name:Graham}

	log.SetPrefix("[log] ")
 log.Println ("prefix") // [log] 2021/01/19 18:50:07 Prefix
	log.SetPrefix("")

	log.SetFlags(log.Flags() | log.LUTC)
 log.Println ("Time timezone uses default, but can be UTC by adding a flag") // 2021/01/19 09:57:09 Timetime zone uses default, but flag Can be UTC by adding

	log.SetFlags(0)
 log.Println ("You can turn off the time output by removing all the flags") // You can turn off the time display by setting the flag

	log.SetFlags(log.Ldate | log.Lmicroseconds)
 log.Println ("Notation up to microseconds") // 2021/01/19 18: 57: 09.086480 Notation up to microseconds

 log.Fatal (errors.New ("some error")) // Output the error content and exit with status code 1.
}

panic

package main

import (
	"log"
)

func main() {
	defer func() {
		e := recover()
		if e != nil {
			str, _ := e.(string)
			log.Println("panic:", str)
		}
	}()

	panic("example panic")
}

Recommended Posts

Go language cheat sheet
Curry cheat sheet
SQLite3 cheat sheet
pyenv cheat sheet
conda command cheat sheet
PIL / Pillow cheat sheet
Linux command cheat sheet
Go language learning record
Go language environment construction
ps command cheat sheet
Spark API cheat sheet
Python3 cheat sheet (basic)
Python sort cheat sheet
Features of Go language
tox configuration file cheat sheet
numpy memory reuse cheat sheet
[Python3] Standard input [Cheat sheet]
Data Science Cheat Sheet (Python)
Slack API attachments cheat sheet
go language learning miscellaneous notes 1
[Golang] About Go language channel
Hello World in GO language
Python Django Tutorial Cheat Sheet
scikit learn algorithm cheat sheet
Apache Beam Cheat Sheet [Python]
Google Test / Mock personal cheat sheet
Try implementing Yubaba in Go language
Use optinal type-like in Go language
Continuation Passing Style (CPS) Cheat Sheet
Python cheat sheet (for C ++ experienced)
Let's touch on the Go language
Post to slack in Go language
Go Language Spreadsheet Library: Excelize 2.3.2 Released
2021 Go Language Framework Star Count Comparison
Write tests in GO language + gin
Python Computation Library Cheat Sheet ~ itertools ~
Do something object-oriented in GO language
Execution environment test after Go language installation
[Golang] Go language basics What is Goroutine?
[GO language] Let's read a YAML file
AtCoder cheat sheet in python (for myself)
[MacOS] Installation of Go (Go language) using goenv
Blender Python Mesh Data Access Cheat Sheet
Mathematical Optimization Modeler (PuLP) Cheat Sheet (Python)
A brief description of pandas (Cheat Sheet)
[Golang] About Go language Producer and Consumer