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:

  1. package main: Declares the package as "main" which makes this package an executable program rather than a reusable library.

  2. import: Imports necessary packages. "fmt" for formatted I/O and "net/http" for HTTP handling.

  3. func main(): Entry point of the program. Registers a handler function for the "/hello" route and starts an HTTP server listening on port 8080.

  4. http.HandleFunc("/hello", helloHandler): Registers the helloHandler function to be executed when the "/hello" route is accessed.

  5. func helloHandler(w http.ResponseWriter, r *http.Request): Defines the helloHandler function which takes in an http.ResponseWriter and an http.Request as parameters.

  6. ctx := r.Context(): Retrieves the context associated with the incoming HTTP request r.

  7. fmt.Fprintf(w, "Context type: %T\n", ctx): Writes the type of the context to the response writer w.

  8. fmt.Fprintf(w, "Context value: %v\n", ctx): Writes the value of the context to the response writer w.

  9. ctx = context.WithValue(ctx, "userID", 123): Creates a new context derived from the original ctx with a key "userID" and value 123.

  10. userID := ctx.Value("userID").(int): Retrieves the value associated with the key "userID" from the context ctx and asserts its type to int.

  11. fmt.Fprintf(w, "UserID: %d\n", userID): Writes the user ID extracted from the context to the response writer w.