71 lines
1.2 KiB
Go
71 lines
1.2 KiB
Go
package mclookup
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// APIResponse is used to parse the data from the api.
|
|
type APIResponse struct {
|
|
Data struct {
|
|
Player APIPlayerData `json:"player"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
// APIPlayerData is used to store player object.
|
|
type APIPlayerData struct {
|
|
Username string `json:"username"`
|
|
ID string `json:"id"`
|
|
Avatar string `json:"avatar"`
|
|
}
|
|
|
|
// LookupPlayer is the main method used to lookup a player
|
|
func LookupPlayer(uuid string) (*APIResponse, error) {
|
|
var err error
|
|
data := &APIResponse{}
|
|
|
|
bytes, err := request("https://playerdb.co/api/player/minecraft/" + uuid)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = json.Unmarshal(bytes, data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return data, err
|
|
}
|
|
|
|
func request(url string) ([]byte, error) {
|
|
var body []byte
|
|
|
|
mclookupClient := http.Client{
|
|
Timeout: time.Second * 2,
|
|
}
|
|
|
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return body, err
|
|
}
|
|
|
|
req.Header.Set("User-Agent", "mclookup")
|
|
|
|
res, err := mclookupClient.Do(req)
|
|
if err != nil {
|
|
return body, err
|
|
}
|
|
|
|
if res.Body != nil {
|
|
defer res.Body.Close()
|
|
}
|
|
|
|
body, err = ioutil.ReadAll(res.Body)
|
|
if err != nil {
|
|
return body, err
|
|
}
|
|
return body, nil
|
|
}
|