server.go 1.06 KB
Newer Older
ale's avatar
ale committed
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
package main

import (
	"context"
	"flag"
	"log"
	"path/filepath"

	"github.com/google/subcommands"

	"git.autistici.org/ale/liber"
	"git.autistici.org/ale/liber/util"
)

type serverCommand struct {
	addr string
}

func (c *serverCommand) Name() string     { return "server" }
func (c *serverCommand) Synopsis() string { return "Run the HTTP server" }
func (c *serverCommand) Usage() string {
	return `server [<OPTIONS>]
  Run the HTTP server.

`
}

func (c *serverCommand) SetFlags(f *flag.FlagSet) {
	f.StringVar(&c.addr, "addr", ":3001", "address to listen on")
}

func (c *serverCommand) Execute(ctx context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
	db := openDB()
	defer db.Close()

	storage := liber.NewRWFileStorage(util.ExpandTilde(*bookDir), 2)
	cache := liber.NewRWFileStorage(filepath.Join(util.ExpandTilde(*databaseDir), "cache"), 2)
	server := liber.NewHttpServer(db, storage, cache, c.addr)
	if err := server.ListenAndServe(); err != nil {
		log.Printf("error: %v", err)
		return subcommands.ExitFailure
	}

	return subcommands.ExitSuccess
}