package router import ( "fmt" "html/template" "net/http" "runtime" "strings" "time" "go.jolheiser.com/vanity/api" "go.jolheiser.com/vanity/flags" "go.jolheiser.com/vanity/router/templates" "go.jolheiser.com/vanity/service" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "go.jolheiser.com/beaver" ) var ( index = template.Must(template.New("index").Parse(templates.Head + templates.Index + templates.Foot)) vanity = template.Must(template.New("vanity").Parse(templates.Head + templates.Vanity + templates.Foot)) ) func Init() *chi.Mux { r := chi.NewRouter() r.Use(middleware.RedirectSlashes) r.Use(middleware.Recoverer) r.Use(middleware.Timeout(30 * time.Second)) r.Get("/", doIndex) r.Get("/*", doVanity) svc = service.New() beaver.Info("Warming up cache...") cronUpdate() beaver.Infof("Finished warming up cache: %s", cache.Names()) go cronStart() beaver.Infof("Running vanity server at http://localhost:%d", flags.Port) return r } func doIndex(res http.ResponseWriter, _ *http.Request) { if err := index.Execute(res, map[string]interface{}{ "Packages": cache.packages, "AppVer": api.Version, "GoVer": runtime.Version(), }); err != nil { beaver.Error(err) } } func doVanity(res http.ResponseWriter, req *http.Request) { key := chi.URLParam(req, "*") pkg, ok := cache.packages[strings.Split(key, "/")[0]] if !ok { http.NotFound(res, req) return } if err := vanity.Execute(res, map[string]interface{}{ "Package": pkg, "AppVer": api.Version, "GoVer": runtime.Version(), "GoSource": fmt.Sprintf("%s %s %s %s", pkg.Module(flags.Domain), pkg.CloneHTTP, svc.GoDir(pkg), svc.GoFile(pkg)), }); err != nil { beaver.Error(err) } }