Created
January 17, 2023 22:22
-
-
Save mdwhatcott/3c3f145fc4084fe971eb72111a5574f0 to your computer and use it in GitHub Desktop.
A simple http get example, using the Smarty US Street Address API (but no error handling or deferred functions)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"os" | |
"strings" | |
) | |
func main() { | |
inputs := [][]string{ | |
{"3214 N University Ave", "Provo", "UT"}, | |
{"2335 S State St", "Provo", "UT"}, | |
// more here? | |
} | |
for _, address := range validateAddresses("84604", inputs) { | |
fmt.Println(address.String()) | |
} | |
} | |
func validateAddresses(targetZIPCode string, records [][]string) (results []Address) { | |
for _, record := range records { | |
for _, candidate := range validateAddress(record) { | |
if strings.Contains(candidate.LastLine, targetZIPCode) { | |
results = append(results, candidate) | |
} | |
} | |
} | |
return results | |
} | |
func validateAddress(record []string) (results []Address) { | |
request, _ := http.NewRequest("GET", smartyAPIURL, nil) | |
params := request.URL.Query() | |
params.Set("auth-id", smartyAuthID) | |
params.Set("auth-token", smartyAuthToken) | |
params.Set("street", record[0]) | |
params.Set("city", record[1]) | |
params.Set("state", record[2]) | |
request.URL.RawQuery = params.Encode() | |
response, _ := http.DefaultClient.Do(request) | |
_ = json.NewDecoder(response.Body).Decode(&results) | |
_ = response.Body.Close() | |
return results | |
} | |
var ( | |
smartyAPIURL = "https://us-street.api.smartystreets.com/street-address" | |
smartyAuthID = os.Getenv("SMARTY_AUTH_ID") | |
smartyAuthToken = os.Getenv("SMARTY_AUTH_TOKEN") | |
) | |
type Address struct { | |
DeliveryLine1 string `json:"delivery_line_1"` | |
DeliveryLine2 string `json:"delivery_line_2"` | |
LastLine string `json:"last_line"` | |
} | |
func (this Address) String() string { | |
return strings.ReplaceAll( | |
fmt.Sprintf("%s\n%s\n%s", this.DeliveryLine1, this.DeliveryLine2, this.LastLine), | |
"\n\n", "\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment