package http import ( "encoding/json" "fmt" "net/http" "git.loyso.art/frx/devsim/internal/entities" "git.loyso.art/frx/devsim/internal/store" ) // ListenAndServe runs server to accept incoming connections. This function blocks on // handling connections. func listStatsHandler(sr store.Stats) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } stats, err := sr.List(r.Context()) if err != nil { http.Error(w, fmt.Errorf("listing stats: %w", err).Error(), http.StatusInternalServerError) return } w.Header().Set("content-type", "application/json") err = json.NewEncoder(w).Encode(stats) if err != nil { http.Error(w, fmt.Errorf("encoding payload: %w", err).Error(), http.StatusInternalServerError) } }) } func postStatsHandler(sr store.Stats) http.HandlerFunc { type request struct { IncomingTraffic int `json:"incoming_traffic"` OutgoingTraffic int `json:"outgoing_traffic"` IncomingRPS int `json:"incoming_rps"` ReadRPS int `json:"read_rps"` WriteRPS int `json:"write_rps"` } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } id := r.PathValue("id") if id == "" { http.Error(w, "no id provided", http.StatusBadRequest) return } var reqbody request err := json.NewDecoder(r.Body).Decode(&reqbody) if err != nil { http.Error(w, fmt.Errorf("decoding body: %w", err).Error(), http.StatusBadRequest) return } ctx := r.Context() err = sr.Upsert(ctx, entities.DeviceStatistics{ ID: entities.DeviceID(id), IncomingTrafficBytes: reqbody.IncomingTraffic, OutgoingTrafficBytes: reqbody.OutgoingTraffic, IncomingRPS: reqbody.IncomingRPS, ReadRPS: reqbody.ReadRPS, WriteRPS: reqbody.WriteRPS, }) if err != nil { http.Error(w, fmt.Errorf("upserting stat metric: %w", err).Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }) }