跳转到内容
代码片段·免费

Go 代码片段

20 个 Go 代码片段:HTTP handler 和 ServeMux、用 %w 包装错误、配合 WaitGroup 的 goroutine、带超时的 select、表驱动测试、JSON 结构体和泛型。少数需要 Go 1.21 或 1.22。

免费安装。

如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。

预览

20 个中的 5 个

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

1.0.0 的变更

首个版本。

相关