vanity/modules/router/router.go

60 lines
1.3 KiB
Go

package router
import (
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"go.jolheiser.com/beaver"
"go.jolheiser.com/vanity/modules/config"
"go.jolheiser.com/vanity/modules/router/templates"
"html/template"
"net/http"
"runtime"
"strings"
"time"
)
var (
index = template.Must(template.New("index").Parse(templates.Head + templates.Index + templates.Info + templates.Foot))
vanity = template.Must(template.New("vanity").Parse(templates.Head + templates.Vanity + templates.Info + templates.Foot))
cache = config.PackageMap()
)
func Init() *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.RedirectSlashes)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(30 * time.Second))
r.Get("/", doGet)
r.Get("/*", doPackage)
return r
}
func doGet(res http.ResponseWriter, req *http.Request) {
if err := index.Execute(res, map[string]interface{}{
"Packages": config.Packages,
"AppVer": config.Version,
"GoVer": runtime.Version(),
}); err != nil {
beaver.Error(err)
}
}
func doPackage(res http.ResponseWriter, req *http.Request) {
key := chi.URLParam(req, "*")
pkg, ok := cache[strings.Split(key, "/")[0]]
if !ok {
http.NotFound(res, req)
return
}
if err := vanity.Execute(res, map[string]interface{}{
"Package": pkg,
"AppVer": config.Version,
"GoVer": runtime.Version(),
}); err != nil {
beaver.Error(err)
}
}