47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package sync
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
// Upload posts the raw playersDB.json bytes to endpoint with X-API-Key and Content-Type: application/json.
|
|
func Upload(ctx context.Context, client *http.Client, endpoint, apiKey string, body []byte) error {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("X-API-Key", apiKey)
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
|
|
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, bytes.TrimSpace(snippet))
|
|
}
|
|
_, _ = io.Copy(io.Discard, resp.Body)
|
|
return nil
|
|
}
|
|
|
|
// ReadPlayersDB reads the file from disk.
|
|
func ReadPlayersDB(path string) ([]byte, error) {
|
|
return os.ReadFile(path)
|
|
}
|
|
|
|
// NewHTTPClient returns a client suitable for large JSON uploads.
|
|
func NewHTTPClient() *http.Client {
|
|
return &http.Client{
|
|
Timeout: 90 * time.Second,
|
|
}
|
|
}
|