Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created January 17, 2023 21:59
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/ce2ab0eb4cd7597812826c5410eaabb1 to your computer and use it in GitHub Desktop.
Save mdwhatcott/ce2ab0eb4cd7597812826c5410eaabb1 to your computer and use it in GitHub Desktop.
A simple http get example, using the Smarty US Street Address API (but everything is in the main function)
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
)
func main() {
type Address struct {
DeliveryLine1 string `json:"delivery_line_1"`
DeliveryLine2 string `json:"delivery_line_2"`
LastLine string `json:"last_line"`
}
var (
smartyAuthID = os.Getenv("SMARTY_AUTH_ID")
smartyAuthToken = os.Getenv("SMARTY_AUTH_TOKEN")
)
inputs := [][]string{
{"3214 N University Ave", "Provo", "UT"},
{"2335 S State St", "Provo", "UT"},
// more here?
}
for _, record := range inputs {
request, err := http.NewRequest("GET", "https://us-street.api.smartystreets.com/street-address", 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)
}
var validated []Address
err = json.NewDecoder(response.Body).Decode(&validated)
if err != nil {
log.Panicln("Failed to decode http response body:", err)
}
err = response.Body.Close()
if err != nil {
log.Panicln("Failed to close http response body:", err)
}
for _, address := range validated {
if strings.Contains(address.LastLine, "84604") {
fmt.Printf(strings.ReplaceAll(
fmt.Sprintf("%s\n%s\n%s", address.DeliveryLine1, address.DeliveryLine2, address.LastLine),
"\n\n", "\n"))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment