gpm/go-gpm/package.go

125 lines
2.6 KiB
Go
Raw Normal View History

package gpm
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
// Package is a gpm package
type Package struct {
Name string `json:"name"`
Import string `json:"import"`
}
// Info is gpm information, such as version and list of packages
type Info struct {
Version string `json:"version"`
NumPackages int `json:"num_packages"`
Packages []Package `json:"packages"`
}
// Info gets Info from a gpm server
func (c *Client) Info(ctx context.Context) (Info, error) {
var info Info
resp, err := c.crud(ctx, Package{}, http.MethodGet)
if err != nil {
return info, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return info, fmt.Errorf("could not get info: %s", resp.Status)
}
if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
return info, err
}
return info, nil
}
// Add adds a new Package to a gpm server
func (c *Client) Add(ctx context.Context, pkg Package) error {
resp, err := c.crud(ctx, pkg, http.MethodPost)
if err != nil {
return err
}
if resp.StatusCode != http.StatusCreated {
return fmt.Errorf("could not add package: %s", resp.Status)
}
return nil
}
// Update updates a Package on a gpm server
func (c *Client) Update(ctx context.Context, pkg Package) error {
resp, err := c.crud(ctx, pkg, http.MethodPatch)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("could not update package: %s", resp.Status)
}
return nil
}
// Remove removes a Package from a gpm server
func (c *Client) Remove(ctx context.Context, pkg Package) error {
resp, err := c.crud(ctx, pkg, http.MethodDelete)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("could not remove package: %s", resp.Status)
}
return nil
}
// Get gets a Package from a server
func (c *Client) Get(ctx context.Context, name string) (Package, error) {
var pkg Package
uri := fmt.Sprintf("%s/%s", c.server, name)
req, err := c.newRequest(ctx, http.MethodGet, uri, nil)
if err != nil {
return pkg, err
}
resp, err := c.http.Do(req)
if err != nil {
return pkg, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return pkg, fmt.Errorf("package not found for %s", name)
}
if err := json.NewDecoder(resp.Body).Decode(&pkg); err != nil {
return pkg, err
}
return pkg, nil
}
func (c *Client) crud(ctx context.Context, pkg Package, method string) (*http.Response, error) {
payload, err := json.Marshal(pkg)
if err != nil {
return nil, err
}
req, err := c.newRequest(ctx, method, c.server, bytes.NewReader(payload))
if err != nil {
return nil, err
}
return c.http.Do(req)
}