rest-server/server.go

71 lines
1.7 KiB
Go
Raw Normal View History

2015-08-11 14:14:07 +02:00
package main
2015-08-15 10:06:10 +02:00
import (
2015-09-07 15:29:24 +02:00
"flag"
2015-08-15 10:06:10 +02:00
"log"
"net/http"
2015-09-16 23:34:11 +02:00
"os"
2015-09-07 15:29:24 +02:00
"path/filepath"
2015-08-15 10:06:10 +02:00
)
2015-08-11 14:14:07 +02:00
2015-09-07 15:29:24 +02:00
const (
HTTP = ":8000"
HTTPS = ":8443"
)
2015-08-15 10:06:10 +02:00
2015-09-07 15:29:24 +02:00
func main() {
2015-09-16 23:34:11 +02:00
// Parse command-line args
2015-09-07 15:29:24 +02:00
var path = flag.String("path", "/tmp/restic", "specifies the path of the data directory")
var tls = flag.Bool("tls", false, "turns on tls support")
flag.Parse()
2015-08-15 10:06:10 +02:00
2015-09-19 14:52:50 +02:00
// Create the missing directories
2015-09-16 23:34:11 +02:00
dirs := []string{
2015-09-19 14:28:26 +02:00
"data",
"snapshots",
"index",
"locks",
"keys",
2015-09-16 23:34:11 +02:00
}
for _, d := range dirs {
2015-09-19 14:52:50 +02:00
os.MkdirAll(filepath.Join(*path, d), 0600)
2015-09-16 23:34:11 +02:00
}
2015-09-19 14:52:50 +02:00
// Define the routes
2015-09-18 17:13:38 +02:00
context := &Context{*path}
router := NewRouter()
router.HeadFunc("/config", CheckConfig(context))
router.GetFunc("/config", GetConfig(context))
router.PostFunc("/config", SaveConfig(context))
router.GetFunc("/:dir/", ListBlobs(context))
router.HeadFunc("/:dir/:name", CheckBlob(context))
router.GetFunc("/:type/:name", GetBlob(context))
router.PostFunc("/:type/:name", SaveBlob(context))
router.DeleteFunc("/:type/:name", DeleteBlob(context))
2015-09-16 23:34:11 +02:00
2015-09-19 14:52:50 +02:00
// Check for a password file
var handler http.Handler
htpasswdFile, err := NewHtpasswdFromFile(filepath.Join(*path, ".htpasswd"))
if err != nil {
log.Println("Authentication disabled")
handler = router
} else {
log.Println("Authentication enabled")
handler = AuthHandler(htpasswdFile, router)
}
2015-09-16 23:34:11 +02:00
// start the server
2015-09-07 15:29:24 +02:00
if !*tls {
2015-09-19 14:52:50 +02:00
log.Printf("start server on port %s\n", HTTP)
http.ListenAndServe(HTTP, handler)
2015-09-07 15:29:24 +02:00
} else {
privateKey := filepath.Join(*path, "private_key")
publicKey := filepath.Join(*path, "public_key")
2015-09-19 14:52:50 +02:00
log.Println("TLS enabled")
2015-09-07 16:17:24 +02:00
log.Printf("private key: %s", privateKey)
log.Printf("public key: %s", publicKey)
2015-09-19 14:52:50 +02:00
log.Printf("start server on port %s\n", HTTPS)
http.ListenAndServeTLS(HTTPS, publicKey, privateKey, handler)
2015-09-07 15:29:24 +02:00
}
2015-08-11 14:14:07 +02:00
}