Browse Source

Make additional type-interface checkings for prices from partners

master
Дмитрий 2 years ago
parent
commit
260c25455e
  1. 21
      cmd/client_server/handlers.go
  2. 22
      cmd/client_server/handlers_test.go

21
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
}
}

22
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

Loading…
Cancel
Save