71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
package router
|
|
|
|
import (
|
|
"encoding/json"
|
|
"github.com/go-chi/chi"
|
|
"github.com/go-chi/chi/middleware"
|
|
"go.jolheiser.com/beaver"
|
|
"go.jolheiser.com/gpm/modules/config"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
var cache map[string]config.Package
|
|
|
|
func Init() *chi.Mux {
|
|
r := chi.NewRouter()
|
|
r.Use(middleware.RedirectSlashes)
|
|
r.Use(middleware.Recoverer)
|
|
r.Use(middleware.Timeout(30 * time.Second))
|
|
|
|
r.Get("/", handleHome)
|
|
r.Get("/export", handleExport)
|
|
r.Get("/package/{name}", handlePackage)
|
|
|
|
cache = config.PackageMap()
|
|
|
|
return r
|
|
}
|
|
|
|
func handleHome(res http.ResponseWriter, _ *http.Request) {
|
|
status, err := json.Marshal(map[string]interface{}{
|
|
"version": config.Version,
|
|
"packages": len(config.Packages),
|
|
})
|
|
if err != nil {
|
|
res.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = res.Write([]byte("{}"))
|
|
return
|
|
}
|
|
|
|
_, _ = res.Write(status)
|
|
}
|
|
|
|
func handleExport(res http.ResponseWriter, _ *http.Request) {
|
|
export, err := config.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("{}"))
|
|
}
|