go-examples/photoblog/main.go

78 lines
1.9 KiB
Go
Raw Normal View History

package main
import (
2017-07-29 18:21:27 +00:00
"encoding/json"
"html/template"
"log"
"net/http"
2017-07-29 11:54:23 +00:00
"os"
"strings"
"meutel.net/meutel/go-examples/photoblog/admin"
2017-07-29 11:54:23 +00:00
"meutel.net/meutel/go-examples/photoblog/photo"
2017-07-30 08:01:23 +00:00
"github.com/gorilla/context"
)
2017-07-29 18:21:27 +00:00
type PhotoBlogConfig struct {
SessionSecret string `json:"session-secret"`
PasswordSecret string `json:"password-secret"`
2017-07-30 09:05:20 +00:00
CsrfSecret string `json:"csrf-secret"`
2017-07-29 18:21:27 +00:00
DataDir string `json:"data-dir"`
}
func ReadConfig(file *os.File) (*PhotoBlogConfig, error) {
conf := new(PhotoBlogConfig)
err := json.NewDecoder(file).Decode(conf)
return conf, err
}
func main() {
2017-07-29 18:21:27 +00:00
// load config
confPath := "photoblog.json"
if len(os.Args) > 1 {
confPath = os.Args[1]
}
confFile, err := os.Open(confPath)
if err != nil {
2017-07-29 18:21:27 +00:00
log.Fatalln("Invalid conf file", err)
}
2017-07-29 18:21:27 +00:00
defer confFile.Close()
conf, err := ReadConfig(confFile)
if err != nil {
log.Fatalln("Configuration error", err)
}
dataInfo, err := os.Stat(conf.DataDir)
2017-07-29 11:54:23 +00:00
if !dataInfo.IsDir() {
2017-07-29 18:21:27 +00:00
log.Fatalln("Invalid data directory")
2017-07-29 11:54:23 +00:00
}
2017-07-29 18:21:27 +00:00
data, err := os.Open(conf.DataDir)
2017-07-29 11:54:23 +00:00
if err != nil {
2017-07-29 18:21:27 +00:00
log.Fatalln("cannot open data directory", err)
2017-07-29 11:54:23 +00:00
}
defer data.Close()
2017-07-29 18:21:27 +00:00
// load templates
tpl, err := template.ParseGlob("templates/*.html")
if err != nil {
log.Fatalln(err)
}
2017-07-29 11:54:23 +00:00
app := photo.PhotoBlog{
2017-07-30 09:05:20 +00:00
*admin.NewAuthCookie(tpl, conf.SessionSecret, conf.PasswordSecret, conf.CsrfSecret, data),
}
2017-07-29 11:54:23 +00:00
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
2017-07-29 18:21:27 +00:00
if strings.HasPrefix(req.RequestURI, photo.DATA) {
http.StripPrefix(photo.DATA, http.FileServer(http.Dir(data.Name()))).ServeHTTP(res, req)
2017-07-29 11:54:23 +00:00
} else {
app.HomePage(res, req)
}
})
2017-07-30 09:05:20 +00:00
CSRF := app.Protect()
2017-07-29 11:54:23 +00:00
http.HandleFunc("/upload", app.UploadPage)
http.HandleFunc("/login", app.LoginPage)
http.HandleFunc("/logout", app.LogoutPage)
2017-07-30 09:05:20 +00:00
http.ListenAndServeTLS(":9443", "../cert.pem", "../key.pem", CSRF(context.ClearHandler(http.DefaultServeMux)))
}