64 lines
1.7 KiB
Go
64 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"queues-go/app/routers"
|
|
client "queues-go/app/storage/mongo"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
func writeMetric(timestamp time.Time, endpoint string, statusCode int, responseTime int, method string) {
|
|
s := fmt.Sprintf(
|
|
`{"timestamp":"%s","service":"queues","environment":"%s","endpoint":"%s","status_code":%s,"response_time":%s,"method":"%s"}`,
|
|
timestamp.Format("2006-01-02T15:04:05Z"),
|
|
os.Getenv("STAGE"),
|
|
endpoint,
|
|
strconv.Itoa(statusCode),
|
|
strconv.Itoa(responseTime),
|
|
method,
|
|
)
|
|
data := []byte(s)
|
|
r := bytes.NewReader(data)
|
|
_, err := http.Post("http://monitoring:1237/api/v1/metrics/endpoint", "application/json", r)
|
|
if err != nil {
|
|
log.Printf("Error sending metrics %s", err.Error())
|
|
}
|
|
}
|
|
|
|
func handlerWrapper(f func(*http.Request) (interface{}, int)) func(http.ResponseWriter, *http.Request) {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
response, status := f(r)
|
|
if response != nil {
|
|
data, err := json.Marshal(response)
|
|
if err != nil {
|
|
log.Printf("Error marshalling response")
|
|
status = http.StatusInternalServerError
|
|
}
|
|
w.WriteHeader(status)
|
|
w.Write(data)
|
|
} else {
|
|
w.WriteHeader(status)
|
|
}
|
|
go writeMetric(start, r.URL.Path, status, int(time.Since(start).Milliseconds()), r.Method)
|
|
log.Printf("%s %d %s", r.URL, status, time.Since(start))
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
client.Connect()
|
|
routers.MutexMap = make(map[string]*sync.Mutex)
|
|
http.HandleFunc("/api/v1/take", handlerWrapper(routers.Take))
|
|
http.HandleFunc("/api/v1/finish", handlerWrapper(routers.Finish))
|
|
http.HandleFunc("/api/v1/put", handlerWrapper(routers.Put))
|
|
log.Printf("Server started")
|
|
http.ListenAndServe(":1239", nil)
|
|
}
|