diff options
author | Kevin Chabowski <kevin@kch42.de> | 2014-05-01 14:28:28 +0200 |
---|---|---|
committer | Kevin Chabowski <kevin@kch42.de> | 2014-05-01 14:33:15 +0200 |
commit | a1b3afb58145cfcda6b206bcbab833fafbc7c55d (patch) | |
tree | f68aa82ba5890c7c9c52602276540db566dfb177 /earthporn.go | |
parent | 901d29509eb759426671ca2766c98c657eb46cd6 (diff) | |
download | startpage-a1b3afb58145cfcda6b206bcbab833fafbc7c55d.tar.gz startpage-a1b3afb58145cfcda6b206bcbab833fafbc7c55d.tar.bz2 startpage-a1b3afb58145cfcda6b206bcbab833fafbc7c55d.zip |
Image is now stored in memory (speedup).
Diffstat (limited to 'earthporn.go')
-rw-r--r-- | earthporn.go | 31 |
1 files changed, 26 insertions, 5 deletions
diff --git a/earthporn.go b/earthporn.go index 9edb837..a7800ef 100644 --- a/earthporn.go +++ b/earthporn.go @@ -1,8 +1,11 @@ package main import ( + "bytes" "encoding/json" "errors" + "io" + "log" "mime" "net/http" "strings" @@ -21,6 +24,8 @@ type EarthPorn struct { URL string `json:"url,omitempty"` Permalink string `json:"permalink"` Domain string `json:"domain"` + data []byte + mediatype string } const earthPornURL = "http://www.reddit.com/r/EarthPorn.json" @@ -49,19 +54,19 @@ func GetEarthPorn() (EarthPorn, error) { continue } - if (&p).getImageURL() { - return p, nil + if p.fetch() { + return *p, nil } } return EarthPorn{}, errors.New("Could not get EarthPorn: No image could be extracted") } -func (p *EarthPorn) getImageURL() bool { +func (p *EarthPorn) fetch() bool { // TODO: We can do further processing here (e.g. if we get a link to flickr, extract the image). // For now, we will simply test, if the URL points to an image. - resp, err := http.Head(p.URL) + resp, err := http.Get(p.URL) if err != nil { return false } @@ -69,12 +74,28 @@ func (p *EarthPorn) getImageURL() bool { t := resp.Header.Get("Content-Type") if t == "" { + log.Printf("could not get image of %s: no Content-Type", p.Permalink) return false } mt, _, err := mime.ParseMediaType(t) if err != nil { + log.Printf("could not get image of %s: %s", p.Permalink, err) return false } - return (strings.Split(mt, "/")[0] == "image") + if strings.Split(mt, "/")[0] != "image" { + log.Printf("could not get image of %s: not an image", p.Permalink) + return false + } + + buf := new(bytes.Buffer) + if _, err := io.Copy(buf, resp.Body); err != nil { + log.Printf("could not get image of %s: %s", p.Permalink, err) + return false + } + + p.mediatype = t + p.data = buf.Bytes() + return true +} } |