grim/hgkeeper

Serve all static files from /static and handle it from go instead of passing it to python. Fixes HGKEEPER-7
//go:generate esc -o files.go -pkg hgweb -include files\/.+ -prefix files/ .
package hgweb
import (
"io/ioutil"
"net/http"
"net/http/cgi"
"os"
"path/filepath"
"text/template"
log "github.com/sirupsen/logrus"
"bitbucket.org/rw_grim/hgkeeper/access"
"bitbucket.org/rw_grim/hgkeeper/hg"
)
type Server struct {
listenAddr string
server *http.Server
configPath string
cgiPath string
cacheSize int
}
func NewServer(listenAddr string, cacheSize int) (*Server, error) {
return &Server{
listenAddr: listenAddr,
cacheSize: cacheSize,
server: &http.Server{
Addr: listenAddr,
},
}, nil
}
func (s *Server) createConfig() error {
configPath, err := ioutil.TempFile("", "hgkeeper-hgweb-*.config")
if err != nil {
return err
}
defer configPath.Close()
t := template.Must(template.New("hgweb-config").Parse(FSMustString(false, "/hgweb.config")))
data := map[string]string{
"HGWEB_ACCESS_CONFIG": access.HgwebConfigPath(),
"SITE_HGRC": filepath.Join(access.AdminRepoPath(), "site.hgrc"),
}
if err := t.Execute(configPath, data); err != nil {
return err
}
s.configPath = configPath.Name()
return nil
}
func (s *Server) createCGI() error {
cgiPath, err := ioutil.TempFile("", "hgkeeper-hgweb-*.cgi")
if err != nil {
return err
}
defer cgiPath.Close()
// make the cgi file executable
if err := cgiPath.Chmod(0755); err != nil {
return err
}
// create a template based for the cgi file
t := template.Must(template.New("cgi").Parse(FSMustString(false, "/hgweb.cgi")))
// create our data
data := map[string]string{
"HGWEB_CONFIG": s.configPath,
}
if err := t.Execute(cgiPath, data); err != nil {
return err
}
s.cgiPath = cgiPath.Name()
return nil
}
func (s *Server) Listen() error {
if err := s.createConfig(); err != nil {
return err
}
if err := s.createCGI(); err != nil {
return err
}
cache, err := newCache(s.cacheSize)
if err != nil {
return err
}
templatesDir, err := hg.TemplatesDir()
if err != nil {
return err
}
staticPath := filepath.Join(templatesDir, "static")
log.Infof("serving static files from %s", staticPath)
fileServer := http.FileServer(http.Dir(staticPath))
mux := http.NewServeMux()
mux.Handle("/static/", http.StripPrefix("/static", fileServer))
mux.Handle("/", &cgi.Handler{Path: s.cgiPath})
s.server.Handler = Logger(cache.middleware(mux))
log.Infof("http listening on %s", s.listenAddr)
return s.server.ListenAndServe()
}
func (s *Server) Close() {
if err := os.Remove(s.cgiPath); err != nil {
log.Warnf("failed to remove temporary cgi file %q: %v", s.cgiPath, err)
}
if err := s.server.Close(); err != nil {
log.Warnf("failed to shutdown http server: %v", err)
}
}