// Package libcapsul provides Capsul operations functionality. package libcapsul import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "time" "github.com/sirupsen/logrus" ) // CapsulCreateResponse is a Capsul creation response payload. type CapsulCreateResponse struct { ID string } // CapsulClient is a Capsul client interface. type CapsulClient struct { InstanceURL string APIToken string } // New creates a new Capsul client. func New(instanceURL, APIToken string) CapsulClient { return CapsulClient{ InstanceURL: instanceURL, APIToken: APIToken, } } // Create creates a new capsul. func (c CapsulClient) Create(capsulName, capsulType, capsulImage string, capsulSSHKeys []string) (CapsulCreateResponse, error) { // yep, the response time is quite slow, something to fix on the Capsul side client := &http.Client{Timeout: 20 * time.Second} capsulCreateURL := fmt.Sprintf("https://%s/api/capsul/create", c.InstanceURL) logrus.Debugf("using '%s' as capsul create url", capsulCreateURL) values := map[string]string{ "name": capsulName, "size": capsulType, "os": capsulImage, } idx := 0 for _, sshKey := range capsulSSHKeys { key := fmt.Sprintf("ssh_key_%v", idx) values[key] = sshKey idx++ } payload, err := json.Marshal(values) if err != nil { return CapsulCreateResponse{}, err } req, err := http.NewRequest("POST", capsulCreateURL, bytes.NewBuffer(payload)) if err != nil { return CapsulCreateResponse{}, err } req.Header = http.Header{ "Content-Type": []string{"application/json"}, "Authorization": []string{c.APIToken}, } res, err := client.Do(req) if err != nil { return CapsulCreateResponse{}, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { body, err := ioutil.ReadAll(res.Body) if err != nil { return CapsulCreateResponse{}, err } return CapsulCreateResponse{}, fmt.Errorf(string(body)) } var resp CapsulCreateResponse if err := json.NewDecoder(res.Body).Decode(&resp); err != nil { return CapsulCreateResponse{}, err } logrus.Debugf("capsul created with ID: '%s'", resp.ID) return resp, nil }