Skip to content

Commit

Permalink
add storage client
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean-Pearce committed Apr 18, 2020
1 parent 1443798 commit fb18c0b
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions service/storage/client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package client

import (
"io"
"net/http"

"github.com/go-resty/resty/v2"
)

const (
pingPath = "/ping"
uploadPath = "/upload"
downloadPath = "/download"
)

// StorageClient is a client of storage service.
type StorageClient struct {
name string
endpoint string
username string
password string
}

// NewStorageClient constructs a new storage client.
func NewStorageClient(name, endpoint, username, password string) *StorageClient {
return &StorageClient{name, endpoint, username, password}
}

// Ping pings storage server with basic auth.
func (c *StorageClient) Ping() (*http.Response, error) {
client := resty.New()

resp, err := client.R().SetBasicAuth(c.username, c.password).Get(c.endpoint + pingPath)
if err != nil {
return nil, err
}

return resp.RawResponse, nil
}

// Upload uploads a file to storage server using given io.Reader.
func (c *StorageClient) Upload(file io.Reader, filename string) (*http.Response, error) {
client := resty.New()

resp, err := client.R().
SetFileReader("file", filename, file).
SetFormData(map[string]string{
"filename": filename,
}).
SetBasicAuth(c.username, c.password).
Post(c.endpoint + uploadPath)
if err != nil {
return nil, err
}

return resp.RawResponse, nil
}

// Download downloads given filename from storage server.
func (c *StorageClient) Download(filename string) (*http.Response, error) {
client := resty.New()

resp, err := client.R().
SetQueryParam(filename, filename).
SetBasicAuth(c.username, c.password).
Get(c.endpoint + pingPath)
if err != nil {
return nil, err
}

return resp.RawResponse, nil
}

0 comments on commit fb18c0b

Please sign in to comment.