package router import ( "fmt" "html/template" "net/http" "strings" "time" "go.jolheiser.com/vanity/flags" "go.jolheiser.com/vanity/service" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "go.jolheiser.com/beaver" ) var tmpl *template.Template func Init() (*chi.Mux, error) { var err error tmpl, err = Templates() if err != nil { return nil, err } r := chi.NewRouter() r.Use(middleware.RedirectSlashes) r.Use(middleware.Recoverer) r.Use(middleware.Timeout(60 * time.Second)) r.Get("/", doIndex) r.Get("/*", doVanity) r.Mount("/_", apiRoutes()) svc = service.New() beaver.Info("Warming up cache...") updateCache() beaver.Infof("Finished warming up cache: %s", cache.Packages.Names()) go cronStart() beaver.Infof("Running vanity server at http://localhost:%d", flags.Port) return r, nil } func doIndex(res http.ResponseWriter, req *http.Request) { format := "list" if flags.Topics { format = "topics" } q := req.URL.Query().Get("format") if q != "" { format = q } if err := tmpl.Lookup("index.tmpl").Execute(res, map[string]interface{}{ "Packages": cache.Packages, "Index": true, "Format": format, }); err != nil { beaver.Errorf("could not write response: %v", 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 } ctx := map[string]interface{}{ "Package": pkg, "Module": pkg.Module(flags.Domain), "GoSource": fmt.Sprintf("%s %s %s %s", pkg.Module(flags.Domain), pkg.CloneHTTP, svc.GoDir(pkg), svc.GoFile(pkg)), "Index": false, } q := req.URL.Query() if q.Get("go-get") != "" || q.Get("git-import") != "" { if err := tmpl.Lookup("import.tmpl").Execute(res, ctx); err != nil { beaver.Errorf("could not write response: %v", err) } return } if err := tmpl.Lookup("vanity.tmpl").Execute(res, ctx); err != nil { beaver.Errorf("could not write response: %v", err) } }