oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/go/http_server.txt
1.4 KiB, 1 run
created by r1870400018:11978, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "log" |
| 7 | "net/http" |
| 8 | "strings" |
| 9 | "sync/atomic" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | var requestCount uint64 |
| 14 | |
| 15 | type StatusResponse struct { |
| 16 | Uptime string `json:"uptime"` |
| 17 | Requests uint64 `json:"requests"` |
| 18 | } |
| 19 | |
| 20 | func statusHandler(startTime time.Time) http.HandlerFunc { |
| 21 | return func(w http.ResponseWriter, r *http.Request) { |
| 22 | count := atomic.AddUint64(&requestCount, 1) |
| 23 | resp := StatusResponse{ |
| 24 | Uptime: time.Since(startTime).String(), |
| 25 | Requests: count, |
| 26 | } |
| 27 | w.Header().Set("Content-Type", "application/json") |
| 28 | json.NewEncoder(w).Encode(resp) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func echoHandler(w http.ResponseWriter, r *http.Request) { |
| 33 | atomic.AddUint64(&requestCount, 1) |
| 34 | path := strings.TrimPrefix(r.URL.Path, "/echo/") |
| 35 | fmt.Fprintf(w, "echo: %s\n", path) |
| 36 | } |
| 37 | |
| 38 | func loggingMiddleware(next http.Handler) http.Handler { |
| 39 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 40 | start := time.Now() |
| 41 | next.ServeHTTP(w, r) |
| 42 | log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start)) |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | func main() { |
| 47 | startTime := time.Now() |
| 48 | mux := http.NewServeMux() |
| 49 | mux.HandleFunc("/status", statusHandler(startTime)) |
| 50 | mux.HandleFunc("/echo/", echoHandler) |
| 51 | |
| 52 | server := &http.Server{ |
| 53 | Addr: ":8080", |
| 54 | Handler: loggingMiddleware(mux), |
| 55 | ReadTimeout: 5 * time.Second, |
| 56 | WriteTimeout: 10 * time.Second, |
| 57 | } |
| 58 | |
| 59 | log.Printf("listening on %s", server.Addr) |
| 60 | log.Fatal(server.ListenAndServe()) |
| 61 | } |