go/pastee.go

57 lines
1.0 KiB
Go
Raw Normal View History

2017-06-08 05:40:35 +00:00
package pastee
import (
"net/http"
"io"
"encoding/json"
"bytes"
)
func New(key string) *Pastee {
return &Pastee{ApiKey: key, Base: "https://api.paste.ee/v1", Client: &http.Client{}}
}
func (p *Pastee) Submit(paste *Paste) (*PasteResponse, error) {
body, err := json.Marshal(paste)
if err != nil {
return nil, err
}
req, err := p.newRequest("POST", "pastes", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Length", len(body))
res, err := p.Client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var response PasteResponse
if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
return nil, err
}
return &response, nil
}
func (p *Pastee) newRequest(method, path string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, p.Base + path, body)
if err != nil {
return nil, err
}
req.Header.Set("X-Auth-Token", p.ApiKey)
return req, nil
}