find-stone-beer / files / seller.go
seller.go
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "strconv" |
| 7 | |
| 8 | "github.com/jftuga/geodist" |
| 9 | ) |
| 10 | |
| 11 | type Seller struct { |
| 12 | Nid string |
| 13 | Title string |
| 14 | Addr string |
| 15 | Addr1 string |
| 16 | Addr2 string |
| 17 | Distance float64 |
| 18 | Phone string |
| 19 | Cot string |
| 20 | Pos geodist.Coord |
| 21 | // Lat float64 |
| 22 | // Lng float64 |
| 23 | LocationCategory string |
| 24 | AllBrands []string |
| 25 | AllPackages []string |
| 26 | } |
| 27 | |
| 28 | func (s *Seller) UnmarshalJSON(data []byte) error { |
| 29 | seller := &struct { |
| 30 | Nid string `json:"nid"` |
| 31 | Title string `json:"title"` |
| 32 | Addr string `json:"addr"` |
| 33 | Addr1 string `json:"addr_1"` |
| 34 | Addr2 string `json:"addr_2"` |
| 35 | Distance string `json:"distance"` |
| 36 | Phone string `json:"phone"` |
| 37 | Cot string `json:"cot"` |
| 38 | Lat string `json:"lat"` |
| 39 | Lng string `json:"lng"` |
| 40 | LocationCategory string `json:"location_category"` |
| 41 | AllBrands []string `json:"all_brands"` |
| 42 | AllPackages []string `json:"all_packages"` |
| 43 | }{} |
| 44 | json.Unmarshal(data, &seller) |
| 45 | |
| 46 | newSeller := Seller{ |
| 47 | Nid: seller.Nid, |
| 48 | Title: seller.Title, |
| 49 | Addr: seller.Addr, |
| 50 | Addr1: seller.Addr1, |
| 51 | Addr2: seller.Addr2, |
| 52 | Phone: seller.Phone, |
| 53 | Cot: seller.Cot, |
| 54 | LocationCategory: seller.LocationCategory, |
| 55 | AllBrands: seller.AllBrands, |
| 56 | AllPackages: seller.AllPackages, |
| 57 | } |
| 58 | |
| 59 | if len(seller.Distance) != 0 { |
| 60 | dist, err := strconv.ParseFloat(seller.Distance, 64) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | newSeller.Distance = dist |
| 65 | } |
| 66 | |
| 67 | if len(seller.Lat) > 0 && len(seller.Lng) > 0 { |
| 68 | lat, err := strconv.ParseFloat(seller.Lat, 64) |
| 69 | if err != nil { |
| 70 | return err |
| 71 | } |
| 72 | |
| 73 | lng, err := strconv.ParseFloat(seller.Lng, 64) |
| 74 | if err != nil { |
| 75 | return err |
| 76 | } |
| 77 | |
| 78 | newSeller.Pos = geodist.Coord{Lat: lat, Lon: lng} |
| 79 | } |
| 80 | |
| 81 | *s = newSeller |
| 82 | return nil |
| 83 | } |
| 84 | |
| 85 | func GetSellers(coords geodist.Coord) ([]Seller, error) { |
| 86 | lat := coords.Lat |
| 87 | latInt := int(lat) |
| 88 | lon := coords.Lon |
| 89 | lonInt := int(lon) |
| 90 | url := fmt.Sprintf("https://find.stonebrewing.com/api/search/%f,%f/%d,%d", lat, lon, latInt, lonInt) |
| 91 | bytes, err := getCachedUrl(url, "find-stone-beer", "2006-01-02") |
| 92 | if err != nil { |
| 93 | return nil, err |
| 94 | } |
| 95 | |
| 96 | var sellers []Seller |
| 97 | err = json.Unmarshal(bytes, &sellers) |
| 98 | if err != nil { |
| 99 | return nil, fmt.Errorf("error unmarshalling json '%s': %w", string(bytes), err) |
| 100 | } |
| 101 | return sellers, nil |
| 102 | } |