Pular para o conteúdo
Snippets·Grátis

Snippets de Go

20 snippets de Go: handlers HTTP e um ServeMux, erros encapsulados com %w, goroutines com WaitGroup, select com tempo limite, testes orientados a tabela, structs JSON e genéricos. Alguns precisam do Go 1.21 ou 1.22.

Instalação grátis.

Se o PocketCode estiver instalado no seu Android, isto abre a página no app.

Prévia

5 de 20

HTTP handlerhandler

net/http handler that sets a JSON content type

func ${1:handleHealth}(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    ${2:w.WriteHeader(http.StatusOK)}
    $0
}

HTTP server with a muxhttpserve

ServeMux with a method pattern (Go 1.22+) and ListenAndServe

mux := http.NewServeMux()
mux.HandleFunc("${1:GET /health}", ${2:handleHealth})
log.Fatal(http.ListenAndServe("${3::8080}", mux))

Wrap an errorwraperr

Return the error with context, keeping it checkable with errors.Is

if err != nil {
    return fmt.Errorf("${1:load config}: %w", err)
}

Check an error typeerrsas

errors.As to get a specific error type out of a chain

var ${1:pathErr} *${2:fs.PathError}
if errors.As(err, &${1:pathErr}) {
    $0
}

Sentinel errorerrvar

Package-level error value to compare with errors.Is

var Err${1:NotFound} = errors.New("${2:not found}")

Mudanças na 1.0.0

Primeira versão.

Relacionados