parcoursmob/handlers/api/geo.go

55 lines
961 B
Go
Executable File

package api
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
func (h *APIHandler) GeoAutocomplete(w http.ResponseWriter, r *http.Request) {
pelias := h.config.GetString("geo.pelias.url")
t, ok := r.URL.Query()["text"]
if !ok || len(t[0]) < 1 {
w.WriteHeader(http.StatusBadRequest)
return
}
text := t[0]
resp, err := http.Get(fmt.Sprintf("%s/autocomplete?text=%s", pelias, text))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
var response map[string]any
jsonErr := json.Unmarshal(body, &response)
if jsonErr != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
j, err := json.Marshal(response["features"])
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}