travebing/backend/controller/geo/geo.go

43 lines
713 B
Go

package geo
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"pkg.bing89.com/travebing/config"
)
type ctrl struct {
cfg *config.Geo
}
func New(cfg *config.Geo)Controller{
return &ctrl{
cfg: cfg,
}
}
func (c *ctrl)Address(lon, lat float32)(string, error){
url := fmt.Sprintf("%s?key=%s&location=%6f,%6f", c.cfg.URL, c.cfg.Key, lon, lat)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
ret := &geoResponse{}
err = json.Unmarshal(data, ret)
if err != nil {
return "", err
}
if ret.Status != "1" {
return "", errors.New(ret.Info)
}
return ret.RegeoCode.Address, nil
}