gpm/modules/router/router.go

71 lines
1.4 KiB
Go
Raw Normal View History

package router
import (
"encoding/json"
"gitea.com/jolheiser/beaver"
"gitea.com/jolheiser/gpm/modules/config"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"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("/status", handleStatus)
r.Get("/export", handleExport)
r.Get("/package/{name}", handlePackage)
cache = config.PackageMap()
return r
}
func handleStatus(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("{}"))
}