-
-
This commit is contained in:
71
datasource/controller/controller.go
Normal file
71
datasource/controller/controller.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"datasource/store"
|
||||
)
|
||||
|
||||
type Controller struct {
|
||||
store *store.Store
|
||||
}
|
||||
|
||||
func NewController(store *store.Store) *Controller {
|
||||
return &Controller{store: store}
|
||||
}
|
||||
|
||||
func (c *Controller) GetMetrics(w http.ResponseWriter, r *http.Request) {
|
||||
query := r.URL.Query()
|
||||
|
||||
service := query.Get("service")
|
||||
if service == "" {
|
||||
http.Error(w, "service cannot be empty", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
t0, err := strconv.ParseInt(query.Get("t0"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
t1, err := strconv.ParseInt(query.Get("t1"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if t0 > t1 {
|
||||
http.Error(w, "t0 cannot be larger than t1", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
metrics, err := c.store.GetMetrics(r.Context(), service, t0, t1)
|
||||
if err != nil {
|
||||
// todo (david): log internal server error
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
|
||||
if err := json.NewEncoder(&buf).Encode(metrics); err != nil {
|
||||
// todo (david): log internal server error
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if _, err := io.Copy(w, &buf); err != nil {
|
||||
// too late to return http.StatusInternalServerError
|
||||
// todo (david): log internal server error
|
||||
}
|
||||
}
|
||||
|
||||
// todo (david)
|
||||
// func (c *Controller) DeleteMetrics(w http.ResponseWriter, r *http.Request) {}
|
||||
Reference in New Issue
Block a user