diff --git a/post/post.go b/post/post.go new file mode 100644 index 0000000..f2e669c --- /dev/null +++ b/post/post.go @@ -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() +} diff --git a/post/post_test.go b/post/post_test.go new file mode 100644 index 0000000..da2efd5 --- /dev/null +++ b/post/post_test.go @@ -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) + } +} diff --git a/writeas.go b/writeas.go new file mode 100644 index 0000000..fc8d028 --- /dev/null +++ b/writeas.go @@ -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 +}