forked from practicalgo/code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
executable file
·87 lines (71 loc) · 1.69 KB
/
server.go
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
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"time"
)
func handlePing(w http.ResponseWriter, r *http.Request) {
log.Println("ping: Got a request")
time.Sleep(3 * time.Second)
fmt.Fprintf(w, "pong")
}
func doSomeWork(data []byte) {
time.Sleep(5 * time.Second)
}
func handleUserAPI(w http.ResponseWriter, r *http.Request) {
done := make(chan bool)
log.Println("I started processing the request")
req, err := http.NewRequestWithContext(
r.Context(),
"GET",
"http://localhost:8080/ping", nil,
)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
client := &http.Client{}
log.Println("Outgoing HTTP request")
resp, err := client.Do(req)
if err != nil {
log.Printf("Error making request: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
log.Println("Processing the response i got")
go func() {
doSomeWork(data)
done <- true
}()
select {
case <-done:
log.Println("doSomeWork done: Continuing request processing")
case <-r.Context().Done():
log.Printf("Aborting request processing: %v\n", r.Context().Err())
return
}
fmt.Fprint(w, string(data))
log.Println("I finished processing the request")
}
func main() {
listenAddr := os.Getenv("LISTEN_ADDR")
if len(listenAddr) == 0 {
listenAddr = ":8443"
}
timeoutDuration := 30 * time.Second
userHandler := http.HandlerFunc(handleUserAPI)
hTimeout := http.TimeoutHandler(
userHandler,
timeoutDuration,
"I ran out of time",
)
mux := http.NewServeMux()
mux.Handle("/api/users/", hTimeout)
mux.HandleFunc("/ping", handlePing)
log.Fatal(http.ListenAndServe(":8080", mux))
}