gojang/username_uuid.go
jolheiser 77a00dbb66
Add rate limit and refactor. Add example.
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2020-07-02 12:15:18 -05:00

66 lines
1.4 KiB
Go

package gojang
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type UsernameResponse struct {
UUID string `json:"id"`
CurrentUsername string `json:"name"`
Legacy bool `json:"legacy"`
Demo bool `json:"demo"`
}
// Username -> UUID (+ profile)
func (g *Gojang) Profile(username string, at time.Time) (UsernameResponse, error) {
var usernameResponse UsernameResponse
endpoint := fmt.Sprintf("%s/users/profiles/minecraft/%s?at=%d", API, username, at.Unix())
resp, err := g.get(endpoint)
if err != nil {
return usernameResponse, err
}
if resp.StatusCode == http.StatusNoContent {
return usernameResponse, PlayerNotFoundError{
Username: username,
At: at,
}
}
if resp.StatusCode == http.StatusBadRequest {
return usernameResponse, errors.New("invalid timestamp")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return usernameResponse, err
}
defer resp.Body.Close()
if err := json.Unmarshal(body, &usernameResponse); err != nil {
return usernameResponse, fmt.Errorf("could not read JSON response: %v", err)
}
return usernameResponse, nil
}
type PlayerNotFoundError struct {
Username string
At time.Time
}
func (p PlayerNotFoundError) Error() string {
return fmt.Sprintf("player not found for user name %s at %s", p.Username, p.At)
}
func IsPlayerNotFoundError(err error) bool {
_, ok := err.(PlayerNotFoundError)
return ok
}