jx/internal/resource/http.go
Matthew Rich 33dd463180
Some checks failed
Lint / golangci-lint (push) Failing after 9m53s
Declarative Tests / test (push) Failing after 58s
update resource schemas
2024-04-09 12:30:05 -07:00

96 lines
1.7 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" json:"endpoint"`
Body string `yaml:"body,omitempty" json:"body,omitempty"`
State string `yaml:"state" json:"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) Validate() error {
return fmt.Errorf("failed")
}
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
}