snap/server.go

119 lines
2.5 KiB
Go

package snap
import (
"github.com/gorilla/mux"
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"fmt"
"git.thirdmartini.com/pub/fancylog"
"git.thirdmartini.com/pub/snap-serve/auth"
"path"
)
type Server interface {
Serve() error
ServeTLS(keyPath string, certPath string) error
HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) error
HandleFuncAuthenticated(path string, f func(http.ResponseWriter, *http.Request)) error
}
type server struct {
address string
path string
debug bool
auth auth.AuthManager
router *mux.Router
cachedTmpl *template.Template
}
type ApplicationContext struct {
Username string
}
func (s *server) loadTemplates() *template.Template {
tmpl := template.New("")
err := filepath.Walk(path.Join(s.path, "templates"), func(path string, info os.FileInfo, err error) error {
if strings.Contains(path, ".html") {
_, err = tmpl.ParseFiles(path)
if err != nil {
log.Println(err)
}
}
return err
})
if err != nil {
log.Fatal(err)
}
return tmpl
}
func (s *server) getTemplates() *template.Template {
if s.debug {
return s.loadTemplates()
}
if s.cachedTmpl == nil {
s.cachedTmpl = s.loadTemplates()
}
return s.cachedTmpl
}
func (s *server) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) error {
s.router.HandleFunc(path, f)
return nil
}
func (s *server) HandleFuncAuthenticated(path string, f func(http.ResponseWriter, *http.Request)) error {
if s.auth == nil {
return fmt.Errorf("no auth manager provided")
}
s.router.HandleFunc(path, s.auth.DoAuth(f))
return nil
}
func (s *server) ServeTLS(keyPath string, certPath string) error {
srv := &http.Server{
Handler: s.router,
Addr: s.address,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
return srv.ListenAndServeTLS(keyPath, certPath)
}
// Serve serve content forever
func (s *server) Serve() error {
srv := &http.Server{
Handler: s.router,
Addr: s.address,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
return srv.ListenAndServe()
}
func New(address string, path string, auth auth.AuthManager) Server {
s := server{
router: mux.NewRouter(),
auth: auth,
address: address,
path: path,
}
s.router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(s.ServerPath+"static/"))))
return &s
}