A JSON check requests a URL with GET or POST, optional headers and body, and requires the expected status and every condition: paths like checks[0].state compared with ==, !=, <, <=, >, >=, contains, exists or absent. Failures name the path, the value found and the expectation. HTTP and JSON checks share the request code and its network guard. Refs #26 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
70 lines
1.5 KiB
Go
70 lines
1.5 KiB
Go
package check
|
|
|
|
import (
|
|
"errors"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// A path selects a value in a JSON document: keys separated by dots and
|
|
// array indexes in brackets, e.g. "checks[0].status". A leading "$." is
|
|
// accepted for familiarity. Keys containing dots or brackets cannot be
|
|
// addressed.
|
|
type path []any // string keys and int indexes
|
|
|
|
var errPath = errors.New("check: invalid path")
|
|
|
|
func parsePath(s string) (path, error) {
|
|
s = strings.TrimPrefix(strings.TrimPrefix(s, "$"), ".")
|
|
if s == "" {
|
|
return path{}, nil
|
|
}
|
|
var p path
|
|
for _, part := range strings.Split(s, ".") {
|
|
key, rest, bracket := strings.Cut(part, "[")
|
|
if (key == "" && rest == "") || (bracket && rest == "") {
|
|
return nil, errPath
|
|
}
|
|
if key != "" {
|
|
p = append(p, key)
|
|
}
|
|
for rest != "" {
|
|
idx, after, ok := strings.Cut(rest, "]")
|
|
n, err := strconv.Atoi(idx)
|
|
if !ok || err != nil || n < 0 {
|
|
return nil, errPath
|
|
}
|
|
p = append(p, n)
|
|
rest = strings.TrimPrefix(after, "[")
|
|
if after != "" && !strings.HasPrefix(after, "[") {
|
|
return nil, errPath
|
|
}
|
|
}
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// lookup returns the value at p in doc, as decoded by encoding/json.
|
|
func (p path) lookup(doc any) (any, bool) {
|
|
cur := doc
|
|
for _, step := range p {
|
|
switch k := step.(type) {
|
|
case string:
|
|
m, ok := cur.(map[string]any)
|
|
if !ok {
|
|
return nil, false
|
|
}
|
|
if cur, ok = m[k]; !ok {
|
|
return nil, false
|
|
}
|
|
case int:
|
|
a, ok := cur.([]any)
|
|
if !ok || k >= len(a) {
|
|
return nil, false
|
|
}
|
|
cur = a[k]
|
|
}
|
|
}
|
|
return cur, true
|
|
}
|