65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/caarlos0/env"
|
|
"googlemaps.github.io/maps"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
type config struct {
|
|
MapsApiKey string `env:"MAPS_API_KEY"`
|
|
}
|
|
|
|
type location struct {
|
|
Lat float64 `json:"lat"`
|
|
Long float64 `json:"long"`
|
|
}
|
|
|
|
func main() {
|
|
cfg := config{}
|
|
err := env.Parse(&cfg)
|
|
if err != nil {
|
|
fmt.Printf("%+v\n", err)
|
|
}
|
|
fmt.Printf("%+v\n", cfg)
|
|
|
|
client, err := maps.NewClient(maps.WithAPIKey(cfg.MapsApiKey))
|
|
if err != nil {
|
|
log.Fatalf("fatal error: %s", err)
|
|
}
|
|
|
|
http.HandleFunc("/latlong/", makeHandler(handleLatLongRequest, client))
|
|
log.Fatal(http.ListenAndServe(":8000", nil))
|
|
}
|
|
|
|
func makeHandler(fn func(http.ResponseWriter, *http.Request, *maps.Client), client *maps.Client) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
fn(w, r, client)
|
|
}
|
|
}
|
|
func handleLatLongRequest(w http.ResponseWriter, r *http.Request, client *maps.Client) {
|
|
req := &maps.GeocodingRequest{
|
|
Address: r.URL.Path[len("/latlong/"):],
|
|
}
|
|
if result, err := client.Geocode(context.Background(), req); err != nil {
|
|
log.Fatalf("fatal error: %s", err)
|
|
w.WriteHeader(400)
|
|
} else {
|
|
if len(result) > 0 {
|
|
l := location{
|
|
Lat: result[0].Geometry.Location.Lat,
|
|
Long: result[0].Geometry.Location.Lng,
|
|
}
|
|
if response, err := json.Marshal(l); err != nil {
|
|
log.Fatalf("fatal error: %s", err)
|
|
w.WriteHeader(404)
|
|
} else {
|
|
_, _ = w.Write(response)
|
|
}
|
|
}
|
|
}
|
|
} |