graphql-engine/cli/plugins/download/fetch.go
Mohd Bilal 3394c97fdc cli: refactor plugins/download to use internal/errors
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/6526
Co-authored-by: Aravind K P <8335904+scriptonist@users.noreply.github.com>
GitOrigin-RevId: b12bbdf7bfac7eb3313b3e814aa6e1d73e77d3ce
2022-10-27 03:18:33 +00:00

62 lines
1.8 KiB
Go

// Copyright 2019 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package download
import (
"fmt"
"io"
"net/http"
"os"
"github.com/hasura/graphql-engine/cli/v2/internal/errors"
)
// Fetcher is used to get files from a URI.
type Fetcher interface {
// Get gets the file and returns an stream to read the file.
Get(uri string) (io.ReadCloser, error)
}
var _ Fetcher = HTTPFetcher{}
// HTTPFetcher is used to get a file from a http:// or https:// schema path.
type HTTPFetcher struct{}
// Get gets the file and returns an stream to read the file.
func (HTTPFetcher) Get(uri string) (io.ReadCloser, error) {
var op errors.Op = "download.HTTPFetcher.Get"
resp, err := http.Get(uri)
if err != nil {
return nil, errors.E(op, errors.KindNetwork, fmt.Errorf("failed to download %q: %w", uri, err))
}
return resp.Body, nil
}
var _ Fetcher = fileFetcher{}
type fileFetcher struct{ f string }
func (f fileFetcher) Get(_ string) (io.ReadCloser, error) {
var op errors.Op = "download.fileFetcher.Get"
file, err := os.Open(f.f)
if err != nil {
return file, errors.E(op, fmt.Errorf("failed to open archive file %q for reading: %w", f.f, err))
}
return file, nil
}
// NewFileFetcher returns a local file reader.
func NewFileFetcher(path string) Fetcher { return fileFetcher{f: path} }