You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.7 KiB

package clientserver
import (
"bytes"
2 years ago
"context"
"encoding/json"
"io/ioutil"
"log"
"math"
"net/http"
req_types "sample-choose-ad/cmd/requests_types"
2 years ago
"sync"
"time"
)
2 years ago
// Make request to partner, born to run as gorutine, 'cuz send partner response into channel
2 years ago
func makeRequest(url string, body *[]byte, response chan<- []req_types.RespImp, wg *sync.WaitGroup) {
defer wg.Done()
var pResp req_types.SuccesResponse
2 years ago
c := &http.Client{}
2 years ago
ctx, cls := context.WithTimeout(context.Background(), time.Duration(200*time.Millisecond))
defer cls()
2 years ago
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(*body))
resp, err := c.Do(req)
// not responding or timeout
if err != nil {
2 years ago
log.Println("Error when making request", err)
return
}
defer resp.Body.Close()
2 years ago
// if response not good
if resp.StatusCode != 200 {
log.Println("Error: status code", resp.StatusCode)
2 years ago
return
}
b, _ := ioutil.ReadAll(resp.Body)
2 years ago
if err := json.Unmarshal(b, &pResp); err != nil {
log.Println("Error: response unmarshalling", err)
return
}
2 years ago
response <- pResp.Imp
}
// Create requset body based in incoming reqest `ir` and return
// `OutgoingRequest` as []byte from marshaled JSON
func constructPartnersRequestBody(ir *req_types.IncomingRequest) []byte {
var outReqBody req_types.OutgoingRequest
var imps []req_types.Imp
for _, tile := range ir.Tiles {
minheight := uint(math.Floor(float64(tile.Width) * tile.Ratio))
imps = append(imps, req_types.Imp{
Id: tile.Id,
Minwidth: tile.Width,
Minheight: minheight})
}
outReqBody.Id = *ir.Id
outReqBody.Imp = imps
outReqBody.Context = ir.Context
t, _ := json.Marshal(outReqBody)
return t
}