working commit
This commit is contained in:
+98
-4
@@ -1,9 +1,103 @@
|
||||
package client
|
||||
|
||||
type Client struct {
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Client struct{}
|
||||
|
||||
func NewClient() *Client {
|
||||
return &Client{}
|
||||
}
|
||||
|
||||
func (cli *Client) FileExists(path string) (bool, error) {
|
||||
//reqPath = fmt.Sprintf("/v3/api/file/%s", path)
|
||||
//request, err := http.NewRequest("HEAD", reqPath, nil)
|
||||
func (cli *Client) FileExists(ctx context.Context, reference string) (bool, error) {
|
||||
var res bool
|
||||
var err error
|
||||
|
||||
reqpath := fmt.Sprintf("/v3/api/file/%s", reference)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "HEAD", reqpath, nil)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
},
|
||||
}
|
||||
client := &http.Client{
|
||||
Transport: transport,
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
res = true
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (cli *Client) GetFile(ctx context.Context, ref, filename string) error {
|
||||
var err error
|
||||
|
||||
const api = "/v3/api/file/"
|
||||
|
||||
if !strings.Contains(ref, "://") {
|
||||
ref = "https://" + ref
|
||||
}
|
||||
url, err := url.Parse(ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
url.Path = path.Join(api, url.Path)
|
||||
url.User = nil
|
||||
ref = url.String()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", ref, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
},
|
||||
}
|
||||
client := &http.Client{
|
||||
Transport: transport,
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
err := fmt.Errorf("Received wrong status code: %s", resp.StatusCode)
|
||||
return err
|
||||
}
|
||||
|
||||
dirname := filepath.Dir(filename)
|
||||
err = os.MkdirAll(dirname, 0750)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0640)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(file, resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user