github.com/sym3tri/etcd@v0.2.1-0.20140422215517-a563d82f95d6/mod/dashboard/dashboard.go (about)

     1  package dashboard
     2  
     3  import (
     4  	"bytes"
     5  	"net/http"
     6  	"os"
     7  	"path"
     8  	"time"
     9  
    10  	"github.com/coreos/etcd/log"
    11  	"github.com/coreos/etcd/mod/dashboard/resources"
    12  )
    13  
    14  func memoryFileServer(w http.ResponseWriter, req *http.Request) {
    15  	log.Debugf("[recv] %s %s [%s]", req.Method, req.URL.Path, req.RemoteAddr)
    16  	upath := req.URL.Path
    17  
    18  	b, err := resources.Asset(req.URL.Path)
    19  
    20  	if err != nil {
    21  		http.Error(w, upath+": File not found", http.StatusNotFound)
    22  		return
    23  	}
    24  
    25  	http.ServeContent(w, req, upath, time.Time{}, bytes.NewReader(b))
    26  	return
    27  }
    28  
    29  func getDashDir() string {
    30  	return os.Getenv("ETCD_DASHBOARD_DIR")
    31  }
    32  
    33  // DashboardHttpHandler either uses the compiled in virtual filesystem for the
    34  // dashboard assets or if ETCD_DASHBOARD_DIR is set uses that as the source of
    35  // assets.
    36  func HttpHandler() (handler http.Handler) {
    37  	handler = http.HandlerFunc(memoryFileServer)
    38  
    39  	// Serve the dashboard from a filesystem if the magic env variable is enabled
    40  	dashDir := getDashDir()
    41  	if len(dashDir) != 0 {
    42  		log.Debugf("Using dashboard directory %s", dashDir)
    43  		handler = http.FileServer(http.Dir(dashDir))
    44  	}
    45  
    46  	return handler
    47  }
    48  
    49  // Always returns the index.html page.
    50  func IndexPage(w http.ResponseWriter, req *http.Request) {
    51  	dashDir := getDashDir()
    52  	if len(dashDir) != 0 {
    53  		// Serve the index page from disk if the env variable is set.
    54  		http.ServeFile(w, req, path.Join(dashDir, "index.html"))
    55  	} else {
    56  		// Otherwise serve it from the compiled resources.
    57  		b, _ := resources.Asset("index.html")
    58  		http.ServeContent(w, req, "index.html", time.Time{}, bytes.NewReader(b))
    59  	}
    60  	return
    61  }