Browse Source

Add basic API with post fetching

pull/6/head
Matt Baer 8 years ago
parent
commit
7c968a435b
3 changed files with 87 additions and 0 deletions
  1. +25
    -0
      post/post.go
  2. +14
    -0
      post/post_test.go
  3. +48
    -0
      writeas.go

+ 25
- 0
post/post.go View File

@@ -0,0 +1,25 @@
package post

import (
"fmt"
writeas "github.com/writeas/writeas-go"
"net/http"
)

func Get(id string) string {
status, body, err := getAPI().Call("GET", fmt.Sprintf("/%s", id))

if status == http.StatusOK {
return body
} else if status == http.StatusNotFound {
return "Post not found."
} else if status == http.StatusGone {
return "Post unpublished."
} else {
return fmt.Sprintf("Problem getting post: %s. %v\n", status, err)
}
}

func getAPI() *writeas.API {
return writeas.GetAPI()
}

+ 14
- 0
post/post_test.go View File

@@ -0,0 +1,14 @@
package post

import (
"testing"

"strings"
)

func TestGet(t *testing.T) {
res := Get("3psnxyhqxy3hq")
if !strings.HasPrefix(res, " Write.as Blog") {
t.Errorf("Unexpected fetch results: %s\n", res)
}
}

+ 48
- 0
writeas.go View File

@@ -0,0 +1,48 @@
package writeas

import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
)

const (
apiURL = "http://i.write.as"
)

type API struct {
BaseURL string
}

// defaultHTTPTimeout is the default http.Client timeout.
const defaultHTTPTimeout = 10 * time.Second

var httpClient = &http.Client{Timeout: defaultHTTPTimeout}

func GetAPI() *API {
return &API{apiURL}
}

func (a API) Call(method, path string) (int, string, error) {
if method != "GET" && method != "HEAD" {
return 0, "", errors.New(fmt.Sprintf("Method %s not currently supported by library (only HEAD and GET).\n", method))
}

r, _ := http.NewRequest(method, fmt.Sprintf("%s%s", a.BaseURL, path), nil)
r.Header.Add("User-Agent", "writeas-go v1")

resp, err := httpClient.Do(r)
if err != nil {
return 0, "", err
}
defer resp.Body.Close()

content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, "", err
}

return resp.StatusCode, string(content), nil
}

Loading…
Cancel
Save