jx/internal/resource/http.go

96 lines
1.7 KiB
Go
Raw Normal View History

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
"context"
2024-04-05 17:22:17 +00:00
_ "errors"
"fmt"
"gopkg.in/yaml.v3"
2024-04-05 17:22:17 +00:00
"io"
"net/url"
2024-04-05 17:22:17 +00:00
"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 {
2024-04-09 19:30:05 +00:00
Endpoint string `yaml:"endpoint" json:"endpoint"`
2024-04-09 19:30:05 +00:00
Body string `yaml:"body,omitempty" json:"body,omitempty"`
State string `yaml:"state" json:"state"`
}
func NewHTTP() *HTTP {
2024-04-05 17:22:17 +00:00
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
}
2024-04-09 19:30:05 +00:00
func (h *HTTP) Validate() error {
return fmt.Errorf("failed")
}
func (h *HTTP) Apply() error {
switch h.State {
case "absent":
case "present":
}
return nil
}
2024-04-05 17:22:17 +00:00
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) {
2024-04-05 17:22:17 +00:00
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
}