updated to goroutine 431f6eec
Steve · 2024-08-25 22:15 1 file(s) · +29 −2
main.go +29 −2
1 1
package main
2 2
3 3
import (
4 +
	"context"
4 5
	_ "embed"
5 6
	"encoding/json"
6 7
	"fmt"
7 8
	"io/ioutil"
8 9
	"log"
9 10
	"net/http"
11 +
	"os"
12 +
	"os/signal"
13 +
	"syscall"
10 14
	"time"
11 15
12 16
	"github.com/shirou/gopsutil/cpu"
48 52
func main() {
49 53
	http.HandleFunc("/", serveHTML)
50 54
	http.HandleFunc("/events", handleSSE)
51 -
	fmt.Println("Server is running on http://localhost:4321")
52 -
	log.Fatal(http.ListenAndServe(":4321", nil))
55 +
56 +
	server := &http.Server{Addr: ":4321"}
57 +
58 +
	go func() {
59 +
		fmt.Println("Server is running on http://localhost:4321")
60 +
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
61 +
			log.Fatalf("Server error: %v", err)
62 +
		}
63 +
	}()
64 +
65 +
	stop := make(chan os.Signal, 1)
66 +
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
67 +
68 +
	<-stop
69 +
70 +
	fmt.Println("Shutting down server...")
71 +
72 +
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
73 +
	defer cancel()
74 +
75 +
	if err := server.Shutdown(ctx); err != nil {
76 +
		log.Printf("Error during server shutdown: %v", err)
77 +
	}
78 +
79 +
	fmt.Println("Server stopped")
53 80
}
54 81
55 82
//go:embed index.html