-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
69 lines (58 loc) · 1.43 KB
/
main.go
File metadata and controls
69 lines (58 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
)
const (
apiKey = "YOUR_GOOGLE_API_KEY"
searchEngineID = "YOUR_CUSTOM_SEARCH_ENGINE_ID"
)
type SearchResult struct {
Items []struct {
Title string `json:"title"`
Link string `json:"link"`
Image struct {
ContextLink string `json:"contextLink"`
ThumbnailLink string `json:"thumbnailLink"`
} `json:"image"`
} `json:"items"`
}
func searchImages(query string) (*SearchResult, error) {
baseURL := "https://www.googleapis.com/customsearch/v1"
params := url.Values{}
params.Add("key", apiKey)
params.Add("cx", searchEngineID)
params.Add("q", query)
params.Add("searchType", "image")
searchURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())
resp, err := http.Get(searchURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to search: %v", resp.Status)
}
var result SearchResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
if len(os.Args) < 2 {
log.Fatal("Please provide a search query")
}
query := os.Args[1]
result, err := searchImages(query)
if err != nil {
log.Fatalf("Failed to search images: %v", err)
}
for _, item := range result.Items {
fmt.Printf("Title: %s\nLink: %s\nThumbnail: %s\n\n", item.Title, item.Link, item.Image.ThumbnailLink)
}
}