1 package reason
2 3 import (
4 "bytes"
5 "fmt"
6 )
7 8 // R is the machine-readable prefix before the colon in an OK or CLOSED envelope message.
9 // Below are the most common kinds that are mentioned in NIP-01.
10 type R []byte
11 12 var (
13 AuthRequired = R("auth-required")
14 PoW = R("pow")
15 Duplicate = R("duplicate")
16 Blocked = R("blocked")
17 RateLimited = R("rate-limited")
18 Invalid = R("invalid")
19 Error = R("error")
20 Unsupported = R("unsupported")
21 Restricted = R("restricted")
22 )
23 24 // S returns the R as a string
25 func (r R) S() string { return string(r) }
26 27 // B returns the R as a byte slice.
28 func (r R) B() []byte { return r }
29 30 // IsPrefix returns whether a text contains the same R prefix.
31 func (r R) IsPrefix(reason []byte) bool {
32 return bytes.HasPrefix(
33 reason, r.B(),
34 )
35 }
36 37 // F allows creation of a full R text with a printf style format.
38 func (r R) F(format string, params ...any) (o []byte) {
39 return Msg(r, format, params...)
40 }
41 42 // Msg constructs a properly formatted message with a machine-readable prefix
43 // for OK and CLOSED envelopes.
44 func Msg(prefix R, format string, params ...any) (o []byte) {
45 if len(prefix) < 1 {
46 prefix = Error
47 }
48 return []byte(fmt.Sprintf(prefix.S()+": "+format, params...))
49 }
50