Saltar al contenido
Snippets·Gratis

Snippets de Go

20 snippets de Go: handlers HTTP y un ServeMux, errores envueltos con %w, goroutines con WaitGroup, select con tiempo límite, tests con tabla de casos, structs JSON y genéricos. Algunos necesitan Go 1.21 o 1.22.

Se instala gratis.

Si tienes PocketCode instalado en tu Android, esto abre la página en la app.

Vista previa

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}")

Cambios en la 1.0.0

Primera versión.

Relacionados