Skip to content

Instantly share code, notes, and snippets.

@nehayward
Created March 7, 2019 23:17
Show Gist options
  • Save nehayward/1c1cc007b749c86fc950f6030e755f2e to your computer and use it in GitHub Desktop.
Save nehayward/1c1cc007b749c86fc950f6030e755f2e to your computer and use it in GitHub Desktop.
Find Gif From Google
package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
type Gif struct {
ContentURL string
}
func main() {
fmt.Println("Hello, playground")
url := "http://google.com"
searchTerm := "monkey"
req, _ := newGoogleRequest(url, searchTerm)
lookupGif(req)
}
func lookupGif(req *http.Request) {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
if resp.StatusCode != http.StatusOK {
return
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
var regexFindContent = regexp.MustCompile(`var u=\'.*?(http.*?)\'`)
var regexFindURL = regexp.MustCompile(`http.*\w`)
matches := regexFindContent.FindAllString(string(bodyBytes), -1)
if len(matches) <= 0 {
}
Gifs := make([]Gif, len(matches))
for i, match := range matches {
Gifs[i].ContentURL = regexFindURL.FindString(match)
}
for _, gif := range Gifs {
fmt.Println(gif.ContentURL)
}
}
func newGoogleRequest(url string, searchTerm string) (*http.Request, error) {
url = strings.TrimSuffix(url, "/")
url += "/search?tbm=isch&tbs=itp:animated&q=" + searchTerm
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Versio n/4.0.5 Mobile/8A293 Safari/6531.22.7")
return req, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment