Skip to content

Instantly share code, notes, and snippets.

@yinhm
Created March 19, 2015 08:01
Show Gist options
  • Save yinhm/8fffe49f0dc637d8fef3 to your computer and use it in GitHub Desktop.
Save yinhm/8fffe49f0dc637d8fef3 to your computer and use it in GitHub Desktop.
mandible media server naive testcase
package media
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
)
const (
apiURL = "http://127.0.0.1:8902"
)
type Client struct {
client *http.Client
BaseURL *url.URL
}
type thumbConfig struct {
Width int `json:"width"`
Height int `json:"height"`
Shape string `json:"shape"`
}
type Response struct {
Data struct {
Width int `json:"width"`
Height int `json:"height"`
Link string `json:"link"`
Mime string `json:"mime"`
Name string `json:"name"`
Size int `json:"size"`
Thumbs map[string]string `json:"thumbs"`
}
Status int `json:"status"`
Success bool `json:"success"`
}
func NewClient() *Client {
httpClient := http.DefaultClient
baseURL, err := url.Parse(apiURL)
if err != nil {
panic("Error media server address.")
}
return &Client{
client: httpClient,
BaseURL: baseURL,
}
}
func (c *Client) PostUrl(imageUrl string) (*Response, error) {
thumbs := map[string]thumbConfig{
"small": thumbConfig{
Width: 175,
Height: 175,
Shape: "thumb",
},
"large": thumbConfig{
Width: 1600,
Height: 1600,
Shape: "thumb",
},
}
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
enc.Encode(thumbs)
// data := map[string]interface{}{
// "image": imageUrl,
// "thumbs": thumbs,
// }
data := url.Values{
"image": {imageUrl},
"thumbs": {buf.String()},
}
reqUrl := c.BaseURL.String() + "/url"
//r, err := http.Post(reqUrl, "application/json", data)
r, err := http.PostForm(reqUrl, data)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
resp := new(Response)
if err = json.Unmarshal(body, resp); err != nil {
return nil, err
}
return resp, nil
}
package media
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestMediaFromUrl(t *testing.T) {
Convey("Fetch media from url", t, func() {
client := NewClient()
url := "https://www.google.com/images/srpr/logo11w.png"
resp, err := client.PostUrl(url)
if err != nil {
t.Fatal(err)
}
So(resp.Success, ShouldEqual, true)
So(resp.Data.Height, ShouldEqual, 190)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment