diff --git a/post.go b/post.go index 22b8630..c4d4996 100644 --- a/post.go +++ b/post.go @@ -28,8 +28,8 @@ type ( Collection *Collection `json:"collection,omitempty"` } - // SubmittedPost represents a new post for publishing or updating. - SubmittedPost struct { + // PostParams holds values for creating or updating a post. + PostParams struct { Title string `json:"title"` Content string `json:"body"` Font string `json:"font"` @@ -64,3 +64,26 @@ func (c *Client) GetPost(id string) (*Post, error) { } return p, nil } + +func (c *Client) CreatePost(sp *PostParams) (*Post, error) { + p := &Post{} + env, err := c.post("/posts", sp, p) + if err != nil { + return nil, err + } + + var ok bool + if p, ok = env.Data.(*Post); !ok { + return nil, fmt.Errorf("Wrong data returned from API.") + } + + status := env.Code + if status == http.StatusCreated { + return p, nil + } else if status == http.StatusBadRequest { + return nil, fmt.Errorf("Bad request: %s", env.ErrorMessage) + } else { + return nil, fmt.Errorf("Problem getting post: %s. %v\n", status, err) + } + return p, nil +} diff --git a/post_test.go b/post_test.go index 65ceee2..80a890c 100644 --- a/post_test.go +++ b/post_test.go @@ -6,7 +6,21 @@ import ( "strings" ) -func TestGet(t *testing.T) { +func TestCreatePost(t *testing.T) { + wac := NewClient("") + p, err := wac.CreatePost(&PostParams{ + Title: "Title!", + Content: "This is a post.", + Font: "sans", + }) + if err != nil { + t.Errorf("Post create failed: %v", err) + } else { + t.Logf("Post created: %+v", p) + } +} + +func TestGetPost(t *testing.T) { wac := NewClient("") res, err := wac.GetPost("zekk5r9apum6p") diff --git a/writeas.go b/writeas.go index 6da8793..e6f4f53 100644 --- a/writeas.go +++ b/writeas.go @@ -1,6 +1,7 @@ package writeas import ( + "bytes" "encoding/json" "errors" "fmt" @@ -43,8 +44,10 @@ func (c *Client) get(path string, r interface{}) (*impart.Envelope, error) { return c.request(method, path, nil, r) } -func (c *Client) post(path string, data io.Reader, r interface{}) (*impart.Envelope, error) { - return c.request("POST", path, data, r) +func (c *Client) post(path string, data, r interface{}) (*impart.Envelope, error) { + b := new(bytes.Buffer) + json.NewEncoder(b).Encode(data) + return c.request("POST", path, b, r) } func (c *Client) request(method, path string, data io.Reader, result interface{}) (*impart.Envelope, error) {