ProfouzorsLinx/server.go

92 lines
2.1 KiB
Go
Raw Normal View History

2015-09-24 07:44:49 +02:00
package main
import (
"flag"
2015-09-28 04:17:12 +02:00
"fmt"
2015-09-24 07:44:49 +02:00
"log"
"net"
"net/http"
2015-09-26 04:03:14 +02:00
"os"
2015-09-28 04:17:12 +02:00
"regexp"
2015-09-24 07:44:49 +02:00
"github.com/flosch/pongo2"
2015-09-24 07:44:49 +02:00
"github.com/zenazn/goji"
"github.com/zenazn/goji/web/middleware"
2015-09-24 07:44:49 +02:00
)
var Config struct {
bind string
filesDir string
2015-09-28 04:17:12 +02:00
metaDir string
noLogs bool
2015-09-24 07:44:49 +02:00
siteName string
siteURL string
2015-09-24 07:44:49 +02:00
}
func main() {
flag.StringVar(&Config.bind, "b", "127.0.0.1:8080",
"host to bind to (default: 127.0.0.1:8080)")
flag.StringVar(&Config.filesDir, "filespath", "files/",
2015-09-28 04:17:12 +02:00
"path to files directory")
flag.StringVar(&Config.metaDir, "metapath", "meta/",
"path to metadata directory")
flag.BoolVar(&Config.noLogs, "nologs", false,
"remove stdout output for each request")
flag.StringVar(&Config.siteName, "sitename", "linx",
2015-09-24 07:44:49 +02:00
"name of the site")
flag.StringVar(&Config.siteURL, "siteurl", "http://"+Config.bind+"/",
2015-09-28 05:07:15 +02:00
"site base url (including trailing slash)")
2015-09-24 07:44:49 +02:00
flag.Parse()
if Config.noLogs {
goji.Abandon(middleware.Logger)
}
2015-09-28 04:17:12 +02:00
// make directories if needed
var err error
err = os.MkdirAll(Config.filesDir, 0755)
2015-09-26 04:03:14 +02:00
if err != nil {
fmt.Println("Error: could not create files directory")
2015-09-26 13:50:33 +02:00
os.Exit(1)
2015-09-26 04:03:14 +02:00
}
2015-09-28 04:17:12 +02:00
err = os.MkdirAll(Config.metaDir, 0700)
if err != nil {
fmt.Println("Error: could not create metadata directory")
2015-09-28 04:17:12 +02:00
os.Exit(1)
}
// ensure siteURL ends wth '/'
if lastChar := Config.siteURL[len(Config.siteURL)-1:]; lastChar != "/" {
Config.siteURL = Config.siteURL + "/"
}
// Template Globals
pongo2.DefaultSet.Globals["sitename"] = Config.siteName
// Routing setup
2015-09-24 07:44:49 +02:00
nameRe := regexp.MustCompile(`^/(?P<name>[a-z0-9-\.]+)$`)
selifRe := regexp.MustCompile(`^/selif/(?P<name>[a-z0-9-\.]+)$`)
goji.Get("/", indexHandler)
2015-09-24 07:44:49 +02:00
goji.Post("/upload", uploadPostHandler)
goji.Post("/upload/", http.RedirectHandler("/upload", 301))
2015-09-24 07:44:49 +02:00
goji.Put("/upload", uploadPutHandler)
goji.Put("/upload/:name", uploadPutHandler)
goji.Get("/static/*", http.StripPrefix("/static/",
http.FileServer(http.Dir("static/"))))
2015-09-24 07:44:49 +02:00
goji.Get(nameRe, fileDisplayHandler)
goji.Get(selifRe, fileServeHandler)
goji.NotFound(notFoundHandler)
2015-09-24 07:44:49 +02:00
listener, err := net.Listen("tcp", Config.bind)
if err != nil {
log.Fatal("Could not bind: ", err)
}
goji.ServeListener(listener)
}