72 lines
1.2 KiB
Go
72 lines
1.2 KiB
Go
package jf2
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"html"
|
|
"io"
|
|
"strconv"
|
|
"strings"
|
|
|
|
nethtml "golang.org/x/net/html"
|
|
)
|
|
|
|
// HTML is the text/html version of the containing object.
|
|
type HTML struct {
|
|
node *nethtml.Node
|
|
value string
|
|
}
|
|
|
|
func NewHTML(r io.Reader) (*HTML, error) {
|
|
value, err := io.ReadAll(r)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cannot read r HTML value as string: %w", err)
|
|
}
|
|
|
|
node, err := nethtml.Parse(bytes.NewReader(value))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cannot parse r as HTML: %w", err)
|
|
}
|
|
|
|
return &HTML{
|
|
node: node,
|
|
value: string(value),
|
|
}, nil
|
|
}
|
|
|
|
func (h *HTML) UnmarshalJSON(v []byte) error {
|
|
unquoted, err := strconv.Unquote(string(v))
|
|
if err != nil {
|
|
return fmt.Errorf("JF2: HTML: cannot unquote value: %w", err)
|
|
}
|
|
|
|
parsed, err := NewHTML(strings.NewReader(html.UnescapeString(unquoted)))
|
|
if err != nil {
|
|
return fmt.Errorf("JF2: HTML: cannot parse value as HTML node: %w", err)
|
|
}
|
|
|
|
*h = *parsed
|
|
|
|
return nil
|
|
}
|
|
|
|
func (h HTML) MarshalJSON() ([]byte, error) {
|
|
if h.value != "" {
|
|
return []byte(strconv.Quote(h.value)), nil
|
|
}
|
|
|
|
return nil, nil
|
|
}
|
|
|
|
func (h HTML) GoString() string {
|
|
return "jf2.HTML(" + h.String() + ")"
|
|
}
|
|
|
|
func (h HTML) String() string {
|
|
if h.value != "" {
|
|
return h.value
|
|
}
|
|
|
|
return "und"
|
|
}
|