agent: Adding endpoint to serve the UI

This commit is contained in:
Armon Dadgar 2014-04-23 12:57:06 -07:00 committed by Jack Pearkes
parent 2739abab7b
commit e20b70b9f6
4 changed files with 78 additions and 1 deletions

View File

@ -98,6 +98,11 @@ func (s *HTTPServer) registerHandlers(enableDebug bool) {
s.mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
s.mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
}
// Enable the UI + special endpoints
if s.uiDir != "" {
s.mux.HandleFunc("/ui/", s.UiIndex)
}
}
// wrap is used to wrap functions to make them more convenient

View File

@ -9,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"testing"
"time"
@ -17,8 +18,10 @@ import (
func makeHTTPServer(t *testing.T) (string, *HTTPServer) {
conf := nextConfig()
dir, agent := makeAgent(t, conf)
uiDir := filepath.Join(dir, "ui")
println(uiDir)
addr, _ := agent.config.ClientListener(agent.config.Ports.HTTP)
server, err := NewHTTPServer(agent, "", true, agent.logOutput, addr.String())
server, err := NewHTTPServer(agent, uiDir, true, agent.logOutput, addr.String())
if err != nil {
t.Fatalf("err: %v", err)
}

View File

@ -0,0 +1,24 @@
package agent
import (
"net/http"
"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))
}()
file := strings.TrimPrefix(req.URL.Path, "/ui/")
if file == "" {
file = "index.html"
}
path := filepath.Join(s.uiDir, file)
http.ServeFile(resp, req, path)
}

View File

@ -0,0 +1,45 @@
package agent
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestUiIndex(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.Shutdown()
defer srv.agent.Shutdown()
// Create file
path := filepath.Join(srv.uiDir, "my-file")
ioutil.WriteFile(path, []byte("test"), 777)
// Register node
req, err := http.NewRequest("GET", "/ui/my-file", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
// Make the request
resp := httptest.NewRecorder()
srv.UiIndex(resp, req)
// Verify teh response
if resp.Code != 200 {
t.Fatalf("bad: %v", resp)
}
// Verify the body
out := bytes.NewBuffer(nil)
io.Copy(out, resp.Body)
if string(out.Bytes()) != "test" {
t.Fatalf("bad: %s", out.Bytes())
}
}