mirror of
https://github.com/writeas/go-writeas.git
synced 2025-07-27 19:18:35 +00:00
Add basic API with post fetching
This commit is contained in:
parent
33048be30d
commit
7c968a435b
25
post/post.go
Normal file
25
post/post.go
Normal 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
post/post_test.go
Normal file
14
post/post_test.go
Normal 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
writeas.go
Normal file
48
writeas.go
Normal 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…
Reference in New Issue
Block a user