package httpClient import ( "TaskApp/models" "encoding/json" "fmt" "io" "log" "net/http" "time" ) type Client interface { GetPerson(id int) (*models.Person, error) TestConnection() (bool, error) } type client struct { BaseUrl string Timeout time.Duration } func (c *client) TestConnection() (bool, error) { client := &http.Client{Timeout: c.Timeout} url := fmt.Sprintf("%s/", c.BaseUrl) resp, err := client.Get(url) if err != nil { return false, err } defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { return } }(resp.Body) if resp.StatusCode != http.StatusOK { return false, fmt.Errorf("bad status code: %d", resp.StatusCode) } return true, nil } func (c *client) GetPerson(id int) (*models.Person, error) { client := &http.Client{Timeout: c.Timeout * time.Second} url := fmt.Sprintf("%s/%d", c.BaseUrl, id) resp, err := client.Get(url) if err != nil { return nil, err } defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { } }(resp.Body) body, _ := io.ReadAll(resp.Body) var person models.Person if err := json.Unmarshal(body, &person); err != nil { log.Printf("Unmarshal error: %s", err) return nil, err } return &person, nil } func NewClient(baseUrl string, timeout time.Duration) Client { return &client{BaseUrl: baseUrl, Timeout: timeout} }