ipfs-cluster/api/rest/client/client.go
Hector Sanjuan 0a8edc17c9 Fix #260: Add REST API client and use it in ipfs-cluster-ctl
This adds the pakage api/rest/client which implements a go-client
for the REST API component. It also update the ipfs-cluster-ctl
tool to rely on it.

Originally, I wanted this to live it in it's own separate repository,
but the api client uses /api/types.go, which is part of cluster.

Therefore it would need to import all of cluster as a dependency.
ipfs-cluster-ctl would also need to import go-ipfs-cluster-api-client
as a dependency, creating circular gx deps which would be a mess to
maintain.

Only the splitting of cluster in multiple repositories (at least for
api, rest, ipfs-cluster-ctl, rest/client and test) would allow better
dependency management by allowing rest/client and the ctl tool
to only import what is needed, but this is something which brings
maintenance costs and can probably wait a bit until cluster is more stable.

License: MIT
Signed-off-by: Hector Sanjuan <code@hector.link>
2017-12-06 20:12:01 +01:00

93 lines
1.8 KiB
Go

package client
import (
"context"
"net/http"
"time"
logging "github.com/ipfs/go-log"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
)
// Configuration defaults
var (
DefaultTimeout = 60 * time.Second
DefaultAPIAddr = "/ip4/127.0.0.1/tcp/9094"
)
var logger = logging.Logger("apiclient")
// Config allows to configure the parameters to connect
// to the ipfs-cluster REST API.
type Config struct {
// Enable SSL support
SSL bool
// Skip certificate verification (insecure)
NoVerifyCert bool
// Username and password for basic authentication
Username string
Password string
// The ipfs-cluster REST API endpoint
APIAddr ma.Multiaddr
// Define timeout for network operations
Timeout time.Duration
// LogLevel defines the verbosity of the "apiclient" facility
LogLevel string
}
// Client provides methods to interact with the ipfs-cluster API. Use
// NewClient() to create one.
type Client struct {
ctx context.Context
cancel func()
config *Config
transport http.RoundTripper
urlPrefix string
}
// NewClient initializes a client given a Config.
func NewClient(cfg *Config) (*Client, error) {
var urlPrefix = ""
var tr http.RoundTripper
if cfg.SSL {
tr = newTLSTransport(cfg.NoVerifyCert)
urlPrefix += "https://"
} else {
tr = http.DefaultTransport
urlPrefix += "http://"
}
if cfg.APIAddr == nil {
cfg.APIAddr, _ = ma.NewMultiaddr(DefaultAPIAddr)
}
_, host, err := manet.DialArgs(cfg.APIAddr)
if err != nil {
return nil, err
}
urlPrefix += host
if lvl := cfg.LogLevel; lvl != "" {
logging.SetLogLevel("apiclient", lvl)
}
if cfg.Timeout == 0 {
cfg.Timeout = DefaultTimeout
}
ctx, cancel := context.WithCancel(context.Background())
return &Client{
ctx: ctx,
cancel: cancel,
urlPrefix: urlPrefix,
transport: tr,
config: cfg,
}, nil
}