-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
75 lines (61 loc) · 1.68 KB
/
main.go
File metadata and controls
75 lines (61 loc) · 1.68 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"
"io"
"log"
"net/http"
"os"
"os/signal"
"time"
"simple-pub-sub/pubsub"
)
var service = pubsub.NewPubSubService()
func handlePublishRequest(w http.ResponseWriter, r *http.Request) {
topicName := r.PathValue("topic")
// Read the message body from the HTTP request.
body, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading request body: %s", err)
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
if err := service.Publish(topicName, string(body)); err != nil {
log.Printf("Error while publishing message: %s", err)
http.Error(w, "Error while publishing message", http.StatusInternalServerError)
return
}
}
func handleWSSubscribeRequest(w http.ResponseWriter, r *http.Request) {
if err := service.Subscribe(w, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("POST /pub/{topic}", handlePublishRequest)
http.HandleFunc("GET /ws/sub/{topic}", handleWSSubscribeRequest)
srv := &http.Server{
Addr: ":" + func() string {
p := os.Getenv("PORT")
if p == "" {
return "8080"
}
return p
}(),
}
go func() {
log.Printf("Listening on %s\n", srv.Addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server error: %v", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
log.Println("Shutting down server gracefully…")
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shut down: %v", err)
}
log.Println("Server stopped")
}