๐Ÿ“ฆ veggiemonk / lingonweb

๐Ÿ“„ dev.go ยท 61 lines
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
61package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

const port = ":8081"

func main() {
	log.SetFlags(0)
	log.Print("starting the service...")
	defer log.Print("shutting down the service...")
	// Closing signal
	stopChan := make(chan os.Signal, 1)
	signal.Notify(
		stopChan,
		// syscall.SIGKILL, // never gets caught on POSIX
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT,
	)
	sm := http.NewServeMux()

	sm.Handle("/", l{})
	srv := &http.Server{
		Addr:    port,
		Handler: sm,
	}
	log.Println("serving on", port)
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatal(err)
		}
	}()

	<-stopChan
	ctxShutDown, cancel := context.WithTimeout(
		context.Background(),
		time.Second*10,
	)
	defer func() { cancel() }()

	if err := srv.Shutdown(ctxShutDown); err != nil {
		log.Fatalf("server Shutdown Failed: %v", err)
	}

}

type l struct{}

func (b l) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Printf("[%s] serving %s\n", time.Now().Format(time.RFC3339), r.URL.Path)
	http.FileServer(http.Dir(".")).ServeHTTP(w, r)
}