2022-02-10 22:06:57 +00:00
|
|
|
//go:build !change
|
2020-03-19 21:57:07 +00:00
|
|
|
|
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2024-06-05 17:36:34 +00:00
|
|
|
"gitlab.com/slon/shad-go/coverme/models"
|
2020-03-19 21:57:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Client struct {
|
|
|
|
addr string
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(addr string) *Client {
|
|
|
|
return &Client{addr: addr}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Add(r *models.AddRequest) (*models.Todo, error) {
|
|
|
|
data, _ := json.Marshal(r)
|
|
|
|
|
2020-03-21 23:52:15 +00:00
|
|
|
resp, err := http.Post(c.addr+"/todo/create", "application/json", bytes.NewReader(data))
|
2020-03-19 21:57:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusCreated {
|
|
|
|
return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
var todo *models.Todo
|
|
|
|
err = json.NewDecoder(resp.Body).Decode(&todo)
|
|
|
|
return todo, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Get(id models.ID) (*models.Todo, error) {
|
|
|
|
resp, err := http.Get(c.addr + fmt.Sprintf("/todo/%d", id))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
var todo *models.Todo
|
|
|
|
err = json.NewDecoder(resp.Body).Decode(&todo)
|
|
|
|
return todo, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) List() ([]*models.Todo, error) {
|
|
|
|
resp, err := http.Get(c.addr + "/todo")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
var todos []*models.Todo
|
|
|
|
err = json.NewDecoder(resp.Body).Decode(&todos)
|
|
|
|
return todos, err
|
|
|
|
}
|
2022-03-24 15:48:48 +00:00
|
|
|
|
|
|
|
func (c *Client) Finish(id models.ID) error {
|
|
|
|
u := fmt.Sprintf("%s/todo/%d/finish", c.addr, id)
|
|
|
|
|
|
|
|
resp, err := http.Post(u, "application/json", nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return fmt.Errorf("unexpected status code %d", resp.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|