2016-02-11 12:03:03 -08:00
|
|
|
/*
|
|
|
|
command ysvd implements the
|
|
|
|
|
|
|
|
The "ysv" in ysvd stands for You're so Vain, the song by Carly Simon.
|
|
|
|
*/
|
2016-02-07 23:54:55 -08:00
|
|
|
package main
|
|
|
|
|
2016-02-08 00:15:22 -08:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
|
2016-02-11 11:57:16 -08:00
|
|
|
"mcquay.me/vain"
|
2016-02-08 00:15:22 -08:00
|
|
|
|
|
|
|
"github.com/kelseyhightower/envconfig"
|
|
|
|
)
|
|
|
|
|
|
|
|
const usage = `ysvd
|
|
|
|
|
|
|
|
environment vars:
|
|
|
|
|
|
|
|
YSV_PORT: tcp listen port
|
2016-02-13 01:18:06 -08:00
|
|
|
YSV_HOST: hostname to use
|
2016-02-14 22:19:41 -08:00
|
|
|
YSV_DB: path to json database
|
2016-02-08 00:15:22 -08:00
|
|
|
`
|
|
|
|
|
|
|
|
type config struct {
|
|
|
|
Port int
|
2016-02-13 01:18:06 -08:00
|
|
|
Host string
|
2016-02-14 22:19:41 -08:00
|
|
|
DB string
|
2016-02-08 00:15:22 -08:00
|
|
|
}
|
|
|
|
|
2016-02-07 23:54:55 -08:00
|
|
|
func main() {
|
2016-02-08 00:15:22 -08:00
|
|
|
c := &config{
|
|
|
|
Port: 4040,
|
|
|
|
}
|
|
|
|
if err := envconfig.Process("ysv", c); err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "problem processing environment: %v", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
if len(os.Args) > 1 {
|
|
|
|
switch os.Args[1] {
|
|
|
|
case "env", "e", "help", "h":
|
2016-02-14 22:19:41 -08:00
|
|
|
fmt.Printf("%s\n", usage)
|
|
|
|
os.Exit(0)
|
2016-02-08 00:15:22 -08:00
|
|
|
}
|
|
|
|
}
|
2016-02-14 22:19:41 -08:00
|
|
|
if c.Host == "" {
|
|
|
|
log.Printf("must set YSV_HOST; please run $(ysvd env) for more information")
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
if c.DB == "" {
|
|
|
|
log.Printf("warning: in-memory db mode; if you do not want this set YSV_DB")
|
|
|
|
}
|
2016-02-08 00:15:22 -08:00
|
|
|
hostname := "localhost"
|
|
|
|
if hn, err := os.Hostname(); err != nil {
|
|
|
|
log.Printf("problem getting hostname:", err)
|
|
|
|
} else {
|
|
|
|
hostname = hn
|
|
|
|
}
|
|
|
|
log.Printf("serving at: http://%s:%d/", hostname, c.Port)
|
|
|
|
sm := http.NewServeMux()
|
2016-02-14 22:19:41 -08:00
|
|
|
ms := vain.NewMemStore(c.DB)
|
|
|
|
if err := ms.Load(); err != nil {
|
|
|
|
log.Printf("unable to load db: %v", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2016-02-13 01:18:06 -08:00
|
|
|
vain.NewServer(sm, ms, c.Host)
|
2016-02-08 00:15:22 -08:00
|
|
|
addr := fmt.Sprintf(":%d", c.Port)
|
|
|
|
if err := http.ListenAndServe(addr, sm); err != nil {
|
|
|
|
log.Printf("problem with http server: %v", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2016-02-07 23:54:55 -08:00
|
|
|
}
|