83 lines
1.8 KiB
Go
83 lines
1.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/danilsolovyov/croupierCbrf/internal/dal"
|
|
"github.com/themakers/hlog"
|
|
)
|
|
|
|
//#region ======== Handler Struct ========
|
|
|
|
type Handler struct {
|
|
mongo *dal.MongoConnection
|
|
hl hlog.Logger
|
|
origins string
|
|
}
|
|
|
|
func NewHandler(mongo *dal.MongoConnection, logger hlog.Logger, origins string) *Handler {
|
|
return &Handler{
|
|
mongo: mongo,
|
|
hl: logger,
|
|
origins: origins,
|
|
}
|
|
}
|
|
|
|
// report Error - Send false Response with string error
|
|
func (h *Handler) reportError(w http.ResponseWriter, r *http.Request, status int, errClient string, errLog error) {
|
|
w.Header().Set("Access-Control-Allow-Origin", h.origins)
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
|
|
w.WriteHeader(status)
|
|
errEncode := json.NewEncoder(w).Encode(Response{false, errClient})
|
|
|
|
if errEncode != nil {
|
|
h.hl.Emit(ErrorReportCanNotSend{errEncode})
|
|
return
|
|
}
|
|
|
|
h.hl.Emit(ErrorHandler{r.URL.String(), errLog})
|
|
}
|
|
|
|
// send Response struct with http status 200
|
|
func (h *Handler) sendResponse(w http.ResponseWriter, r *http.Request, response Response) {
|
|
w.Header().Set("Access-Control-Allow-Origin", h.origins)
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
err := json.NewEncoder(w).Encode(response)
|
|
|
|
if err != nil {
|
|
h.reportError(w, r, http.StatusInternalServerError, "response failed", err)
|
|
}
|
|
}
|
|
|
|
//#endregion
|
|
|
|
//#region ======== Response Structs ========
|
|
|
|
type Response struct {
|
|
Success bool `json:"success"` // True if OK
|
|
Message interface{} `json:"message"` // Message Response body
|
|
}
|
|
|
|
//#endregion
|
|
|
|
//#region ======== Hl Handlers Errors ========
|
|
|
|
type ErrorReportCanNotSend struct {
|
|
Err error
|
|
}
|
|
|
|
type ErrorHandler struct {
|
|
URL string
|
|
Err error
|
|
}
|
|
|
|
//#endregion
|
|
|
|
//#region ======== Other functions ========
|
|
|
|
//#endregion
|