summaryrefslogtreecommitdiffhomepage
path: root/main.go
blob: d6b8ae56e0b992355d8e2727e2f0125f3dfcdf15 (plain) (blame)
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
69
70
71
72
package main

import (
	"fmt"
	"flag"
	"os"

	bolt "go.etcd.io/bbolt"
	"github.com/go-redis/redis/v7"
	"github.com/valyala/fasthttp"
	"toast.cafe/x/brpaste/v2/http"
	"toast.cafe/x/brpaste/v2/storage"
)

var s settings

type settings struct {
	Bind    string
	Bolt    string
	Redis   string
	Storage string
}

func main() {
	// ---- Flags
	flag.StringVar(&s.Bind, "bind", ":8080", "address to bind to")
	flag.StringVar(&s.Bolt, "bolt", "brpaste.db", "bolt database file to use")
	flag.StringVar(&s.Redis, "redis", "redis://localhost:6379", "redis connection string")
	flag.StringVar(&s.Storage, "storage", "bolt", "type of storage to use")
	flag.Parse()

	// ---- Storage system
	var store storage.CHR

	switch s.Storage {
	case "memory":
		store = storage.NewMemory()
	case "redis":
		redisOpts, err := redis.ParseURL(s.Redis)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not parse redis connection string %s\n", s.Redis)
			os.Exit(1)
		}
		client := redis.NewClient(redisOpts)
		store = (*storage.Redis)(client)
	case "bolt":
		db, err := bolt.Open(s.Bolt, 0600, nil)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to open/create boltdb database at %s\n", s.Bolt)
			os.Exit(1)
		}
		store, err = storage.OpenBolt(db)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to initialize boltdb database at %s: %s\n", s.Bolt, err)
			os.Exit(1)
		}
		defer db.Close()
	default:
		fmt.Fprintf(os.Stderr, "Could not figure out which storage system to use, tried %s\n", s.Storage)
		os.Exit(1)
	}

	// ---- Is storage healthy?
	if !store.Healthy() {
		fmt.Fprintf(os.Stderr, "Storage is unhealthy, cannot proceed.\n")
		os.Exit(1)
	}

	// ---- Start!
	handler := http.GenHandler(store)
	fasthttp.ListenAndServe(s.Bind, handler)
}