|
1 | 1 | package main |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "context" |
4 | 5 | "fmt" |
5 | 6 | "io" |
6 | 7 | "net/http" |
| 8 | + "os" |
| 9 | + "os/signal" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/creativeprojects/clog" |
7 | 13 | ) |
8 | 14 |
|
9 | 15 | func serveCommand(w io.Writer, cmdCtx commandContext) error { |
10 | 16 | if len(cmdCtx.flags.resticArgs) < 2 { |
11 | 17 | return fmt.Errorf("missing argument: port") |
12 | 18 | } |
13 | | - handler := http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { |
14 | | - resp.Write([]byte("Hello, World!")) |
| 19 | + handler := http.NewServeMux() |
| 20 | + handler.HandleFunc("GET /configuration/{remote}", func(resp http.ResponseWriter, req *http.Request) { |
| 21 | + remoteName := req.PathValue("remote") |
| 22 | + if !cmdCtx.config.HasRemote(remoteName) { |
| 23 | + resp.WriteHeader(http.StatusNotFound) |
| 24 | + resp.Write([]byte("remote not found")) |
| 25 | + return |
| 26 | + } |
| 27 | + remote, err := cmdCtx.config.GetRemote(remoteName) |
| 28 | + if err != nil { |
| 29 | + resp.WriteHeader(http.StatusBadRequest) |
| 30 | + resp.Write([]byte(err.Error())) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + clog.Infof("sending configuration for %q", remoteName) |
| 35 | + resp.Header().Set("Content-Type", "application/x-tar") |
| 36 | + resp.WriteHeader(http.StatusOK) |
| 37 | + sendFiles(resp, remote.SendFiles) |
15 | 38 | }) |
| 39 | + |
| 40 | + quit := make(chan os.Signal, 1) |
| 41 | + signal.Notify(quit, os.Interrupt) |
| 42 | + defer signal.Stop(quit) |
| 43 | + |
16 | 44 | server := &http.Server{ |
17 | 45 | Addr: fmt.Sprintf("localhost:%s", cmdCtx.flags.resticArgs[1]), |
18 | 46 | Handler: handler, |
19 | 47 | } |
| 48 | + |
| 49 | + // put the shutdown code in a goroutine |
| 50 | + go func(server *http.Server, quit chan os.Signal) { |
| 51 | + <-quit |
| 52 | + |
| 53 | + clog.Info("shutting down the server") |
| 54 | + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 55 | + defer cancel() |
| 56 | + |
| 57 | + err := server.Shutdown(ctx) |
| 58 | + if err != nil { |
| 59 | + clog.Errorf("error while shutting down the server: %v", err) |
| 60 | + } |
| 61 | + |
| 62 | + }(server, quit) |
| 63 | + |
| 64 | + // we want to return the server error if any so we need to keep it in the main thread. |
| 65 | + clog.Infof("listening on %s", server.Addr) |
20 | 66 | err := server.ListenAndServe() |
21 | 67 | if err != nil && err != http.ErrServerClosed { |
22 | 68 | return err |
|
0 commit comments