From 260c25455e1bb9499a46a8eaf4d875d88fd4d45a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Tue, 25 Oct 2022 15:58:33 +0300 Subject: [PATCH] Make additional type-interface checkings for prices from partners --- cmd/client_server/handlers.go | 21 +++++++++++++++++++-- cmd/client_server/handlers_test.go | 22 +++++++--------------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/cmd/client_server/handlers.go b/cmd/client_server/handlers.go index 1c14420..1f9772c 100644 --- a/cmd/client_server/handlers.go +++ b/cmd/client_server/handlers.go @@ -9,6 +9,7 @@ import ( "net/http" customtypes "sample-choose-ad/cmd/custom_types" req_types "sample-choose-ad/cmd/requests_types" + "strconv" "sync" ) @@ -93,8 +94,24 @@ func handleRequest(partners []customtypes.PartnersAddress) http.HandlerFunc { } // Replase with new Imp, if last saved price smaller - // Using type assertion, 'cause `Price` is interface - if partnersRespones[resp.Id].Price.(float64) < resp.Price.(float64) { + // Using type switch and addition checks, 'cause `Price` is interface + var oldPrice float64 + switch partnersRespones[resp.Id].Price.(type) { + case string: + oldPrice, _ = strconv.ParseFloat(partnersRespones[resp.Id].Price.(string), 64) + case float64: + oldPrice = partnersRespones[resp.Id].Price.(float64) + } + + var newPrice float64 + switch resp.Price.(type) { + case string: + newPrice, _ = strconv.ParseFloat(resp.Price.(string), 64) + case float64: + newPrice = resp.Price.(float64) + } + + if oldPrice < newPrice { partnersRespones[resp.Id] = resp } } diff --git a/cmd/client_server/handlers_test.go b/cmd/client_server/handlers_test.go index cf7657c..346b9d4 100644 --- a/cmd/client_server/handlers_test.go +++ b/cmd/client_server/handlers_test.go @@ -4,8 +4,10 @@ import ( "bytes" "encoding/json" "io/ioutil" + "log" "net/http" "net/http/httptest" + "os" customtypes "sample-choose-ad/cmd/custom_types" req_types "sample-choose-ad/cmd/requests_types" "testing" @@ -41,22 +43,12 @@ func TestPostRequestWithEmptyBody(t *testing.T) { } func TestPostRequestWithRightBody(t *testing.T) { - body_json := `{ - "id": "123", - "tiles": [ - { - "id": 123, - "width": 122, - "ratio": 1.5 - } - ], - "context": { - "ip": "192.168.1.1", - "user_agent": "curl" - } -}` + file, err := os.ReadFile("../../internal/curl_requests/simple.json") + if err != nil { + log.Fatal(err) + } - req := httptest.NewRequest(http.MethodPost, "/placements/request", bytes.NewBuffer([]byte(body_json))) + req := httptest.NewRequest(http.MethodPost, "/placements/request", bytes.NewBuffer(file)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() _, _ = req, w