Files
hauler/pkg/getter/https.go
T
2026-08-05 16:34:41 -04:00

82 lines
1.5 KiB
Go

package getter
import (
"context"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"path/filepath"
"strings"
"hauler.dev/go/hauler/v2/pkg/artifacts"
"hauler.dev/go/hauler/v2/pkg/consts"
)
type Http struct{}
func NewHttp() *Http {
return &Http{}
}
func (h Http) Name(u *url.URL) string {
resp, err := http.Head(u.String())
if err != nil {
return ""
}
defer resp.Body.Close()
unescaped, err := url.PathUnescape(u.String())
if err != nil {
return ""
}
contentType := resp.Header.Get("Content-Type")
for _, v := range strings.Split(contentType, ",") {
t, _, err := mime.ParseMediaType(v)
if err != nil {
break
}
// TODO: Identify known mimetypes for hints at a filename
_ = t
}
return filepath.Base(unescaped)
}
func (h Http) Open(ctx context.Context, u *url.URL) (io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("unexpected status fetching %s: %s", u.String(), resp.Status)
}
return resp.Body, nil
}
func (h Http) Detect(u *url.URL) bool {
switch u.Scheme {
case "http", "https":
return true
}
return false
}
func (h *Http) Config(u *url.URL) artifacts.Config {
c := &httpConfig{
config{Reference: u.String()},
}
return artifacts.ToConfig(c, artifacts.WithConfigMediaType(consts.FileHttpConfigMediaType))
}
type httpConfig struct {
config `json:",inline,omitempty"`
}