2022-08-11 15:26:55 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
|
2024-11-11 18:50:17 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
|
2022-08-11 15:26:55 +00:00
|
|
|
"github.com/gorilla/mux"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (h APIHandler) GetCache(w http.ResponseWriter, r *http.Request) {
|
|
|
|
vars := mux.Vars(r)
|
|
|
|
cacheid := vars["cacheid"]
|
2023-04-20 10:14:25 +00:00
|
|
|
// Use a channel to synchronize the goroutines
|
|
|
|
ch := make(chan []byte)
|
|
|
|
// Fetch data from cache asynchronously
|
|
|
|
go func() {
|
|
|
|
d, err := h.cache.Get(cacheid)
|
|
|
|
if err != nil {
|
2024-11-11 18:50:17 +00:00
|
|
|
log.Error().Err(err).Msg("")
|
2023-04-20 10:14:25 +00:00
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
ch <- nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
var data []any
|
|
|
|
if val, ok := d.([]any); ok {
|
|
|
|
data = val
|
|
|
|
} else {
|
|
|
|
data = []any{d}
|
|
|
|
}
|
|
|
|
j := toJSON(data, w, r)
|
|
|
|
ch <- j // Signal that the data has been fetched successfully
|
|
|
|
close(ch)
|
|
|
|
}()
|
|
|
|
// wait for the JSON marshaling goroutine to finish
|
|
|
|
j := <-ch
|
|
|
|
if j == nil {
|
|
|
|
return // Stop processing if an error occurred
|
2022-08-11 15:26:55 +00:00
|
|
|
}
|
2023-04-20 10:14:25 +00:00
|
|
|
// Send the JSON response to the client
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Write(j)
|
2022-08-11 15:26:55 +00:00
|
|
|
|
2023-04-20 10:14:25 +00:00
|
|
|
<-ch
|
|
|
|
}
|
|
|
|
func toJSON(data []any, w http.ResponseWriter, r *http.Request) []byte {
|
|
|
|
result := data
|
|
|
|
if limitsmin, ok := r.URL.Query()["limits.min"]; ok {
|
|
|
|
min, _ := strconv.Atoi(limitsmin[0])
|
|
|
|
if limitsmax, ok := r.URL.Query()["limits.max"]; ok {
|
|
|
|
max, _ := strconv.Atoi(limitsmax[0])
|
|
|
|
if max > len(data) {
|
2022-08-11 15:26:55 +00:00
|
|
|
result = data[min:]
|
2023-04-20 10:14:25 +00:00
|
|
|
} else {
|
|
|
|
result = data[min:max]
|
2022-08-11 15:26:55 +00:00
|
|
|
}
|
2023-04-20 10:14:25 +00:00
|
|
|
} else {
|
|
|
|
result = data[min:]
|
2022-08-11 15:26:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
j, err := json.Marshal(result)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
2023-04-20 10:14:25 +00:00
|
|
|
return nil
|
2022-08-11 15:26:55 +00:00
|
|
|
}
|
2023-04-20 10:14:25 +00:00
|
|
|
return j
|
2022-08-11 15:26:55 +00:00
|
|
|
}
|