gpm/go-gpm/client.go

60 lines
1.1 KiB
Go
Raw Normal View History

package gpm
import (
"context"
"io"
"net/http"
"strings"
)
const (
DefaultServer = "https://gpm.jolheiser.com"
TokenHeader = "X-GPM-Token"
)
// Client is a gpm client
type Client struct {
token string
server string
http *http.Client
}
// New returns a new Client
func New(token string, opts ...ClientOption) *Client {
c := &Client{
token: token,
server: DefaultServer,
http: http.DefaultClient,
}
for _, opt := range opts {
opt(c)
}
return c
}
// ClientOption is an option for a Client
type ClientOption func(*Client)
// WithHTTP sets the http.Client for a Client
func WithHTTP(client *http.Client) ClientOption {
return func(c *Client) {
c.http = client
}
}
// WithServer sets the gpm server for a Client
func WithServer(server string) ClientOption {
return func(c *Client) {
c.server = strings.TrimSuffix(server, "/")
}
}
func (c *Client) newRequest(ctx context.Context, method, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, err
}
req.Header.Set(TokenHeader, c.token)
return req, nil
}