-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserve.go
54 lines (42 loc) · 948 Bytes
/
serve.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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"time"
)
const serveAddr = "localhost:8080"
var ServeCmd = &Command{
Usage: "serve",
Short: "serve the published jrnl",
Run: serveCmd,
}
func serveCmd(cmd *Command, args []string) error {
if err := Initialized("."); err != nil {
return err
}
srv := http.Server{
Addr: serveAddr,
ReadTimeout: time.Second * 10,
WriteTimeout: time.Second * 10,
Handler: http.FileServer(http.Dir(siteDir)),
}
go func() {
if err := srv.ListenAndServe(); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
fmt.Fprintf(os.Stderr, "%s: %s\n", cmd.Argv0, err)
}
}
}()
fmt.Println("serving contents of", siteDir, "over", serveAddr)
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
<-ch
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer cancel()
srv.Shutdown(ctx)
return nil
}