Files
janus/server/handlers.go
2024-03-06 20:11:34 +05:30

95 lines
2.5 KiB
Go

package server
import (
metrics "com.navi.medici.janus/instrumentation"
"com.navi.medici.janus/lib"
"com.navi.medici.janus/utils"
"compress/gzip"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"time"
"fmt"
"strings"
)
var (
healthyBool bool = true
)
const (
JSON = "json"
SUCCESS = "success"
ERROR = "error"
)
type NewSchemaRequest struct {
Topic string `json:"topic"`
Schema string `json:"schema"`
SchemaType string `json:"schema_type"`
}
type CustomResponse struct {
Code int `json:"code"`
Message string `json:"message"`
}
func eventsHandlerJson(w http.ResponseWriter, r *http.Request) {
eventHandlerStartTime := utils.NanosToMillis(time.Now().UnixNano())
headerName := "X-Correlation-Id"
substring := "abcdabcd-1234"
headerValue, ok := r.Header[headerName]
if ok {
if strings.HasPrefix(headerValue[0], substring) {
w.Header().Set("Content-Type", "application/json")
var rsp = CustomResponse{Code: 200, Message: "OK"}
json.NewEncoder(w).Encode(rsp)
fmt.Println("Dropped blacklisted request")
return
}
}
var reader io.Reader
// check if body is gzip compressed
if r.Header.Get("Content-Encoding") == "gzip" {
var err error
reader, err = gzip.NewReader(r.Body)
if err != nil {
// log.Printf(err)
w.Header().Set("Content-Type", "application/json")
http.Error(w, "Error while decompressing GZIP payload", http.StatusBadRequest)
metrics.EventHandlerTimeHist.WithLabelValues(JSON, ERROR).Observe(float64(utils.NanosToMillis(time.Now().UnixNano()) - eventHandlerStartTime))
return
}
} else {
reader = r.Body
}
body, err := ioutil.ReadAll(reader)
if err != nil {
// log.Printf(err)
w.Header().Set("Content-Type", "application/json")
http.Error(w, "Request body invalid", http.StatusBadRequest)
metrics.EventHandlerTimeHist.WithLabelValues(JSON, ERROR).Observe(float64(utils.NanosToMillis(time.Now().UnixNano()) - eventHandlerStartTime))
return
}
w.Header().Set("Content-Type", "application/json")
lib.JsonRequestChannel <- &lib.RequestObject{Body: body, Header: r.Header}
var rsp = CustomResponse{Code: 200, Message: "OK"}
json.NewEncoder(w).Encode(rsp)
metrics.EventHandlerTimeHist.WithLabelValues(JSON, SUCCESS).Observe(float64(utils.NanosToMillis(time.Now().UnixNano()) - eventHandlerStartTime))
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
if healthyBool {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, "true")
} else {
http.Error(w, "server unhealthy", http.StatusServiceUnavailable)
return
}
}