shad-go/coverme/client/client.go

71 lines
1.5 KiB
Go
Raw Normal View History

2020-03-19 21:57:07 +00:00
// +build !change
package client
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
2020-03-19 22:02:50 +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
}