/ pkg / web / metrics.go
metrics.go
 1  package web
 2  
 3  import (
 4  	"encoding/json"
 5  	"io"
 6  	"log"
 7  	"net/http"
 8  
 9  	dogeboxd "github.com/dogeorg/dogeboxd/pkg"
10  )
11  
12  func (t api) getPupMetrics(w http.ResponseWriter, r *http.Request) {
13  	pupID := r.PathValue("ID")
14  	lastOnly := r.URL.Query().Get("last") == "true"
15  
16  	metrics := t.dbx.Pups.GetMetrics(pupID)
17  
18  	if !lastOnly {
19  		sendResponse(w, metrics)
20  		return
21  	}
22  
23  	lastMetrics := make(map[string]interface{})
24  	for name, buffer := range metrics {
25  		switch bufferSlice := buffer.(type) {
26  		case []string:
27  			if len(bufferSlice) > 0 {
28  				lastMetrics[name] = bufferSlice[0]
29  			}
30  		case []int:
31  			if len(bufferSlice) > 0 {
32  				lastMetrics[name] = bufferSlice[0]
33  			}
34  		case []float64:
35  			if len(bufferSlice) > 0 {
36  				lastMetrics[name] = bufferSlice[0]
37  			}
38  		default:
39  			log.Printf("Unexpected buffer type for metric %s", name)
40  		}
41  	}
42  
43  	sendResponse(w, lastMetrics)
44  }
45  
46  func (t InternalRouter) recordMetrics(w http.ResponseWriter, r *http.Request) {
47  	originPup, ok := t.getOriginPup(r)
48  	if !ok {
49  		// you must be a pup!
50  		forbidden(w, "You are not a Pup we know about")
51  		return
52  	}
53  
54  	body, err := io.ReadAll(r.Body)
55  	if err != nil {
56  		sendErrorResponse(w, http.StatusBadRequest, "Error reading request body")
57  		return
58  	}
59  	defer r.Body.Close()
60  
61  	data := make(map[string]dogeboxd.PupMetric)
62  	err = json.Unmarshal(body, &data)
63  	if err != nil {
64  		sendErrorResponse(w, http.StatusBadRequest, "Error unmarshalling JSON")
65  		return
66  	}
67  
68  	update := dogeboxd.UpdateMetrics{
69  		PupID:   originPup.ID,
70  		Payload: data,
71  	}
72  
73  	id := t.dbx.AddAction(update)
74  	sendResponse(w, map[string]string{"id": id})
75  }