Skip to content

Commit

Permalink
add index handler if no package is sered at /
Browse files Browse the repository at this point in the history
  • Loading branch information
rakyll committed Aug 3, 2017
1 parent e749108 commit d76d64b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
44 changes: 39 additions & 5 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,22 +85,22 @@ func newHandler(config []byte) (*handler, error) {
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
current := r.URL.Path
pc, _ := h.paths.find(current)
if pc == nil && current == "/" {
h.serveIndex(w, r)
return
}
if pc == nil {
http.NotFound(w, r)
return
}

host := h.host
if host == "" {
host = defaultHost(r)
}
if err := vanityTmpl.Execute(w, struct {
Import string
Repo string
Display string
VCS string
}{
Import: host + pc.path,
Import: h.Host(r) + pc.path,
Repo: pc.repo,
Display: pc.display,
VCS: pc.vcs,
Expand All @@ -109,6 +109,40 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}

func (h *handler) serveIndex(w http.ResponseWriter, r *http.Request) {
host := h.Host(r)
handlers := make([]string, len(h.paths))
for i, h := range h.paths {
handlers[i] = host + h.path
}
if err := indexTmpl.Execute(w, struct {
Host string
Handlers []string
}{
Host: host,
Handlers: handlers,
}); err != nil {
http.Error(w, "cannot render the page", http.StatusInternalServerError)
}
}

func (h *handler) Host(r *http.Request) string {
host := h.host
if host == "" {
host = defaultHost(r)
}
return host
}

var indexTmpl = template.Must(template.New("index").Parse(`<!DOCTYPE html>
<html>
<h1>{{.Host}}</h1>
<ul>
{{range .Handlers}}<li><a href="https://godoc.org/{{.}}">{{.}}</a></li>{{end}}
</ul>
</html>
`))

var vanityTmpl = template.Must(template.New("vanity").Parse(`<!DOCTYPE html>
<html>
<head>
Expand Down
1 change: 1 addition & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func TestHandler(t *testing.T) {
path: "/portmidi",
goImport: "example.com/portmidi git https://github.com/rakyll/portmidi",
goSource: "example.com/portmidi https://github.com/rakyll/portmidi _ _",
link: "godoc.org/"
},
{
name: "display GitHub inference",
Expand Down

0 comments on commit d76d64b

Please sign in to comment.