vanity/router/api.go

72 lines
1.5 KiB
Go

package router
import (
"encoding/json"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"go.jolheiser.com/beaver"
"go.jolheiser.com/vanity/api"
"go.jolheiser.com/vanity/flags"
"net/http"
"runtime"
"time"
)
func apiRoutes() *chi.Mux {
r := chi.NewRouter()
r.Use(cors.AllowAll().Handler)
r.Get("/status", doAPIStatus)
r.Get("/update", doAPIUpdate)
return r
}
func doAPIStatus(res http.ResponseWriter, _ *http.Request) {
res.Header().Set("Content-Type", "application/json")
var nextUpdate *string
if !lastUpdate.IsZero() {
nu := lastUpdate.Add(flags.Interval).Format(time.RFC3339)
nextUpdate = &nu
}
resp := map[string]interface{}{
"vanity_version": api.Version,
"go_version": runtime.Version(),
"num_packages": len(cache.Packages),
"next_update": nextUpdate,
}
data, err := json.Marshal(&resp)
if err != nil {
beaver.Errorf("could not marshal API status: %v", err)
data = []byte("{}")
}
if _, err = res.Write(data); err != nil {
beaver.Errorf("could not write response: %v", err)
}
}
func doAPIUpdate(res http.ResponseWriter, _ *http.Request) {
res.Header().Set("Content-Type", "application/json")
resp := map[string]bool{
"updated": false,
}
if canUpdate {
updateCache()
resp["updated"] = true
}
payload, err := json.Marshal(resp)
if err != nil {
beaver.Errorf("could not marshal payload: %v", err)
}
if _, err = res.Write(payload); err != nil {
beaver.Errorf("could not write response: %v", err)
}
}