wip (apply)
This commit is contained in:
71
pkg/client/client.go
Normal file
71
pkg/client/client.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mirror-sync/pkg/project"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type (
|
||||
Client struct {
|
||||
url string
|
||||
}
|
||||
|
||||
SimpleError struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
)
|
||||
|
||||
func New(url string) *Client {
|
||||
return &Client{
|
||||
url: url,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Apply(pr project.Project) error {
|
||||
url, err := url.JoinPath(c.url, "api", "v1", "projects", pr.Name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to make url: %s", err)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(pr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal project data: %s", err)
|
||||
}
|
||||
|
||||
r := bytes.NewReader(data)
|
||||
|
||||
req, err := http.NewRequest("POST", url, r)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate http request: %s", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var cli http.Client
|
||||
res, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to send the request to the server: %s", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != 201 {
|
||||
return fmt.Errorf("failed to send the request to the server: %s: %s", res.Status, toError(res.Body))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func toError(body io.ReadCloser) error {
|
||||
var msg SimpleError
|
||||
|
||||
d := json.NewDecoder(body)
|
||||
if err := d.Decode(&msg); err != nil {
|
||||
return fmt.Errorf("failed to decode error message: %s", err)
|
||||
}
|
||||
|
||||
return fmt.Errorf("%s", msg.Message)
|
||||
}
|
||||
Reference in New Issue
Block a user