package main

import (
	"context"
	"fmt"
	toxiproxy "github.com/Shopify/toxiproxy/v2/client"
	"io"
	"log"
	"net/http"
	"time"
)

func main() {

	client := toxiproxy.NewClient("localhost:8474")
	proxy, err := client.CreateProxy("booking-fellow", "localhost:0", "localhost:8080")
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		fmt.Println("delete")
		proxy.Delete()
	}()
	proxy.AddToxic("booking-fellow", "timeout", "", 1, toxiproxy.Attributes{
		"timeout": 0,
	})

	url := fmt.Sprintf("http://%s/trainings", proxy.Listen)

	var response *http.Response
	if false {
		response, err = http.Get(url)
		if err != nil {
			log.Println(err)
			return
		}
	} else {
		ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
		defer cancel()
		requestWithContext, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
		if err != nil {
			log.Println(err)
			return
		}
		response, err = http.DefaultClient.Do(requestWithContext)
		if err != nil {
			log.Println(err)
			return
		}
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		log.Printf("got status %s. exit", response.Status)
		return
	}

	all, err := io.ReadAll(response.Body)
	if err != nil {
		log.Println(err)
		return
	}

	log.Println(string(all))

}
