jx/internal/resource/http.go
Matthew Rich c4b7819713
Some checks failed
Lint / golangci-lint (push) Failing after 10m4s
Declarative Tests / test (push) Successful in 1m14s
add command helper
2024-04-05 10:22:17 -07:00

92 lines
1.6 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
"context"
_ "errors"
"fmt"
"gopkg.in/yaml.v3"
"io"
"net/url"
"net/http"
_ "os"
)
func init() {
ResourceTypes.Register("http", HTTPFactory)
ResourceTypes.Register("https", HTTPFactory)
}
func HTTPFactory(u *url.URL) Resource {
h := NewHTTP()
return h
}
// Manage the state of an HTTP endpoint
type HTTP struct {
Endpoint string `yaml:"endpoint"`
Body string `yaml:"body,omitempty"`
State string `yaml:"state"`
}
func NewHTTP() *HTTP {
return &HTTP{}
}
func (h *HTTP) URI() string {
return h.Endpoint
}
func (h *HTTP) SetURI(uri string) error {
if _, e := url.Parse(uri); e != nil {
return fmt.Errorf("%w: %s is not a file", ErrInvalidResourceURI, uri)
}
h.Endpoint = uri
return nil
}
func (h *HTTP) Apply() error {
switch h.State {
case "absent":
case "present":
}
return nil
}
func (h *HTTP) Load(r io.Reader) error {
c := NewYAMLDecoder(r)
return c.Decode(h)
}
func (h *HTTP) LoadDecl(yamlResourceDeclaration string) error {
c := NewYAMLStringDecoder(yamlResourceDeclaration)
return c.Decode(h)
}
func (h *HTTP) ResolveId(ctx context.Context) string {
return h.Endpoint
}
func (h *HTTP) Read(ctx context.Context) ([]byte, error) {
resp, err := http.Get(h.Endpoint)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, errReadBody := io.ReadAll(resp.Body)
if errReadBody != nil {
return nil, errReadBody
}
h.Body = string(body)
return yaml.Marshal(h)
}
func (h *HTTP) Type() string {
u, _ := url.Parse(h.Endpoint)
return u.Scheme
}