experiment

This commit is contained in:
unintendedfraud
2024-03-08 03:28:24 +01:00
parent ef3410470a
commit 848b9fc51a
2 changed files with 50 additions and 9 deletions
+13 -6
View File
@@ -1,19 +1,21 @@
package main
import (
"context"
"fmt"
"math/rand"
"net/http"
"time"
)
const PORT = 8080
func main() {
server := Server{}
server := NewServer(3 * time.Second)
server.Handle(
"/get-random-number",
printHello,
addValueToContext,
handleGetRandomNumber,
)
@@ -25,14 +27,19 @@ func main() {
func handleGetRandomNumber(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Random number: ", rand.Int())
fmt.Println("Random number: ", r.Context().Value("number"))
w.Write([]byte(`{"error": "process timeout"}`))
})
}
func printHello(next http.Handler) http.Handler {
func addValueToContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("hello")
n := rand.Intn(50)
ctx := context.WithValue(r.Context(), "number", n)
fmt.Println("add value to context: ", n)
next.ServeHTTP(w, r)
time.Sleep(10 * time.Second)
next.ServeHTTP(w, r.WithContext(ctx))
})
}