main.go 1.7 K raw
1
package main
2
3
import (
4
	"context"
5
	_ "embed"
6
	"encoding/json"
7
	"fmt"
8
	"log"
9
	"net/http"
10
	"os"
11
	"os/signal"
12
	"syscall"
13
	"time"
14
)
15
16
func main() {
17
	http.HandleFunc("/", serveHTML)
18
	http.HandleFunc("/events", handleSSE)
19
20
	server := &http.Server{Addr: ":4321"}
21
22
	go func() {
23
		fmt.Println("Server is running on http://localhost:4321")
24
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
25
			log.Fatalf("Server error: %v", err)
26
		}
27
	}()
28
29
	stop := make(chan os.Signal, 1)
30
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
31
32
	<-stop
33
34
	fmt.Println("Shutting down server...")
35
36
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
37
	defer cancel()
38
39
	if err := server.Shutdown(ctx); err != nil {
40
		log.Printf("Error during server shutdown: %v", err)
41
	}
42
43
	fmt.Println("Server stopped")
44
}
45
46
//go:embed index.html
47
var indexHTML string
48
49
func serveHTML(w http.ResponseWriter, r *http.Request) {
50
	w.Header().Set("Content-Type", "text/html")
51
	w.Write([]byte(indexHTML))
52
}
53
54
func handleSSE(w http.ResponseWriter, r *http.Request) {
55
	w.Header().Set("Content-Type", "text/event-stream")
56
	w.Header().Set("Cache-Control", "no-cache")
57
	w.Header().Set("Connection", "keep-alive")
58
59
	log.Println("SSE connection established")
60
61
	for {
62
		combinedStats, err := getStats()
63
		if err != nil {
64
			log.Printf("Error getting IPFS Stats: %v", err)
65
			time.Sleep(1 * time.Second)
66
			continue
67
		}
68
69
		data, err := json.Marshal(combinedStats)
70
		if err != nil {
71
			log.Printf("Error marshaling IPFS stats: %v", err)
72
			time.Sleep(1 * time.Second)
73
			continue
74
		}
75
76
		_, err = fmt.Fprintf(w, "data: %s\n\n", data)
77
		if err != nil {
78
			log.Printf("Error writing to response: %v", err)
79
			return
80
		}
81
		w.(http.Flusher).Flush()
82
83
		time.Sleep(1 * time.Second)
84
	}
85
}