use pkger for embedding static contents

Co-authored-by: Vikram Yadav <vyadav@pivotal.io>
Signed-off-by: Rui Yang <ruiya@vmware.com>
This commit is contained in:
Rui Yang
2020-10-14 21:19:23 -04:00
committed by CI Bot
parent 1eab25f89f
commit 7b50cbf0ac
11 changed files with 39 additions and 144 deletions

View File

@@ -135,7 +135,7 @@ func TestHandleInvalidSAMLCallbacks(t *testing.T) {
func TestConnectorLoginDoesNotAllowToChangeConnectorForAuthRequest(t *testing.T) {
memStorage := memory.New(logger)
templates, err := loadTemplates(WebConfig{Dir: http.Dir("../web")}, "../web/templates")
templates, err := loadTemplates(WebConfig{Dir: "/web"}, "/web/templates")
if err != nil {
t.Fatal("failed to load templates")
}

View File

@@ -19,6 +19,7 @@ import (
"github.com/felixge/httpsnoop"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/markbates/pkger"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/bcrypt"
@@ -108,7 +109,7 @@ type WebConfig struct {
// * templates - HTML templates controlled by dex.
// * themes/(theme) - Static static served at "( issuer URL )/theme".
//
Dir http.FileSystem
Dir string
// Defaults to "( issuer URL )/theme/logo.png"
LogoURL string
@@ -206,6 +207,10 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy)
supported[respType] = true
}
if c.Web.Dir == "" {
c.Web.Dir = pkger.Include("/web")
}
tmpls, err := loadTemplates(c.Web, issuerURL.Path)
if err != nil {
return nil, fmt.Errorf("server: failed to load templates: %v", err)
@@ -337,7 +342,11 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy)
}
fmt.Fprintf(w, "Health check passed")
}))
handlePrefix("/", http.FileServer(c.Web.Dir))
staticDir := path.Join(c.Web.Dir, "static")
themeDir := path.Join(c.Web.Dir, "themes", c.Web.Theme)
handlePrefix("/static", http.FileServer(pkger.Dir(staticDir)))
handlePrefix(path.Join("/themes", c.Web.Theme), http.FileServer(pkger.Dir(themeDir)))
s.mux = r

View File

@@ -93,7 +93,7 @@ func newTestServer(ctx context.Context, t *testing.T, updateConfig func(c *Confi
Issuer: s.URL,
Storage: memory.New(logger),
Web: WebConfig{
Dir: http.Dir("../web"),
Dir: "/web",
},
Logger: logger,
PrometheusRegistry: prometheus.NewRegistry(),
@@ -132,7 +132,7 @@ func newTestServerMultipleConnectors(ctx context.Context, t *testing.T, updateCo
Issuer: s.URL,
Storage: memory.New(logger),
Web: WebConfig{
Dir: http.Dir("../web"),
Dir: "/web",
},
Logger: logger,
PrometheusRegistry: prometheus.NewRegistry(),

View File

@@ -6,11 +6,12 @@ import (
"html/template"
"io"
"net/http"
"net/url"
"path"
"path/filepath"
"sort"
"strings"
"github.com/markbates/pkger"
)
const (
@@ -61,9 +62,11 @@ func loadTemplates(c WebConfig, issuerPath string) (*templates, error) {
funcs := template.FuncMap{
"issuer": func() string { return c.Issuer },
"logo": func() string { return c.LogoURL },
"url": func(reqPath, assetPath string) string { return relativeURL(hostURL, reqPath, assetPath) },
"theme": func(reqPath, assetPath string) string {
return relativeURL(hostURL, reqPath, path.Join("themes", c.Theme, assetPath))
"static": func(assetPath string) string {
return path.Join(hostURL, "static", assetPath)
},
"theme": func(assetPath string) string {
return path.Join(hostURL, "themes", c.Theme, assetPath)
},
"lower": strings.ToLower,
"extra": func(k string) string { return c.Extra[k] },
@@ -130,76 +133,9 @@ func loadTemplates(c WebConfig, issuerPath string) (*templates, error) {
}, nil
}
// relativeURL returns the URL of the asset relative to the URL of the request path.
// The serverPath is consulted to trim any prefix due in case it is not listening
// to the root path.
//
// Algorithm:
// 1. Remove common prefix of serverPath and reqPath
// 2. Remove common prefix of assetPath and reqPath
// 3. For each part of reqPath remaining(minus one), go up one level (..)
// 4. For each part of assetPath remaining, append it to result
//
// eg
// server listens at localhost/dex so serverPath is dex
// reqPath is /dex/auth
// assetPath is static/main.css
// relativeURL("/dex", "/dex/auth", "static/main.css") = "../static/main.css"
func relativeURL(serverPath, reqPath, assetPath string) string {
if u, err := url.ParseRequestURI(assetPath); err == nil && u.Scheme != "" {
// assetPath points to the external URL, no changes needed
return assetPath
}
splitPath := func(p string) []string {
res := []string{}
parts := strings.Split(path.Clean(p), "/")
for _, part := range parts {
if part != "" {
res = append(res, part)
}
}
return res
}
stripCommonParts := func(s1, s2 []string) ([]string, []string) {
min := len(s1)
if len(s2) < min {
min = len(s2)
}
splitIndex := min
for i := 0; i < min; i++ {
if s1[i] != s2[i] {
splitIndex = i
break
}
}
return s1[splitIndex:], s2[splitIndex:]
}
server, req, asset := splitPath(serverPath), splitPath(reqPath), splitPath(assetPath)
// Remove common prefix of request path with server path
_, req = stripCommonParts(server, req)
// Remove common prefix of request path with asset path
asset, req = stripCommonParts(asset, req)
// For each part of the request remaining (minus one) -> go up one level (..)
// For each part of the asset remaining -> append it
var relativeURL string
for i := 0; i < len(req)-1; i++ {
relativeURL = path.Join("..", relativeURL)
}
relativeURL = path.Join(relativeURL, path.Join(asset...))
return relativeURL
}
// load a template by name from the templates dir
func loadTemplate(dir http.FileSystem, name string, funcs template.FuncMap, group *template.Template) (*template.Template, error) {
file, err := dir.Open(filepath.Join("templates", name))
func loadTemplate(dir string, name string, funcs template.FuncMap, group *template.Template) (*template.Template, error) {
file, err := pkger.Open(filepath.Join(dir, "templates", name))
if err != nil {
return nil, err
}

View File

@@ -1,51 +0,0 @@
package server
import "testing"
func TestRelativeURL(t *testing.T) {
tests := []struct {
name string
serverPath string
reqPath string
assetPath string
expected string
}{
{
name: "server-root-req-one-level-asset-two-level",
serverPath: "/",
reqPath: "/auth",
assetPath: "/theme/main.css",
expected: "theme/main.css",
},
{
name: "server-one-level-req-one-level-asset-two-level",
serverPath: "/dex",
reqPath: "/dex/auth",
assetPath: "/theme/main.css",
expected: "theme/main.css",
},
{
name: "server-root-req-two-level-asset-three-level",
serverPath: "/dex",
reqPath: "/dex/auth/connector",
assetPath: "assets/css/main.css",
expected: "../assets/css/main.css",
},
{
name: "external-url",
serverPath: "/dex",
reqPath: "/dex/auth/connector",
assetPath: "https://kubernetes.io/images/favicon.png",
expected: "https://kubernetes.io/images/favicon.png",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
actual := relativeURL(test.serverPath, test.reqPath, test.assetPath)
if actual != test.expected {
t.Fatalf("Got '%s'. Expected '%s'", actual, test.expected)
}
})
}
}