forked from mtlynch/picoshare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (54 loc) · 1.46 KB
/
main.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"time"
gorilla "github.com/mtlynch/gorilla-handlers"
"github.com/mtlynch/picoshare/v2/garbagecollect"
"github.com/mtlynch/picoshare/v2/handlers"
"github.com/mtlynch/picoshare/v2/handlers/auth/shared_secret"
"github.com/mtlynch/picoshare/v2/store/sqlite"
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.Print("Starting picoshare server")
dbPath := flag.String("db", "data/store.db", "path to database")
flag.Parse()
authenticator, err := shared_secret.New(requireEnv("PS_SHARED_SECRET"))
if err != nil {
log.Fatalf("invalid shared secret: %v", err)
}
ensureDirExists(filepath.Dir(*dbPath))
store := sqlite.New(*dbPath)
gc := garbagecollect.NewScheduler(store, 7*time.Hour)
gc.StartAsync()
h := gorilla.LoggingHandler(os.Stdout, handlers.New(authenticator, store).Router())
if os.Getenv("PS_BEHIND_PROXY") != "" {
h = gorilla.ProxyIPHeadersHandler(h)
}
http.Handle("/", h)
port := os.Getenv("PORT")
if port == "" {
port = "4001"
}
log.Printf("Listening on %s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
func requireEnv(key string) string {
val := os.Getenv(key)
if val == "" {
panic(fmt.Sprintf("missing required environment variable: %s", key))
}
return val
}
func ensureDirExists(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.Mkdir(dir, os.ModePerm); err != nil {
panic(err)
}
}
}