Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created January 16, 2023 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/e4ef0b8f123e30f573b0f622d81af4d6 to your computer and use it in GitHub Desktop.
Save mdwhatcott/e4ef0b8f123e30f573b0f622d81af4d6 to your computer and use it in GitHub Desktop.
A simple http get example, using the Smarty US Street Address API
package main
import (
"encoding/json"
"fmt"
"log"
"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, err := http.NewRequest(http.MethodGet, smartyAPIURL, nil)
if err != nil {
log.Panicln("Failed to create http request:", err)
}
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, err := http.DefaultClient.Do(request)
if err != nil {
log.Panicln("Failed to send http request:", err)
}
if response.StatusCode != http.StatusOK {
log.Panicln("Non-200 http response status:", response.Status)
}
defer func() {
err := response.Body.Close()
if err != nil {
log.Panicln("Failed to close http response body:", err)
}
}()
err = json.NewDecoder(response.Body).Decode(&results)
if err != nil {
log.Panicln("Failed to decode http response body:", err)
}
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