76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
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/context"
|
|
)
|
|
|
|
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.NewAuthCookie(tpl, conf.SessionSecret, conf.PasswordSecret, data),
|
|
}
|
|
|
|
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", context.ClearHandler(http.DefaultServeMux))
|
|
}
|