1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-04 22:14:30 +00:00
arikawa/api/api.go

59 lines
1.2 KiB
Go
Raw Normal View History

2020-01-02 05:39:52 +00:00
package api
import (
"net/http"
2020-01-08 18:43:15 +00:00
"github.com/diamondburned/arikawa/api/rate"
"github.com/diamondburned/arikawa/httputil"
2020-01-02 05:39:52 +00:00
)
const (
BaseEndpoint = "https://discordapp.com/api"
APIVersion = "6"
Endpoint = BaseEndpoint + "/v" + APIVersion + "/"
EndpointGateway = Endpoint + "gateway"
EndpointGatewayBot = EndpointGateway + "/bot"
EndpointWebhooks = Endpoint + "webhooks/"
)
var UserAgent = "DiscordBot (https://github.com/diamondburned/arikawa, v0.0.1)"
type Client struct {
httputil.Client
2020-01-08 18:43:15 +00:00
Limiter *rate.Limiter
2020-01-02 05:39:52 +00:00
Token string
}
func NewClient(token string) *Client {
cli := &Client{
2020-01-08 18:43:15 +00:00
Client: httputil.NewClient(),
Limiter: rate.NewLimiter(),
Token: token,
2020-01-02 05:39:52 +00:00
}
tw := httputil.NewTransportWrapper()
tw.Pre = func(r *http.Request) error {
if r.Header.Get("Authorization") == "" {
r.Header.Set("Authorization", cli.Token)
}
if r.UserAgent() == "" {
r.Header.Set("User-Agent", UserAgent)
}
2020-01-08 07:10:37 +00:00
r.Header.Set("X-RateLimit-Precision", "millisecond")
2020-01-08 18:43:15 +00:00
// Rate limit stuff
return cli.Limiter.Acquire(r.Context(), r.URL.Path)
}
tw.Post = func(r *http.Response) error {
return cli.Limiter.Release(r.Request.URL.Path, r.Header)
2020-01-02 05:39:52 +00:00
}
cli.Client.Transport = tw
return cli
}