go-twitch/api/conduit/create_conduits.go

60 lines
1.2 KiB
Go
Raw Normal View History

2024-02-28 13:50:07 -05:00
package conduit
import (
"context"
"encoding/json"
"fmt"
2024-03-05 12:33:34 -05:00
"io"
2024-02-28 13:50:07 -05:00
"net/http"
"net/url"
)
2024-03-05 12:33:34 -05:00
type CreateConduitsRequest struct {
// The number of shards to create for this conduit.
ShardCount int `json:"shard_count"`
}
2024-02-28 13:50:07 -05:00
type CreateConduitsResponse struct {
Data []ConduitData `json:"data"`
}
// Creates a new conduit.
//
// Requires an app access token.
2024-03-05 12:33:34 -05:00
func (c *Conduit) CreateConduits(ctx context.Context, body *CreateConduitsRequest) (*CreateConduitsResponse, error) {
endpoint := c.baseUrl.ResolveReference(&url.URL{Path: "eventsub/conduits"})
r, w := io.Pipe()
go func() {
if err := json.NewEncoder(w).Encode(body); err != nil {
w.CloseWithError(err)
} else {
w.Close()
}
}()
2024-02-28 13:50:07 -05:00
2024-03-05 12:33:34 -05:00
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), r)
2024-02-28 13:50:07 -05:00
if err != nil {
return nil, err
}
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
statusOK := res.StatusCode >= 200 && res.StatusCode < 300
if !statusOK {
return nil, fmt.Errorf("failed to create conduit (%d)", res.StatusCode)
}
2024-02-28 13:50:07 -05:00
var data CreateConduitsResponse
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
return nil, err
}
return &data, nil
}