add ch14
This commit is contained in:
67
ch14/3/ch14_3.go
Normal file
67
ch14/3/ch14_3.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TimeHandler struct{}
|
||||
|
||||
func (th TimeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(time.Now().Format(time.RFC3339)))
|
||||
}
|
||||
|
||||
type Level string
|
||||
|
||||
const (
|
||||
Debug Level = "debug"
|
||||
Info Level = "info"
|
||||
)
|
||||
|
||||
func ExtractLogLevel(ctx context.Context) Level {
|
||||
return ctx.Value("log_level").(Level)
|
||||
}
|
||||
|
||||
func StoreLogLevel(ctx context.Context, level Level) context.Context {
|
||||
return context.WithValue(ctx, "log_level", level)
|
||||
}
|
||||
|
||||
func GetLogLevelQuery(http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
logLevel := r.URL.Query().Get("log_level")
|
||||
if logLevel != "info" && logLevel != "debug" {
|
||||
slog.Info("Wrong logLevel")
|
||||
}
|
||||
Log(StoreLogLevel(r.Context(), Level(logLevel)), Debug, "Test message")
|
||||
})
|
||||
}
|
||||
|
||||
func Log(ctx context.Context, level Level, message string) {
|
||||
var inLevel Level
|
||||
inLevel = ExtractLogLevel(ctx)
|
||||
if level == Debug && inLevel == Debug {
|
||||
fmt.Println(message)
|
||||
}
|
||||
if level == Info && (inLevel == Debug || inLevel == Info) {
|
||||
fmt.Println(message)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
server := http.Server{
|
||||
Addr: ":10100",
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 90 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
Handler: GetLogLevelQuery(TimeHandler{}),
|
||||
}
|
||||
err := server.ListenAndServe()
|
||||
if err != nil {
|
||||
if err != http.ErrServerClosed {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user