-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
90 lines (69 loc) · 1.48 KB
/
main.go
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
type Product struct {
Product ProductBody
}
type ProductBody struct {
Variants []Variant
}
type Variant struct {
ID uint
Title string
}
var (
client = &http.Client{
Timeout: 30 * time.Second,
}
)
func main() {
if len(os.Args) < 2 {
log.Fatal("Please specify a product url")
}
rawurl := os.Args[1]
url, err := url.Parse(rawurl)
if err != nil && !strings.Contains(url.Path, "products") {
log.Fatalf("URL is not valid - %s: %v\n", rawurl, err)
}
fmt.Println("Getting variants for", url.String())
req, err := http.NewRequest("GET", fmt.Sprintf("%s.json", url.String()), nil)
if err != nil {
log.Fatalf("Failed to create request: %v\n", err)
}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Failed to carry out request: %v\n", err)
}
defer resp.Body.Close()
isShopify := false
for _, cookie := range resp.Cookies() {
if strings.Contains(cookie.Name, "shopify") {
isShopify = true
break;
}
}
if !isShopify {
log.Println("[WARN] Probably not a shopify store")
}
switch resp.StatusCode {
case 200:
var parsedJSON Product
err = json.NewDecoder(resp.Body).Decode(&parsedJSON)
if err != nil {
log.Fatalf("Could not decode JSON: %v\n", err)
}
for _, product := range parsedJSON.Product.Variants {
fmt.Printf("%v - %s\n", product.ID, product.Title)
}
default:
log.Fatalf("Invalid status code: %v", resp.StatusCode)
}
}