概要
Stackoverflowには Go Collective というのがあります。
The official Q&A channel for Google's Go Programming Language.
と書いてある通り、公式のQ&Aとなっていて、いい質問と回答が揃っています。
ついでなので、自分の勉強も兼ねて、ここにメモメモ。。。
今回はコレ。
サンプル
main.go
// Stackoverflow Go Collective example // // How to retrieve values from URL // // URL // - https://stackoverflow.com/questions/73079531/how-to-retrieve-values-from-the-url-in-go // // REFERENCES // - https://pkg.go.dev/net/http@latest // - https://stackoverflow.com/questions/39320025/how-to-stop-http-listenandserve package main import ( "context" "fmt" "net/http" "time" ) func main() { var ( mux = http.NewServeMux() srv = &http.Server{Addr: ":8888", Handler: mux} ctx, cxl = context.WithTimeout(context.Background(), 3*time.Second) ) defer cxl() mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() fmt.Println(query.Get("message")) }) go func() { srv.ListenAndServe() }() go func() { for { _, err := http.Get("http://localhost:8888/hello?message=world") if err == nil { break } } }() <-ctx.Done() srv.Shutdown(ctx) }
Taskfile.yml
version: '3' tasks: imports: cmds: - goimports -w . vet: cmds: - go vet . run: cmds: - go run -race main.go
実行すると以下のようになります。
gitpod /workspace/try-golang (master) $ task -d examples/gocollective/retrive-values-from-url/ run task: [run] go run -race main.go world
参考情報
過去の記事については、以下のページからご参照下さい。
サンプルコードは、以下の場所で公開しています。