agent: Simplify serving of ui files

This commit is contained in:
Armon Dadgar 2014-04-24 12:10:23 -06:00 committed by Jack Pearkes
parent 0449428e20
commit ba69350cef
2 changed files with 2 additions and 51 deletions

View File

@ -102,7 +102,7 @@ func (s *HTTPServer) registerHandlers(enableDebug bool) {
// Enable the UI + special endpoints
if s.uiDir != "" {
s.mux.HandleFunc("/ui/", s.UiIndex)
s.mux.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(http.Dir(s.uiDir))))
}
}

View File

@ -1,52 +1,3 @@
package agent
import (
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
// UiIndex serves files in the /ui/ prefix from a preconfigured directory
func (s *HTTPServer) UiIndex(resp http.ResponseWriter, req *http.Request) {
// Invoke the handler
start := time.Now()
defer func() {
s.logger.Printf("[DEBUG] http: Request %v (%v)", req.URL, time.Now().Sub(start))
}()
// Determine the file path
file := strings.TrimPrefix(req.URL.Path, "/ui/")
if file == "" {
file = "index.html"
}
// Reject if it is relative
if strings.Contains(file, "..") {
s.logger.Printf("[WARN] http: Invalid file %s", file)
resp.WriteHeader(404)
return
}
path := filepath.Join(s.uiDir, file)
// Attempt to open
fh, err := os.Open(path)
if err != nil {
s.logger.Printf("[WARN] http: Failed to serve file %s: %v", path, err)
resp.WriteHeader(404)
return
}
defer fh.Close()
// Get the file info
info, err := fh.Stat()
if err != nil {
s.logger.Printf("[WARN] http: Failed to stat file %s: %v", path, err)
resp.WriteHeader(404)
return
}
// Serve the file
http.ServeContent(resp, req, path, info.ModTime(), fh)
}
import ()