Skip to content

Instantly share code, notes, and snippets.

@dacr
Created March 28, 2025 09:02
Show Gist options
  • Save dacr/981a082667657468f6670015b6821872 to your computer and use it in GitHub Desktop.
Save dacr/981a082667657468f6670015b6821872 to your computer and use it in GitHub Desktop.
go context / published by https://github.com/dacr/code-examples-manager #7c71a8a9-8170-4ade-b396-58834bd30b03/58276355af21d0cef4f0455802c4b2608ea06831
/*?sr/bin/true; exec /usr/bin/env nix-shell -p go --run "go run $0" #*/
// summary : go context
// keywords : go, context, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 7c71a8a9-8170-4ade-b396-58834bd30b03
// created-on : 2025-03-27T16:56:13+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : nix-shell -p go --run "go run $file"
package main
import (
"context"
"io"
"net/http"
"time"
)
func main() {
// TODO => useful for example for tests, to study...
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", "https://example.com", nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
println("Error:", err.Error())
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
println("Error reading body:", err.Error())
return
}
bodyAsString := string(body)
println("Response Body:", bodyAsString)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment