go-mcstatus/endpoints.go
jolheiser b98e3fd177
Initial commit
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2021-04-05 21:40:59 -05:00

77 lines
1.7 KiB
Go

package mcstatus
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
var baseEndpoint = "https://api.mcsrvstat.us"
// Status returns the full ServerStatus for an address
func (c *Client) Status(ctx context.Context, address string) (ServerStatus, error) {
var status ServerStatus
endpoint := fmt.Sprintf("%s/2/%s", baseEndpoint, address)
req, err := newRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return status, err
}
resp, err := c.http.Do(req)
if err != nil {
return status, err
}
defer resp.Body.Close()
return status, json.NewDecoder(resp.Body).Decode(&status)
}
// Online uses the status endpoint to check for online/offline status
func (c *Client) Online(ctx context.Context, address string) (bool, error) {
endpoint := fmt.Sprintf("%s/simple/%s", baseEndpoint, address)
req, err := newRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return false, err
}
resp, err := c.http.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return true, nil
case http.StatusNotFound:
return false, nil
default:
return false, fmt.Errorf("invalid HTTP response code: %d", resp.StatusCode)
}
}
// Icon returns the server's icon as a 64x64 PNG
func (c *Client) Icon(ctx context.Context, address string) ([]byte, error) {
req, err := newRequest(ctx, http.MethodGet, c.IconURL(address), nil)
if err != nil {
return nil, err
}
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
// IconURL returns a URL suitable for getting the icon of a server
func (c *Client) IconURL(address string) string {
return fmt.Sprintf("%s/icon/%s", baseEndpoint, address)
}