Browse Source

locate asset files more robustly so you aren't required to be in a certain directory to run the client program

Alan Shreve 12 years ago
parent
commit
3ba6ada7c8
1 changed files with 45 additions and 8 deletions
  1. 45 8
      src/ngrok/client/views/web/static/debug.go

+ 45 - 8
src/ngrok/client/views/web/static/debug.go

@@ -4,19 +4,56 @@ package static
 
 import (
 	"io/ioutil"
+	"os"
+	"path"
 )
 
-func ReadFileOrPanic(path string) []byte {
-	bytes, err := ioutil.ReadFile(path)
+var assetDir string
+
+func init() {
+	// find the directory with the assets. 
+	// this doesn't work if you:
+	// 1. move the binary
+	// 2. put ngrok in your PATH
+	// but you shouldn't be doing either of these things while developng anyways
+	var binPath string
+	execPath := os.Args[0]
+	if path.IsAbs(execPath) {
+		binPath = execPath
+	} else {
+		wd, err := os.Getwd()
+		if err != nil {
+			panic(err)
+		}
+		binPath = path.Join(wd, execPath)
+	}
+	assetDir = path.Join(path.Dir(path.Dir(binPath)), "assets")
+
+	// call all the functions on startup to make sure the files exist
+	fns := []func() []byte{
+		BodyHtml,
+		PageHtml,
+		HighlightJs,
+		HighlightCss,
+		BootstrapCss,
+		JqueryJs,
+	}
+	for _, f := range fns {
+		f()
+	}
+}
+
+func ReadFileOrPanic(p string) []byte {
+	bytes, err := ioutil.ReadFile(path.Join(assetDir, p))
 	if err != nil {
 		panic(err)
 	}
 	return bytes
 }
 
-func BodyHtml() []byte     { return ReadFileOrPanic("assets/body.html") }
-func PageHtml() []byte     { return ReadFileOrPanic("assets/page.html") }
-func HighlightJs() []byte  { return ReadFileOrPanic("assets/highlight.min.js") }
-func HighlightCss() []byte { return ReadFileOrPanic("assets/highlight.min.css") }
-func BootstrapCss() []byte { return ReadFileOrPanic("assets/bootstrap.min.css") }
-func JqueryJs() []byte     { return ReadFileOrPanic("assets/jquery-1.9.1.min.js") }
+func BodyHtml() []byte     { return ReadFileOrPanic("body.html") }
+func PageHtml() []byte     { return ReadFileOrPanic("page.html") }
+func HighlightJs() []byte  { return ReadFileOrPanic("highlight.min.js") }
+func HighlightCss() []byte { return ReadFileOrPanic("highlight.min.css") }
+func BootstrapCss() []byte { return ReadFileOrPanic("bootstrap.min.css") }
+func JqueryJs() []byte     { return ReadFileOrPanic("jquery-1.9.1.min.js") }