core

package
v0.0.0-...-a3b39dc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2024 License: BSD-3-Clause Imports: 14 Imported by: 36

Documentation

Index

Examples

Constants

View Source
const (
	TimestampName = "timestamp"
	StatusName    = "status"
	CodeName      = "code"
	TraceName     = "trace"
	RequestIdName = "request-id"
	ErrorsName    = "errors"
)
View Source
const (
	XRequestId        = "X-Request-Id"
	XRelatesTo        = "X-Relates-To"
	XDomain           = "X-Domain"
	XVersion          = "X-Version"
	XURLPath          = "x-url-path"
	XTest             = "X-Test"
	XFrom             = "X-From"
	XTo               = "X-To"
	XRoute            = "X-Route"
	XExchangeRequest  = "X-Exchange-Request"
	XExchangeResponse = "X-Exchange-Response"
	XExchangeStatus   = "X-Exchange-Status"
)
View Source
const (
	RegionKey                = "region"
	ZoneKey                  = "zone"
	SubZoneKey               = "sub-zone"
	HostKey                  = "host"
	InstanceIdKey            = "id"
	RouteKey                 = "route"
	RegionZoneHostFmt        = "%v:%v.%v.%v"
	RegionZoneSubZoneHostFmt = "%v:%v.%v.%v.%v"
)
View Source
const (
	StatusInvalidContent             = int(90)  // Content is not available, is nil, or is of the wrong type, usually found via unmarshalling
	StatusIOError                    = int(91)  // I/O operation failed
	StatusJsonDecodeError            = int(92)  // Json decoding failed
	StatusJsonEncodeError            = int(93)  // Json encoding failed
	StatusContentEncodingError       = int(94)  // Content encoding error
	StatusContentEncodingInvalidType = int(95)  // Content encoding error
	StatusNotProvided                = int(96)  // No status is available
	StatusRateLimited                = int(97)  // Rate limited
	StatusNotStarted                 = int(98)  // Not started
	StatusHaveContent                = int(99)  // Content is available
	StatusGzipEncodingError          = int(100) // Gzip encoding error
	StatusGzipDecodingError          = int(101) // Gzip decoding error
	StatusTxnBeginError              = int(102) // Transaction processing begin error
	StatusTxnRollbackError           = int(103) // Transaction processing rollback error
	StatusTxnCommitError             = int(104) // Transaction processing commit error
	StatusExecError                  = int(105) // Execution error, as in a database call
	StatusNoChange                   = int(106) // State has not changed

	StatusInvalidArgument  = 3 //codes.InvalidArgument    // The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
	StatusDeadlineExceeded = 4 //codes.DeadlineExceeded   // The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long

)

Variables

This section is empty.

Functions

func AddRequestId

func AddRequestId(t any) http.Header

AddRequestId - add a request to an http.Request or an http.Header

Example
h := AddRequestId(nil)
fmt.Printf("test: AddRequestId(nil) -> [empty:%v]\n", len(h.Get(XRequestId)) == 0)

head := make(http.Header)
h = AddRequestId(head)
fmt.Printf("test: AddRequestId(head) -> [empty:%v]\n", len(h.Get(XRequestId)) == 0)

head = make(http.Header)
head.Add(XRequestId, "123-45-head")
h = AddRequestId(head)
fmt.Printf("test: AddRequestId(head) -> %v\n", h.Get(XRequestId))

req, _ := http.NewRequest("", "https.www.google.com", nil)
h = AddRequestId(req)
fmt.Printf("test: RequestId(request) -> [empty:%v]\n", len(h.Get(XRequestId)) == 0)

req, _ = http.NewRequest("", "https.www.google.com", nil)
req.Header.Set(XRequestId, "123-456-request")
h = AddRequestId(req)
fmt.Printf("test: RequestId(request) -> %v\n", h.Get(XRequestId))
Output:

test: AddRequestId(nil) -> [empty:false]
test: AddRequestId(head) -> [empty:false]
test: AddRequestId(head) -> 123-45-head
test: RequestId(request) -> [empty:false]
test: RequestId(request) -> 123-456-request

func ExchangeHeaders

func ExchangeHeaders(h http.Header) (req, resp, status string)

func FmtRFC3339Millis

func FmtRFC3339Millis(t time.Time) string

FmtRFC3339Millis - format time https://datatracker.ietf.org/doc/html/rfc3339

func HttpCode

func HttpCode(code int) int

HttpCode - conversion of a code to HTTP status code

func HttpStatus

func HttpStatus(code int) string

HttpStatus - string representation of status code

func JsonMarkup

func JsonMarkup(name, value string, stringValue bool) string

JsonMarkup - markup a name/value pair

func NewContext

func NewContext(ctx context.Context) context.Context

func NewInvalidBodyTypeError

func NewInvalidBodyTypeError(t any) error

NewInvalidBodyTypeError - invalid type error

func NewValues

func NewValues(o Origin) url.Values
Example
o := Origin{
	Region:     "region",
	Zone:       "zone",
	SubZone:    "sub-zone",
	Host:       "host",
	InstanceId: "",
}
values := NewValues(o)
fmt.Printf("test: NewValues() -> [%v]\n", values)
Output:

test: NewValues() -> [map[host:[host] region:[region] sub-zone:[sub-zone] zone:[zone]]]

func OriginMatch

func OriginMatch(target Origin, filter Origin) bool
Example
target := Origin{
	Region:     "Region",
	Zone:       "zonE",
	SubZone:    "sub-zone",
	Host:       "hOst",
	InstanceId: "",
}
filter := Origin{
	Region:     "",
	Zone:       "",
	SubZone:    "",
	Host:       "",
	InstanceId: "",
}

fmt.Printf("test: OriginMatch(%v,%v) -> [match:%v]\n", target, filter, OriginMatch(target, filter))

filter.Region = "region"
fmt.Printf("test: OriginMatch(%v,%v) -> [match:%v]\n", target, filter, OriginMatch(target, filter))

filter.Zone = "zone"
fmt.Printf("test: OriginMatch(%v,%v) -> [match:%v]\n", target, filter, OriginMatch(target, filter))

filter.SubZone = "sub-zone"
fmt.Printf("test: OriginMatch(%v,%v) -> [match:%v]\n", target, filter, OriginMatch(target, filter))

filter.Host = "host"
fmt.Printf("test: OriginMatch(%v,%v) -> [match:%v]\n", target, filter, OriginMatch(target, filter))

filter.SubZone = ""
fmt.Printf("test: OriginMatch(%v,%v) -> [match:%v]\n", target, filter, OriginMatch(target, filter))

filter.SubZone = "invalid"
fmt.Printf("test: OriginMatch(%v,%v) -> [match:%v]\n", target, filter, OriginMatch(target, filter))
Output:

test: OriginMatch({Region zonE sub-zone hOst  },{     }) -> [match:false]
test: OriginMatch({Region zonE sub-zone hOst  },{region     }) -> [match:true]
test: OriginMatch({Region zonE sub-zone hOst  },{region zone    }) -> [match:true]
test: OriginMatch({Region zonE sub-zone hOst  },{region zone sub-zone   }) -> [match:true]
test: OriginMatch({Region zonE sub-zone hOst  },{region zone sub-zone host  }) -> [match:true]
test: OriginMatch({Region zonE sub-zone hOst  },{region zone  host  }) -> [match:true]
test: OriginMatch({Region zonE sub-zone hOst  },{region zone invalid host  }) -> [match:false]

func ParseRFC3339Millis

func ParseRFC3339Millis(ts string) (time.Time, error)

ParseRFC3339Millis - parse a string into a time.Time, using the following string : 2023-04-14T14:14:45.522Z

func ParseTimestamp2

func ParseTimestamp2(s string) (time.Time, error)

ParseTimestamp2 - parse a string into a time.Time, using the following string : 2023-04-14 14:14:45.522460

func RequestId

func RequestId(t any) string

RequestId - return a request id from any type and will create a new one if not found

Example
id := RequestId("123-456-string")
fmt.Printf("test: RequestId(string) -> %v\n", id)

req, _ := http.NewRequest("", "https.www.google.com", nil)
req.Header.Set(XRequestId, "123-456-request")
id = RequestId(req)
fmt.Printf("test: RequestId(request) -> %v\n", id)

h := make(http.Header)
h.Set(XRequestId, "123-456-header")
id = RequestId(h)
fmt.Printf("test: RequestId(header) -> %v\n", id)
Output:

test: RequestId(string) -> 123-456-string
test: RequestId(request) -> 123-456-request
test: RequestId(header) -> 123-456-header

func SetLogFunc

func SetLogFunc(fn LogFunc)

SetLogFunc - optional override of logging

func StringMatch

func StringMatch(target, filter string) bool

Types

type Bypass

type Bypass struct{}

Bypass - bypass error handler

func (Bypass) Handle

func (h Bypass) Handle(s *Status) *Status

Handle - bypass error handler

type ErrorHandler

type ErrorHandler interface {
	Handle(s *Status) *Status
}

ErrorHandler - error handler interface

type ExchangeProxy

type ExchangeProxy struct {
	// contains filtered or unexported fields
}

ExchangeProxy - key value pairs of a domain -> HttpExchange

func NewExchangeProxy

func NewExchangeProxy() *ExchangeProxy

NewExchangeProxy - create a new Exchange Proxy

func (*ExchangeProxy) Lookup

func (p *ExchangeProxy) Lookup(domain string) HttpExchange

Lookup - get an HttpExchange from the proxy, using an domain as a key

func (*ExchangeProxy) LookupByRequest

func (p *ExchangeProxy) LookupByRequest(req *http.Request) HttpExchange

LookupByRequest - find an HttpExchange from a request

func (*ExchangeProxy) Register

func (p *ExchangeProxy) Register(domain string, handler HttpExchange) error

type HttpExchange

type HttpExchange func(r *http.Request) (*http.Response, *Status)

type HttpHandler

type HttpHandler func(w http.ResponseWriter, r *http.Request)

type Log

type Log struct{}

Log - log error handler

func (Log) Handle

func (h Log) Handle(s *Status) *Status

Handle - log error handler

type LogFunc

type LogFunc func(code int, status, requestId string, errs []error, trace []string)

LogFunc - log function

type Origin

type Origin struct {
	Region     string `json:"region"`
	Zone       string `json:"zone"`
	SubZone    string `json:"sub-zone"`
	Host       string `json:"host"`
	Route      string `json:"route"`
	InstanceId string `json:"instance-id"`
}

Origin - location

func NewOrigin

func NewOrigin(values url.Values) Origin
Example
o := Origin{
	Region:     "region",
	Zone:       "zone",
	SubZone:    "sub-zone",
	Host:       "host",
	Route:      "route",
	InstanceId: "",
}
values := NewValues(o)
o = NewOrigin(values)
fmt.Printf("test: NewOrigin() -> [%v]\n", o)
Output:

test: NewOrigin() -> [{region zone sub-zone host route }]

func (Origin) Tag

func (o Origin) Tag() string
Example
o := Origin{
	Region:     "region",
	Zone:       "zone",
	SubZone:    "sub-zone",
	Host:       "host",
	InstanceId: "",
}
fmt.Printf("test: Tag() -> [%v]\n", o.Tag())

o.Zone = ""
fmt.Printf("test: Tag() -> [%v]\n", o.Tag())

o.Host = ""
fmt.Printf("test: Tag() -> [%v]\n", o.Tag())

o.SubZone = ""
fmt.Printf("test: Tag() -> [%v]\n", o.Tag())
Output:

test: Tag() -> [region:zone:sub-zone:host]
test: Tag() -> [region:sub-zone:host]
test: Tag() -> [region:sub-zone]
test: Tag() -> [region]

func (Origin) Uri

func (o Origin) Uri(class string) string
Example
target := Origin{
	Region:     "region",
	Zone:       "zone",
	SubZone:    "sub-zone",
	Host:       "host",
	InstanceId: "",
}

fmt.Printf("test: Origin_Uri_SubZone()       -> [%v]\n", target.Uri("class"))
target.Route = "route"
fmt.Printf("test: Origin_Uri_SubZone_Route() -> [%v]\n", target.Uri("class"))

target.SubZone = ""
target.Route = ""
fmt.Printf("test: Origin_Uri_No_SubZone()    -> [%v]\n", target.Uri("class"))
Output:

test: Origin_Uri_SubZone()       -> [class:region.zone.sub-zone.host]
test: Origin_Uri_SubZone_Route() -> [class:region.zone.sub-zone.host.route]
test: Origin_Uri_No_SubZone()    -> [class:region.zone.host]

type Output

type Output struct{}

Output - standard output error handler

func (Output) Handle

func (h Output) Handle(s *Status) *Status

Handle - output error handler

type Status

type Status struct {
	Code      int    `json:"code"`
	Err       error  `json:"err"`
	RequestId string `json:"request-id"`
	Handled   bool   `json:"handled"`
	Duration  time.Duration
	Content   any
	// contains filtered or unexported fields
}

func NewStatus

func NewStatus(code int) *Status

func NewStatusDuration

func NewStatusDuration(code int, duration time.Duration) *Status

func NewStatusError

func NewStatusError(code int, err error) *Status

func StatusBadRequest

func StatusBadRequest() *Status

func StatusNoContent

func StatusNoContent() *Status

func StatusNotFound

func StatusNotFound() *Status

func StatusOK

func StatusOK() *Status

func (*Status) AddLocation

func (s *Status) AddLocation() *Status

func (*Status) AddParentLocation

func (s *Status) AddParentLocation() *Status

func (*Status) HttpCode

func (s *Status) HttpCode() int

func (*Status) NoContent

func (s *Status) NoContent() bool

func (*Status) NotFound

func (s *Status) NotFound() bool

func (*Status) OK

func (s *Status) OK() bool

func (*Status) StatusCode

func (s *Status) StatusCode() int

func (*Status) String

func (s *Status) String() string

func (*Status) Timeout

func (s *Status) Timeout() bool

func (*Status) Trace

func (s *Status) Trace() []string

func (*Status) WithRequestId

func (s *Status) WithRequestId(t any) *Status
Example
h := make(http.Header)
h.Add(XRequestId, "123456789")

status := StatusNotFound()
fmt.Printf("test: Status_WithRequestId() -> [request-id:%v]\n", status.WithRequestId(h).RequestId)

fmt.Printf("test: Status_WithRequestId() -> [request-id:%v]\n", status.WithRequestId("333-444-555").RequestId)
Output:

test: Status_WithRequestId() -> [request-id:123456789]
test: Status_WithRequestId() -> [request-id:333-444-555]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL