Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
75 lines (59 loc) · 1.79 KB
/
Copy pathmain.go
File metadata and controls
75 lines (59 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"context"
"os/exec"
"fmt"
"log"
"net/http"
"time"
"github.com/google/uuid"
"go.uber.org/zap"
)
func requestHandler(w http.ResponseWriter, r *http.Request) {
logger := zap.Must(zap.NewDevelopment())
defer logger.Sync()
// Extract the request ID from the context or generate a new one if it doesn't exist
requestID, ok := r.Context().Value("requestID").(string)
if !ok {
log.Printf("No Request ID in http request")
}
reqLogger := logger.With(
zap.String("requestID", requestID),
)
reqLogger.Info("Incoming request")
// Define a context with a timeout of 5 seconds
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
// Command to be executed
cmd := exec.CommandContext(ctx, "sleep", "10")
// Run the command and capture its output
output, err := cmd.CombinedOutput()
if err != nil {
// Check if the error is due to context timeout
if ctx.Err() == context.DeadlineExceeded {
reqLogger.Error("Command timed out")
} else {
// Handle other errors
reqLogger.Error("Command failed with error: %v\n", zap.Error(err))
}
}
// Send response to the client
fmt.Fprintf(w, "sleep: %s", output)
}
func main() {
// Create a new HTTP server mux
mux := http.NewServeMux()
// Handle requests with the requestHandler function and use context.WithValue to set the request ID in the context
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Create a context with the request ID and pass it to the requestHandler
ctx := context.WithValue(r.Context(), "requestID", uuid.New().String())
requestHandler(w, r.WithContext(ctx))
})
// Start the HTTP server
port := ":8080"
log.Printf("Server listening on port %s", port)
err := http.ListenAndServe(port, mux)
if err != nil {
log.Fatalf("Server error: %v", err)
}
}