From 3e556645fa07e69843551b5b71a429686b662557 Mon Sep 17 00:00:00 2001 From: jonbetti Date: Wed, 6 Jun 2018 03:40:20 +0000 Subject: [PATCH] Split option processing from serving git-svn-id: file:///srv/svn/repo/toyohime/trunk@88 922d331f-388e-da47-97a9-ad700dc0b8b9 --- vanity.go | 62 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/vanity.go b/vanity.go index a699606..7af7e48 100644 --- a/vanity.go +++ b/vanity.go @@ -62,33 +62,25 @@ func WithRedirector(redir Redirector) Option { } } -// Returns an http.Handler that serves the vanity URL information for a single -// repository. Each Option gives additional information to agents about the -// repository or provides help to browsers that may have navigated to the vanity -// URL. The WithImport Option is mandatory since the go tool requires it to -// fetch the repository. -func Handler(opts ...Option) http.Handler { - var redir Redirector +func compile(opts []Option) (*template.Template, Redirector) { + // Process options. + var cfg config + for _, opt := range opts { + opt(&cfg) + } - tpl := func() *template.Template { - // Process options. - var cfg config - for _, opt := range opts { - opt(&cfg) - } + // A WithImport is required. + if cfg.importTag == nil { + panic("vanity: WithImport is required") + } - // A WithImport is required. - if cfg.importTag == nil { - panic("vanity: WithImport is required") - } + tags := []string{*cfg.importTag} + if cfg.sourceTag != nil { + tags = append(tags, *cfg.sourceTag) + } + tagBlk := strings.Join(tags, "\n") - tags := []string{*cfg.importTag} - if cfg.sourceTag != nil { - tags = append(tags, *cfg.sourceTag) - } - tagBlk := strings.Join(tags, "\n") - - h := fmt.Sprintf(` + h := fmt.Sprintf(` @@ -101,16 +93,17 @@ Nothing to see here; move along. `, tagBlk) - redir = cfg.redir - return template.Must(template.New("").Parse(h)) - }() - - if redir == nil { - redir = func(pkg string) string { + // Use default GDDO Redirector. + if cfg.redir == nil { + cfg.redir = func(pkg string) string { return "https://godoc.org/" + pkg } } + return template.Must(template.New("").Parse(h)), cfg.redir +} + +func handlerFrom(tpl *template.Template, redir Redirector) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Redirect to https. if r.URL.Scheme == "http" { @@ -142,6 +135,15 @@ Nothing to see here; move along. }) } +// Returns an http.Handler that serves the vanity URL information for a single +// repository. Each Option gives additional information to agents about the +// repository or provides help to browsers that may have navigated to the vanity +// URL. The WithImport Option is mandatory since the go tool requires it to +// fetch the repository. +func Handler(opts ...Option) http.Handler { + return handlerFrom(compile(opts)) +} + // Helpers for common VCSs. // Redirects gddo to browsable source files for GitHub hosted repositories.