77 lines
1.6 KiB
Go
77 lines
1.6 KiB
Go
package router
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"go.jolheiser.com/gpm/config"
|
|
|
|
"github.com/go-chi/chi"
|
|
"github.com/go-chi/chi/middleware"
|
|
"go.jolheiser.com/beaver"
|
|
)
|
|
|
|
var cache map[string]config.Package
|
|
|
|
func New(cfg *config.Config) *chi.Mux {
|
|
r := chi.NewRouter()
|
|
r.Use(middleware.RedirectSlashes)
|
|
r.Use(middleware.Recoverer)
|
|
r.Use(middleware.Timeout(30 * time.Second))
|
|
|
|
r.Get("/", handleHome(cfg))
|
|
r.Get("/export", handleExport(cfg))
|
|
r.Get("/package/{name}", handlePackage)
|
|
|
|
cache = cfg.Packages.Map()
|
|
|
|
return r
|
|
}
|
|
|
|
func handleHome(cfg *config.Config) func(res http.ResponseWriter, _ *http.Request) {
|
|
return func(res http.ResponseWriter, _ *http.Request) {
|
|
status, err := json.Marshal(map[string]interface{}{
|
|
"version": config.Version,
|
|
"packages": len(cfg.Packages),
|
|
})
|
|
if err != nil {
|
|
res.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = res.Write([]byte("{}"))
|
|
return
|
|
}
|
|
|
|
_, _ = res.Write(status)
|
|
}
|
|
}
|
|
|
|
func handleExport(cfg *config.Config) func(res http.ResponseWriter, _ *http.Request) {
|
|
return func(res http.ResponseWriter, _ *http.Request) {
|
|
export, err := cfg.Export()
|
|
if err != nil {
|
|
beaver.Error(err)
|
|
return
|
|
}
|
|
|
|
_, _ = res.Write([]byte(export))
|
|
}
|
|
}
|
|
|
|
func handlePackage(res http.ResponseWriter, req *http.Request) {
|
|
name := chi.URLParam(req, "name")
|
|
|
|
if pkg, ok := cache[name]; ok {
|
|
data, err := json.Marshal(pkg)
|
|
if err != nil {
|
|
res.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = res.Write([]byte("{}"))
|
|
return
|
|
}
|
|
_, _ = res.Write(data)
|
|
return
|
|
}
|
|
|
|
res.WriteHeader(http.StatusNotFound)
|
|
_, _ = res.Write([]byte("{}"))
|
|
}
|