golang http context
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8080", nil)
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
fmt.Fprintf(w, "Context type: %T\n", ctx)
fmt.Fprintf(w, "Context value: %v\n", ctx)
ctx = context.WithValue(ctx, "userID", 123)
userID := ctx.Value("userID").(int)
fmt.Fprintf(w, "UserID: %d\n", userID)
}
Explanation:
package main
: Declares the package as "main" which makes this package an executable program rather than a reusable library.import
: Imports necessary packages."fmt"
for formatted I/O and"net/http"
for HTTP handling.func main()
: Entry point of the program. Registers a handler function for the "/hello" route and starts an HTTP server listening on port 8080.http.HandleFunc("/hello", helloHandler)
: Registers thehelloHandler
function to be executed when the "/hello" route is accessed.func helloHandler(w http.ResponseWriter, r *http.Request)
: Defines thehelloHandler
function which takes in anhttp.ResponseWriter
and anhttp.Request
as parameters.ctx := r.Context()
: Retrieves the context associated with the incoming HTTP requestr
.fmt.Fprintf(w, "Context type: %T\n", ctx)
: Writes the type of the context to the response writerw
.fmt.Fprintf(w, "Context value: %v\n", ctx)
: Writes the value of the context to the response writerw
.ctx = context.WithValue(ctx, "userID", 123)
: Creates a new context derived from the originalctx
with a key "userID" and value 123.userID := ctx.Value("userID").(int)
: Retrieves the value associated with the key "userID" from the contextctx
and asserts its type toint
.fmt.Fprintf(w, "UserID: %d\n", userID)
: Writes the user ID extracted from the context to the response writerw
.