Skip to content

Commit

Permalink
fixed error by interface error supported
Browse files Browse the repository at this point in the history
  • Loading branch information
kubitre committed Feb 4, 2022
1 parent 117060e commit b7f914b
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 8 deletions.
19 changes: 11 additions & 8 deletions extractors/extract_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@ import (
)

const (
tagParsing = "query"
paramExtracting = "ex_param"
)

// TODO: make abstract type interface{}
type extractor func(string, *http.Request) string
type extractor func(string, *http.Request) interface{}

func RequestToType(request *http.Request, data interface{}, parseQuery, parseParams bool) (interface{}, error) {
if err := json.NewDecoder(request.Body).Decode(&data); err != nil {
Expand All @@ -38,26 +37,30 @@ func RequestToType(request *http.Request, data interface{}, parseQuery, parsePar
return data, nil
}

func extractFromQuery(paramName string, request *http.Request) string {
func extractFromQuery(paramName string, request *http.Request) interface{} {
return request.URL.Query().Get(paramName)
}

func extractFromPathVariables(paramName string, request *http.Request) string {
func extractFromPathVariables(paramName string, request *http.Request) interface{} {
vars := request.Context().Value(0).(map[string]interface{})
return vars[paramName].(string)
}

func extractFromHeaders(paramName string, request *http.Request) interface{} {
return request.Header.Get(paramName)
}

func prepareInlineStructFields(request *http.Request, value reflect.Value, preparator extractor) error {
for i := 0; i < value.NumField(); i++ {
val := reflect.Indirect(value.Field(i).Addr())
if val.Kind() == reflect.Struct {
prepareInlineStructFields(request, val, preparator)
} else {
parsedTag := value.Type().Field(i).Tag.Get(tagParsing)
parsedTag := value.Type().Field(i).Tag.Get(paramExtracting)
if parsedTag != "" {
dataQuery := request.URL.Query().Get(parsedTag)
dataQuery := preparator(parsedTag, request)
if dataQuery != "" {
value.SetString(dataQuery)
value.Set(reflect.ValueOf(dataQuery)) // TODO: need format to concrete type
} else {
return errors.New("in request does not exist query param with name: " + parsedTag)
}
Expand Down
50 changes: 50 additions & 0 deletions middlewares/metrics_middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package middlewares

import (
"net/http"
"strconv"
"time"

metricsprometheus "github.com/kubitre/go_api_infra/metrics_prometheus"
)

func AddGoldenMetrics(recorder metricsprometheus.MetricRecorder, method string, handler http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
wi := &responseWriterInterceptor{
statusCode: http.StatusOK,
ResponseWriter: writer,
}

timeStart := time.Now()
defer func() {
recorder.ObserveHTTPRequestDuration(request.Context(), metricsprometheus.HTTPReqProperties{
Method: method,
Code: strconv.Itoa(wi.statusCode),
}, time.Since(timeStart))

recorder.ObserveHTTPResponseSize(request.Context(), metricsprometheus.HTTPReqProperties{
Method: method,
Code: strconv.Itoa(wi.statusCode),
}, wi.sizeResponse)
}()

handler.ServeHTTP(wi, request)
})
}

type responseWriterInterceptor struct {
http.ResponseWriter
statusCode int
sizeResponse int64
}

func (w *responseWriterInterceptor) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}

func (w *responseWriterInterceptor) Write(bts []byte) (int, error) {
size, err := w.ResponseWriter.Write(bts)
w.sizeResponse = int64(size)
return size, err
}
11 changes: 11 additions & 0 deletions response/api_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ type ApiError struct {
Errors []ApiError `json:"errors,omitempty"`
}

func (e ApiError) Error() string {
result := "Err: " + string(e.Code) + " " + e.Message
if e.Target != "" {
result += "Service: " + e.Target
}
if e.TraceId != "" {
result += "TraceID: " + e.TraceId
}
return result
}

func MakeApiError(code string, message string, target string) ApiError {
return ApiError{
Code: code,
Expand Down

0 comments on commit b7f914b

Please sign in to comment.