1
0
mirror of https://github.com/jhillyerd/inbucket.git synced 2025-12-18 10:07:02 +00:00

Complete REST client for #43

- Add source, delete and purge
This commit is contained in:
James Hillyerd
2017-01-08 22:11:22 +00:00
parent d8255382da
commit c8fd56ca90
5 changed files with 206 additions and 15 deletions

View File

@@ -1,8 +1,11 @@
package client
import (
"bytes"
"fmt"
"net/http"
"net/url"
"time"
"github.com/jhillyerd/inbucket/rest/model"
)
@@ -21,7 +24,9 @@ func NewV1(baseURL string) (*ClientV1, error) {
}
c := &ClientV1{
restClient{
client: &http.Client{},
client: &http.Client{
Timeout: 30 * time.Second,
},
baseURL: parsedURL,
},
}
@@ -31,13 +36,61 @@ func NewV1(baseURL string) (*ClientV1, error) {
// ListMailbox returns a list of messages for the requested mailbox
func (c *ClientV1) ListMailbox(name string) (headers []*model.JSONMessageHeaderV1, err error) {
uri := "/api/v1/mailbox/" + url.QueryEscape(name)
err = c.doGet(uri, &headers)
err = c.doJSON("GET", uri, &headers)
return
}
// GetMessage returns the message details given a mailbox name and message ID.
func (c *ClientV1) GetMessage(name, id string) (message *model.JSONMessageV1, err error) {
uri := "/api/v1/mailbox/" + url.QueryEscape(name) + "/" + id
err = c.doGet(uri, &message)
err = c.doJSON("GET", uri, &message)
return
}
// GetMessageSource returns the message source given a mailbox name and message ID.
func (c *ClientV1) GetMessageSource(name, id string) (*bytes.Buffer, error) {
uri := "/api/v1/mailbox/" + url.QueryEscape(name) + "/" + id + "/source"
resp, err := c.do("GET", uri)
if err != nil {
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return nil,
fmt.Errorf("Unexpected HTTP response status %v: %s", resp.StatusCode, resp.Status)
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
return buf, err
}
// DeleteMessage deletes a single message given the mailbox name and message ID.
func (c *ClientV1) DeleteMessage(name, id string) error {
uri := "/api/v1/mailbox/" + url.QueryEscape(name) + "/" + id
resp, err := c.do("DELETE", uri)
if err != nil {
return err
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Unexpected HTTP response status %v: %s", resp.StatusCode, resp.Status)
}
return nil
}
// PurgeMailbox deletes all messages in the given mailbox
func (c *ClientV1) PurgeMailbox(name string) error {
uri := "/api/v1/mailbox/" + url.QueryEscape(name)
resp, err := c.do("DELETE", uri)
if err != nil {
return err
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Unexpected HTTP response status %v: %s", resp.StatusCode, resp.Status)
}
return nil
}