package main
import (
"encoding/json"
"html/template"
"log"
"net/http"
"os"
"strings"
"meutel.net/meutel/go-examples/photoblog/admin"
"meutel.net/meutel/go-examples/photoblog/photo"
"github.com/gorilla/sessions"
)
type PhotoBlogConfig struct {
SessionSecret string `json:"session-secret"`
PasswordSecret string `json:"password-secret"`
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() {
// load config
confPath := "photoblog.json"
if len(os.Args) > 1 {
confPath = os.Args[1]
}
confFile, err := os.Open(confPath)
if err != nil {
log.Fatalln("Invalid conf file", err)
}
defer confFile.Close()
conf, err := ReadConfig(confFile)
if err != nil {
log.Fatalln("Configuration error", err)
}
dataInfo, err := os.Stat(conf.DataDir)
if !dataInfo.IsDir() {
log.Fatalln("Invalid data directory")
}
data, err := os.Open(conf.DataDir)
if err != nil {
log.Fatalln("cannot open data directory", err)
}
defer data.Close()
// load templates
tpl, err := template.ParseGlob("templates/*.html")
if err != nil {
log.Fatalln(err)
}
app := photo.PhotoBlog{
admin.AuthCookie{
Templates: tpl,
Store: sessions.NewCookieStore([]byte(conf.SessionSecret)),
DataDir: data,
PasswordSecret: conf.PasswordSecret,
},
}
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.RequestURI, photo.DATA) {
http.StripPrefix(photo.DATA, http.FileServer(http.Dir(data.Name()))).ServeHTTP(res, req)
} else {
app.HomePage(res, req)
}
})
http.HandleFunc("/upload", app.UploadPage)
http.HandleFunc("/login", app.LoginPage)
http.HandleFunc("/logout", app.LogoutPage)
http.ListenAndServeTLS(":9443", "../cert.pem", "../key.pem", nil)
}