2020-09-10 17:27:46 +00:00
|
|
|
package router
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
|
|
|
"runtime"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2020-09-12 01:38:18 +00:00
|
|
|
"go.jolheiser.com/vanity/api"
|
2020-09-10 18:43:38 +00:00
|
|
|
"go.jolheiser.com/vanity/flags"
|
2020-09-10 17:27:46 +00:00
|
|
|
"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()
|
|
|
|
|
2020-09-12 01:38:18 +00:00
|
|
|
beaver.Infof("Running vanity server at http://localhost:%d", flags.Port)
|
2020-09-10 17:27:46 +00:00
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
func doIndex(res http.ResponseWriter, _ *http.Request) {
|
|
|
|
if err := index.Execute(res, map[string]interface{}{
|
|
|
|
"Packages": cache.packages,
|
2020-09-12 01:38:18 +00:00
|
|
|
"AppVer": api.Version,
|
2020-09-10 17:27:46 +00:00
|
|
|
"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,
|
2020-09-12 01:38:18 +00:00
|
|
|
"AppVer": api.Version,
|
2020-09-10 17:27:46 +00:00
|
|
|
"GoVer": runtime.Version(),
|
2020-09-12 01:38:18 +00:00
|
|
|
"GoSource": fmt.Sprintf("%s %s %s %s", pkg.Module(flags.Domain), pkg.CloneHTTP, svc.GoDir(pkg), svc.GoFile(pkg)),
|
2020-09-10 17:27:46 +00:00
|
|
|
}); err != nil {
|
|
|
|
beaver.Error(err)
|
|
|
|
}
|
|
|
|
}
|