Files
purpleschool/go-demo-5/geo/geo.go
2025-03-24 21:10:02 +03:00

35 lines
530 B
Go

package geo
import (
"encoding/json"
"errors"
"io"
"net/http"
)
type GeoData struct {
City string `json:"city"`
}
func GetMyLocation(city string) (*GeoData, error) {
if city != "" {
return &GeoData{
City: city,
}, nil
}
resp, err := http.Get("https://ipapi.co/json/")
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New("NOT200")
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var geo GeoData
json.Unmarshal(body, &geo)
return &geo, nil
}