template.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package storageos
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "net/http"
  7. "strconv"
  8. "github.com/storageos/go-api/types"
  9. )
  10. var (
  11. // TemplateAPIPrefix is a partial path to the HTTP endpoint.
  12. TemplateAPIPrefix = "/templates"
  13. // ErrNoSuchTemplate is the error returned when the template does not exist.
  14. ErrNoSuchTemplate = errors.New("no such template")
  15. // ErrTemplateInUse is the error returned when the template requested to be removed is still in use.
  16. ErrTemplateInUse = errors.New("template in use and cannot be removed")
  17. )
  18. // TemplateList returns the list of available templates.
  19. func (c *Client) TemplateList(opts types.ListOptions) ([]types.Template, error) {
  20. path := TemplateAPIPrefix + "?" + queryString(opts)
  21. resp, err := c.do("GET", path, doOptions{context: opts.Context})
  22. if err != nil {
  23. return nil, err
  24. }
  25. defer resp.Body.Close()
  26. var templates []types.Template
  27. if err := json.NewDecoder(resp.Body).Decode(&templates); err != nil {
  28. return nil, err
  29. }
  30. return templates, nil
  31. }
  32. // TemplateCreate creates a template on the server and returns the new object.
  33. func (c *Client) TemplateCreate(opts types.TemplateCreateOptions) (string, error) {
  34. resp, err := c.do("POST", TemplateAPIPrefix, doOptions{
  35. data: opts,
  36. context: opts.Context,
  37. })
  38. if err != nil {
  39. return "", err
  40. }
  41. defer resp.Body.Close()
  42. out, err := ioutil.ReadAll(resp.Body)
  43. if err != nil {
  44. return "", err
  45. }
  46. return strconv.Unquote(string(out))
  47. }
  48. // Template returns a template by its reference.
  49. func (c *Client) Template(ref string) (*types.Template, error) {
  50. resp, err := c.do("GET", TemplateAPIPrefix+"/"+ref, doOptions{})
  51. if err != nil {
  52. if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound {
  53. return nil, ErrNoSuchTemplate
  54. }
  55. return nil, err
  56. }
  57. defer resp.Body.Close()
  58. var template types.Template
  59. if err := json.NewDecoder(resp.Body).Decode(&template); err != nil {
  60. return nil, err
  61. }
  62. return &template, nil
  63. }
  64. // TemplateDelete removes a template by its reference.
  65. func (c *Client) TemplateDelete(ref string) error {
  66. resp, err := c.do("DELETE", TemplateAPIPrefix+"/"+ref, doOptions{})
  67. if err != nil {
  68. if e, ok := err.(*Error); ok {
  69. if e.Status == http.StatusNotFound {
  70. return ErrNoSuchTemplate
  71. }
  72. if e.Status == http.StatusConflict {
  73. return ErrTemplateInUse
  74. }
  75. }
  76. return nil
  77. }
  78. defer resp.Body.Close()
  79. return nil
  80. }