skir_client

package module
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 20 Imported by: 0

README

skir-go-client

Go runtime library for skir-generated code.

This package is imported by Go code generated by skir-go-gen.

Installation

go get github.com/gepheum/skir-go-client

Usage

See https://github.com/gepheum/skir-go-gen

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	BoolDescriptor      = &PrimitiveDescriptor{primitiveType: PrimitiveTypeBool}
	Int32Descriptor     = &PrimitiveDescriptor{primitiveType: PrimitiveTypeInt32}
	Int64Descriptor     = &PrimitiveDescriptor{primitiveType: PrimitiveTypeInt64}
	Hash64Descriptor    = &PrimitiveDescriptor{primitiveType: PrimitiveTypeHash64}
	Float32Descriptor   = &PrimitiveDescriptor{primitiveType: PrimitiveTypeFloat32}
	Float64Descriptor   = &PrimitiveDescriptor{primitiveType: PrimitiveTypeFloat64}
	TimestampDescriptor = &PrimitiveDescriptor{primitiveType: PrimitiveTypeTimestamp}
	StringDescriptor    = &PrimitiveDescriptor{primitiveType: PrimitiveTypeString}
	BytesDescriptor     = &PrimitiveDescriptor{primitiveType: PrimitiveTypeBytes}
)

Singleton instances – one per primitive type.

Functions

func AddMethod added in v0.1.1

func AddMethod[Req, Resp, RequestMeta any](
	b *ServiceBuilder[RequestMeta],
	method Method[Req, Resp],
	impl func(ctx context.Context, req Req, meta RequestMeta) (Resp, error),
) error

AddMethod registers a method implementation on the builder.

Because Go generics do not allow generic methods, AddMethod is a package-level function rather than a method on ServiceBuilder.

Returns an error if a method with the same number has already been registered.

func Internal__AddField

func Internal__AddField[T, Builder, V any](
	a *Internal__StructAdapter[T, Builder],
	name string,
	number int,
	ser Serializer[V],
	doc string,
	getter func(T) V,
	setter func(Builder, V),
)

AddField registers a struct field on an in-progress Internal__StructAdapter. Must be called before Finalize.

This is a package-level function (not a method) because Go does not permit additional type parameters on methods.

func Internal__AddWrapperVariant

func Internal__AddWrapperVariant[T, V any](
	a *Internal__EnumAdapter[T],
	number int,
	name string,
	kindOrdinal int,
	ser Serializer[V],
	doc string,
	wrap func(V) T,
	getValue func(T) V,
)

Internal__AddWrapperVariant registers a wrapper variant on an in-progress Internal__EnumAdapter. Must be called before Finalize.

This is a package-level function (not a method) because Go does not permit additional type parameters on methods.

Types

type Array

type Array[T any] struct {
	// contains filtered or unexported fields
}

Array is an immutable, ordered sequence of elements of type T.

Unlike []T, an Array value cannot be modified after creation: callers cannot append to it, remove from it, or overwrite individual elements.

Elements must not be nil; ArrayFromSlice panics if any element is nil.

func ArrayFromSlice

func ArrayFromSlice[T any](s []T) Array[T]

ArrayFromSlice returns an Array whose content is a copy of s. Panics if any element of s is nil.

func (Array[T]) All

func (a Array[T]) All() iter.Seq2[int, T]

All returns an iterator over index-value pairs in forward order, compatible with range loops in Go 1.23+.

func (Array[T]) At

func (a Array[T]) At(i int) T

At returns the element at index i. Panics if i is out of range.

func (Array[T]) Backward

func (a Array[T]) Backward() iter.Seq2[int, T]

Backward returns an iterator over index-value pairs in reverse order, compatible with range loops in Go 1.23+.

func (Array[T]) IsEmpty

func (a Array[T]) IsEmpty() bool

IsEmpty reports whether the array contains no elements.

func (Array[T]) Len

func (a Array[T]) Len() int

Len returns the number of elements in the array.

func (Array[T]) ToSlice

func (a Array[T]) ToSlice() []T

ToSlice returns a copy of the underlying elements as a []T.

type ArrayDescriptor

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

ArrayDescriptor describes an ordered collection of elements of a single type.

func (*ArrayDescriptor) AsJson

func (d *ArrayDescriptor) AsJson() string

func (*ArrayDescriptor) ItemType

func (d *ArrayDescriptor) ItemType() TypeDescriptor

ItemType returns the type descriptor for each array element.

func (*ArrayDescriptor) KeyExtractor

func (d *ArrayDescriptor) KeyExtractor() string

KeyExtractor returns the key chain string, or empty if none.

type Bytes

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

Bytes is an immutable sequence of bytes.

Unlike []byte, a Bytes value cannot be modified after creation.

func BytesFromHex

func BytesFromHex(s string) (Bytes, error)

BytesFromHex decodes a hex string and returns the corresponding Bytes. It returns an error if s is not a valid hex string.

func BytesFromSlice

func BytesFromSlice(b []byte) Bytes

BytesFromSlice returns a Bytes whose content is a copy of b.

func (Bytes) Equal

func (b Bytes) Equal(other Bytes) bool

Equal reports whether b and other contain the same byte sequence.

func (Bytes) Hex

func (b Bytes) Hex() string

Hex returns the bytes encoded as a lowercase hexadecimal string.

func (Bytes) IsEmpty

func (b Bytes) IsEmpty() bool

IsEmpty reports whether the sequence contains no bytes.

func (Bytes) Len

func (b Bytes) Len() int

Len returns the number of bytes.

func (Bytes) Slice

func (b Bytes) Slice() []byte

Slice returns a copy of the bytes as a []byte.

func (Bytes) String

func (b Bytes) String() string

String returns the bytes encoded as a lowercase hexadecimal string.

type EnumConstantVariant

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

EnumConstantVariant describes a constant (non-wrapping) enum variant.

func (*EnumConstantVariant) Doc

func (v *EnumConstantVariant) Doc() string

func (*EnumConstantVariant) Name

func (v *EnumConstantVariant) Name() string

func (*EnumConstantVariant) Number

func (v *EnumConstantVariant) Number() int

type EnumDescriptor

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

EnumDescriptor describes a skir enum type.

func (*EnumDescriptor) AsJson

func (d *EnumDescriptor) AsJson() string

func (*EnumDescriptor) Doc

func (d *EnumDescriptor) Doc() string

func (*EnumDescriptor) ModulePath

func (d *EnumDescriptor) ModulePath() string

func (*EnumDescriptor) Name

func (d *EnumDescriptor) Name() string

func (*EnumDescriptor) QualifiedName

func (d *EnumDescriptor) QualifiedName() string

func (*EnumDescriptor) RemovedNumbers

func (d *EnumDescriptor) RemovedNumbers() map[int]struct{}

func (*EnumDescriptor) VariantByName

func (d *EnumDescriptor) VariantByName(name string) EnumVariant

VariantByName returns the variant with the given name, or nil if not found.

func (*EnumDescriptor) VariantByNumber

func (d *EnumDescriptor) VariantByNumber(number int) EnumVariant

VariantByNumber returns the variant with the given number, or nil if not found.

func (*EnumDescriptor) Variants

func (d *EnumDescriptor) Variants() []EnumVariant

type EnumVariant

type EnumVariant interface {
	Name() string
	Number() int
	Doc() string
	// contains filtered or unexported methods
}

EnumVariant is the common interface for skir enum variants. Concrete types: *EnumConstantVariant, *EnumWrapperVariant.

type EnumWrapperVariant

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

EnumWrapperVariant describes an enum variant that wraps a value of another type.

func (*EnumWrapperVariant) Doc

func (v *EnumWrapperVariant) Doc() string

func (*EnumWrapperVariant) Name

func (v *EnumWrapperVariant) Name() string

func (*EnumWrapperVariant) Number

func (v *EnumWrapperVariant) Number() int

func (*EnumWrapperVariant) Type

type HttpErrorCode

type HttpErrorCode int

HttpErrorCode is an HTTP error status code (4xx or 5xx).

const (
	HttpErrorCode_BadRequest                    HttpErrorCode = 400
	HttpErrorCode_Unauthorized                  HttpErrorCode = 401
	HttpErrorCode_PaymentRequired               HttpErrorCode = 402
	HttpErrorCode_Forbidden                     HttpErrorCode = 403
	HttpErrorCode_NotFound                      HttpErrorCode = 404
	HttpErrorCode_MethodNotAllowed              HttpErrorCode = 405
	HttpErrorCode_NotAcceptable                 HttpErrorCode = 406
	HttpErrorCode_ProxyAuthenticationRequired   HttpErrorCode = 407
	HttpErrorCode_RequestTimeout                HttpErrorCode = 408
	HttpErrorCode_Conflict                      HttpErrorCode = 409
	HttpErrorCode_Gone                          HttpErrorCode = 410
	HttpErrorCode_LengthRequired                HttpErrorCode = 411
	HttpErrorCode_PreconditionFailed            HttpErrorCode = 412
	HttpErrorCode_ContentTooLarge               HttpErrorCode = 413
	HttpErrorCode_UriTooLong                    HttpErrorCode = 414
	HttpErrorCode_UnsupportedMediaType          HttpErrorCode = 415
	HttpErrorCode_RangeNotSatisfiable           HttpErrorCode = 416
	HttpErrorCode_ExpectationFailed             HttpErrorCode = 417
	HttpErrorCode_ImATeapot                     HttpErrorCode = 418
	HttpErrorCode_MisdirectedRequest            HttpErrorCode = 421
	HttpErrorCode_UnprocessableContent          HttpErrorCode = 422
	HttpErrorCode_Locked                        HttpErrorCode = 423
	HttpErrorCode_FailedDependency              HttpErrorCode = 424
	HttpErrorCode_TooEarly                      HttpErrorCode = 425
	HttpErrorCode_UpgradeRequired               HttpErrorCode = 426
	HttpErrorCode_PreconditionRequired          HttpErrorCode = 428
	HttpErrorCode_TooManyRequests               HttpErrorCode = 429
	HttpErrorCode_RequestHeaderFieldsTooLarge   HttpErrorCode = 431
	HttpErrorCode_UnavailableForLegalReasons    HttpErrorCode = 451
	HttpErrorCode_InternalServerError           HttpErrorCode = 500
	HttpErrorCode_NotImplemented                HttpErrorCode = 501
	HttpErrorCode_BadGateway                    HttpErrorCode = 502
	HttpErrorCode_ServiceUnavailable            HttpErrorCode = 503
	HttpErrorCode_GatewayTimeout                HttpErrorCode = 504
	HttpErrorCode_HttpVersionNotSupported       HttpErrorCode = 505
	HttpErrorCode_VariantAlsoNegotiates         HttpErrorCode = 506
	HttpErrorCode_InsufficientStorage           HttpErrorCode = 507
	HttpErrorCode_LoopDetected                  HttpErrorCode = 508
	HttpErrorCode_NotExtended                   HttpErrorCode = 510
	HttpErrorCode_NetworkAuthenticationRequired HttpErrorCode = 511
)

type Internal__EnumAdapter

type Internal__EnumAdapter[T any] struct {
	// contains filtered or unexported fields
}

Internal__EnumAdapter implements typeAdapter[T] for a skir enum type. For use only by code generated by the skir Go generator.

  • T is the frozen enum type.

Usage: call NewEnumAdapter, then AddConstantVariant / AddWrapperVariant / AddRemovedNumber for each variant, then Finalize before using the adapter.

func NewEnumAdapter

func NewEnumAdapter[T any](
	modulePath, qualifiedName, doc string,
	getKindOrdinal func(T) int,
	kindCount int,
	unknownInstance T,
	wrapUnrecognized func(*Internal__UnrecognizedVariant) T,
	getUnrecognized func(T) *Internal__UnrecognizedVariant,
) *Internal__EnumAdapter[T]

NewEnumAdapter creates a new Internal__EnumAdapter.

kindCount is the total number of kind values including UNKNOWN. Call AddConstantVariant, AddWrapperVariant, AddRemovedNumber, then Finalize.

func (*Internal__EnumAdapter[T]) AddConstantVariant

func (a *Internal__EnumAdapter[T]) AddConstantVariant(
	number int,
	name string,
	kindOrdinal int,
	doc string,
	instance T,
)

AddConstantVariant registers a constant (non-wrapping) variant. Must be called before Finalize.

func (*Internal__EnumAdapter[T]) AddRemovedNumber

func (a *Internal__EnumAdapter[T]) AddRemovedNumber(number int)

AddRemovedNumber marks a variant number as having been removed from the schema. Must be called before Finalize.

func (*Internal__EnumAdapter[T]) Finalize

func (a *Internal__EnumAdapter[T]) Finalize()

Finalize prepares the adapter for serialization. Must be called once, after all Add* calls.

func (*Internal__EnumAdapter[T]) Serializer

func (a *Internal__EnumAdapter[T]) Serializer() Serializer[T]

Serializer returns a Serializer[T] backed by this adapter.

type Internal__StructAdapter

type Internal__StructAdapter[T, Builder any] struct {
	// contains filtered or unexported fields
}

Internal__StructAdapter implements typeAdapter[T] for a skir struct type. For use only by code generated by the skir Go generator.

  • T is the frozen (immutable) struct type.
  • Builder is the partial-builder type (e.g. *Foo_partialBuilderType).

Usage: call NewStructAdapter, then AddField / AddRemovedNumber for each field, then Finalize before using the adapter.

func Internal__NewStructAdapter

func Internal__NewStructAdapter[T, Builder any](
	defaultInstance T,
	isDefaultInstance func(T) bool,
	newBuilder func() Builder,
	build func(Builder) T,
	modulePath, qualifiedName, doc string,
	getUnrecognized func(T) *Internal__UnrecognizedFields,
	setUnrecognized func(Builder, *Internal__UnrecognizedFields),
) *Internal__StructAdapter[T, Builder]

NewStructAdapter creates a new Internal__StructAdapter. Call AddField / AddRemovedNumber for each field and removed number, then Finalize before using the adapter.

func (*Internal__StructAdapter[T, Builder]) AddRemovedNumber

func (a *Internal__StructAdapter[T, Builder]) AddRemovedNumber(number int)

AddRemovedNumber registers a field number that was removed from the schema. Must be called before Finalize.

func (*Internal__StructAdapter[T, Builder]) Finalize

func (a *Internal__StructAdapter[T, Builder]) Finalize()

Finalize prepares the adapter for serialization. Must be called once, after all AddField and AddRemovedNumber calls.

func (*Internal__StructAdapter[T, Builder]) Serializer

func (a *Internal__StructAdapter[T, Builder]) Serializer() Serializer[T]

Serializer returns a Serializer[T] backed by this adapter.

type Internal__UnrecognizedFields

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

Internal__UnrecognizedFields holds field data from a newer schema version that this client does not recognise. It preserves the data in whichever form it was received (JSON or binary) so it can be round-tripped.

Exactly one of jsonElements or bytes is non-nil.

func Internal__NewUnrecognizedFieldsFromBytes

func Internal__NewUnrecognizedFieldsFromBytes(totalSlotCount int, bytes []byte) *Internal__UnrecognizedFields

Internal__NewUnrecognizedFieldsFromBytes constructs an Internal__UnrecognizedFields from binary wire data.

func Internal__NewUnrecognizedFieldsFromJson

func Internal__NewUnrecognizedFieldsFromJson(totalSlotCount int, jsonElements []*fastjson.Value) *Internal__UnrecognizedFields

Internal__NewUnrecognizedFieldsFromJson constructs an Internal__UnrecognizedFields from JSON data.

type Internal__UnrecognizedVariant

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

Internal__UnrecognizedVariant holds the value of an enum variant from a newer schema version that this client does not recognise. It preserves the data in whichever form it was received (JSON or binary) so it can be round-tripped.

Exactly one of jsonElement or bytes is non-nil.

func Internal__NewUnrecognizedVariantFromBytes

func Internal__NewUnrecognizedVariantFromBytes(bytes []byte) *Internal__UnrecognizedVariant

Internal__NewUnrecognizedVariantFromBytes constructs an Internal__UnrecognizedVariant from binary wire data.

func Internal__NewUnrecognizedVariantFromJson

func Internal__NewUnrecognizedVariantFromJson(jsonElement *fastjson.Value) *Internal__UnrecognizedVariant

Internal__NewUnrecognizedVariantFromJson constructs an Internal__UnrecognizedVariant from JSON data.

type InvokeOption

type InvokeOption func(*invokeConfig)

InvokeOption is a functional option for InvokeRemote.

func WithHeader

func WithHeader(key, value string) InvokeOption

WithHeader returns an InvokeOption that adds an HTTP header for a single InvokeRemote call, overriding any default header with the same name.

type KeepUnrecognizedValues

type KeepUnrecognizedValues struct{}

KeepUnrecognizedValues instructs FromJson and FromBytes to preserve fields and variants from a newer schema version that are not recognised by this decoder.

type Method

type Method[Request, Response any] struct {
	// contains filtered or unexported fields
}

Method identifies one method in a SkirRPC service, both on the server side and the client side.

  • Request is the type of the request parameter.
  • Response is the type of the response returned by this method.

func NewMethod

func NewMethod[Request, Response any](
	name string,
	number int64,
	requestSerializer Serializer[Request],
	responseSerializer Serializer[Response],
	doc string,
) Method[Request, Response]

NewMethod creates an immutable Method.

func (Method[Request, Response]) Doc

func (m Method[Request, Response]) Doc() string

Doc returns the documentation string for this method.

func (Method[Request, Response]) Name

func (m Method[Request, Response]) Name() string

Name returns the name of the method.

func (Method[Request, Response]) Number

func (m Method[Request, Response]) Number() int64

Number returns the unique number identifying this method within the service.

func (Method[Request, Response]) RequestSerializer

func (m Method[Request, Response]) RequestSerializer() Serializer[Request]

RequestSerializer returns the serializer for the request type.

func (Method[Request, Response]) ResponseSerializer

func (m Method[Request, Response]) ResponseSerializer() Serializer[Response]

ResponseSerializer returns the serializer for the response type.

type MethodErrorInfo

type MethodErrorInfo[RequestMeta any] struct {
	// Err is the error returned by the method implementation.
	Err error
	// MethodName is the name of the method that was invoked.
	MethodName string
	// RawRequest is the JSON-serialized request.
	RawRequest string
	// RequestMeta is the per-request metadata supplied by the HTTP handler.
	RequestMeta RequestMeta
}

MethodErrorInfo carries contextual information about an error that occurred while handling a method call. It is passed to the ErrorLogger and CanSendUnknownErrorMessage hooks in ServiceBuilder.

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional[T] holds a value of type T that may or may not be present. It is deeply immutable when T is deeply immutable.

To obtain a present value, use OptionalOf or OptionalOfNilable. To obtain an absent value, use the zero value: Optional[T]{}.

The wrapped value must not be nil; OptionalOf panics if it is.

func OptionalOf

func OptionalOf[T any](v T) Optional[T]

OptionalOf returns an Optional containing v. Panics if v is nil.

func OptionalOfNilable

func OptionalOfNilable[T any](p *T) Optional[T]

OptionalOfNilable converts a possibly-nil pointer to an Optional: nil pointer → absent, non-nil pointer → present with *p. If T is an interface type, *p must not be a nil interface; panics if it is.

func (Optional[T]) Get

func (o Optional[T]) Get() T

Get returns the value. Panics if not present.

func (Optional[T]) GetOr

func (o Optional[T]) GetOr(def T) T

GetOr returns the value if present, or the provided default value otherwise.

func (Optional[T]) IsPresent

func (o Optional[T]) IsPresent() bool

IsPresent reports whether a value is present.

func (Optional[T]) String

func (o Optional[T]) String() string

type OptionalDescriptor

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

OptionalDescriptor describes an optional type that can hold either a value of the wrapped type or a null/zero value.

func (*OptionalDescriptor) AsJson

func (d *OptionalDescriptor) AsJson() string

func (*OptionalDescriptor) OtherType

func (d *OptionalDescriptor) OtherType() TypeDescriptor

OtherType returns the type descriptor for the wrapped non-null type.

type PrimitiveDescriptor

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

PrimitiveDescriptor describes a primitive skir type.

func (*PrimitiveDescriptor) AsJson

func (d *PrimitiveDescriptor) AsJson() string

func (*PrimitiveDescriptor) PrimitiveType

func (d *PrimitiveDescriptor) PrimitiveType() PrimitiveType

PrimitiveType returns the PrimitiveType value.

type PrimitiveType

type PrimitiveType int

PrimitiveType enumerates all primitive types supported by skir.

const (
	PrimitiveTypeBool PrimitiveType = iota
	PrimitiveTypeInt32
	PrimitiveTypeInt64
	PrimitiveTypeHash64
	PrimitiveTypeFloat32
	PrimitiveTypeFloat64
	PrimitiveTypeTimestamp
	PrimitiveTypeString
	PrimitiveTypeBytes
)

func (PrimitiveType) String

func (p PrimitiveType) String() string

type RawResponse

type RawResponse struct {
	// Data is the response body.
	Data string
	// StatusCode is the HTTP status code.
	StatusCode int
	// ContentType is the value for the Content-Type header.
	ContentType string
}

RawResponse is the serialized response returned by Service.HandleRequest. Pass it directly to your HTTP framework's response writer.

func (RawResponse) ServeHttp

func (r RawResponse) ServeHttp(w http.ResponseWriter)

ServeHttp writes the raw response to an http.ResponseWriter.

type Readable

type Readable struct{}

Readable is a tag type passed to ToJson to request human-readable (indented) output.

type RecordDescriptorBase

type RecordDescriptorBase interface {
	TypeDescriptor

	// Name of the record as specified in the '.skir' file.
	Name() string

	// QualifiedName contains all names in the hierarchical sequence, e.g.
	// "Foo.Bar" if Bar is nested within Foo, or simply "Bar" for top-level.
	QualifiedName() string

	// ModulePath is the path to the '.skir' file relative to the skir source root.
	ModulePath() string

	// Doc is the documentation extracted from doc comments in the '.skir' file.
	Doc() string

	// RemovedNumbers returns the set of field/variant numbers that have been
	// marked as removed (reserved).
	RemovedNumbers() map[int]struct{}
	// contains filtered or unexported methods
}

RecordDescriptorBase provides common metadata for struct and enum descriptors.

type RpcError

type RpcError struct {
	// StatusCode is the HTTP status code returned by the server, or 0 for
	// network-level failures (e.g. DNS error, connection refused, timeout).
	StatusCode int
	// Message is the error description.
	Message string
}

RpcError is returned by InvokeRemote when the server responds with a non-2xx HTTP status code or when a network-level failure occurs.

func InvokeRemote

func InvokeRemote[Req, Resp any](
	ctx context.Context,
	client *ServiceClient,
	method Method[Req, Resp],
	req Req,
	opts ...InvokeOption,
) (Resp, *RpcError)

InvokeRemote sends req to the remote service and returns the deserialized response. The provided context controls the deadline and cancellation of the underlying HTTP request.

Because Go generics do not allow generic methods on structs, InvokeRemote is a package-level function rather than a method on ServiceClient.

Example:

client := skir_client.NewServiceClient("https://example.com/api")
defer client.Close()

resp, err := skir_client.InvokeRemote(ctx, client, MyMethod(), MyRequest{...})

func (*RpcError) Error

func (e *RpcError) Error() string

type Serializer

type Serializer[T any] struct {
	// contains filtered or unexported fields
}

Serializer serialises and deserialises values of type T in both JSON and binary formats.

func ArraySerializer

func ArraySerializer[E any](item Serializer[E]) Serializer[Array[E]]

ArraySerializer wraps an existing item Serializer to produce a Serializer[Array[E]].

func BoolSerializer

func BoolSerializer() Serializer[bool]

BoolSerializer returns a Serializer for bool values.

func BytesSerializer

func BytesSerializer() Serializer[Bytes]

BytesSerializer returns a Serializer for Bytes values.

func Float32Serializer

func Float32Serializer() Serializer[float32]

Float32Serializer returns a Serializer for float32 values.

func Float64Serializer

func Float64Serializer() Serializer[float64]

Float64Serializer returns a Serializer for float64 values.

func Hash64Serializer

func Hash64Serializer() Serializer[uint64]

Hash64Serializer returns a Serializer for uint64 hash values.

func Int32Serializer

func Int32Serializer() Serializer[int32]

Int32Serializer returns a Serializer for int32 values.

func Int64Serializer

func Int64Serializer() Serializer[int64]

Int64Serializer returns a Serializer for int64 values.

func Internal__ArraySerializer

func Internal__ArraySerializer[E any](item Serializer[E], keyExtractor string) Serializer[Array[E]]

Internal__ArraySerializer returns a Serializer[Array[E]] backed by item, using keyExtractor to produce sort keys. For use by code generated by the skir Go generator.

func OptionalSerializer

func OptionalSerializer[E any](other Serializer[E]) Serializer[Optional[E]]

OptionalSerializer wraps an existing Serializer to produce a Serializer[*E], where nil represents the absent value.

func StringSerializer

func StringSerializer() Serializer[string]

StringSerializer returns a Serializer for string values.

func TimestampSerializer

func TimestampSerializer() Serializer[time.Time]

TimestampSerializer returns a Serializer for time.Time values.

func (Serializer[T]) FromBytes

func (s Serializer[T]) FromBytes(b []byte, opts ...KeepUnrecognizedValues) (T, error)

FromBytes deserialises a value from the skir binary wire format, falling back to JSON if the payload lacks the "skir" prefix. Pass KeepUnrecognizedValues{} to preserve fields from a newer schema version.

func (Serializer[T]) FromJson

func (s Serializer[T]) FromJson(code string, opts ...KeepUnrecognizedValues) (T, error)

FromJson deserialises a JSON string into a value of type T. Pass KeepUnrecognizedValues{} to preserve fields from a newer schema version.

func (Serializer[T]) ToBytes

func (s Serializer[T]) ToBytes(v T) []byte

ToBytes serialises v to the skir binary wire format.

func (Serializer[T]) ToJson

func (s Serializer[T]) ToJson(v T, flavor ...Readable) string

ToJson serialises v to a JSON string. Pass Readable{} for human-readable output.

func (Serializer[T]) TypeDescriptor

func (s Serializer[T]) TypeDescriptor() TypeDescriptor

TypeDescriptor returns a descriptor that describes the schema of type T.

type Service

type Service[RequestMeta any] struct {
	// contains filtered or unexported fields
}

Service dispatches Skir RPC requests to registered method implementations. Create one by calling Build on a ServiceBuilder.

RequestMeta is the type of per-request metadata supplied by the HTTP handler (e.g. authenticated user identity, request-scoped logger). Use struct{} if your service does not need metadata.

func (*Service[RequestMeta]) HandleRequest

func (s *Service[RequestMeta]) HandleRequest(ctx context.Context, body string, meta RequestMeta) RawResponse

HandleRequest processes a raw request body and returns a RawResponse. Pass the result directly to RawResponse.ServeHttp to write the HTTP response.

The body argument must be one of:

  • Empty string or "studio": serves Skir Studio (the interactive browser UI).
  • "list": returns a JSON list of all registered methods.
  • A JSON object (starts with '{'): dispatched as a JSON-format RPC call.
  • Any other string: dispatched as a colon-format RPC call ("MethodName:number::requestJson" or "MethodName::requestJson").

If you are using the standard Go HTTP library, prefer Service.HandleRequestFromStandardLib, which extracts the body from an *http.Request automatically. HandleRequest is a lower-level alternative for integrating a SkirRPC service into a different web framework.

func (*Service[RequestMeta]) HandleRequestFromStandardLib

func (s *Service[RequestMeta]) HandleRequestFromStandardLib(r *http.Request, meta RequestMeta) RawResponse

HandleRequestFromStandardLib is like [HandleRequest] but reads the body from an *http.Request.

type ServiceBuilder

type ServiceBuilder[RequestMeta any] struct {
	// KeepUnrecognizedValues instructs the service to preserve fields from a
	// newer schema version that are not recognized by this server. Defaults to
	// false.
	KeepUnrecognizedValues bool

	// CanSendUnknownErrorMessage is called when a non-ServiceError is returned
	// by a method implementation. If it returns true, the raw error message is
	// included in the HTTP 500 response body; otherwise a generic
	// "internal server error" message is used. Defaults to always false, which
	// is the safe default for production services.
	CanSendUnknownErrorMessage func(MethodErrorInfo[RequestMeta]) bool

	// ErrorLogger is called for every error that occurs during request
	// handling. Defaults to writing a one-line message to stderr.
	ErrorLogger func(MethodErrorInfo[RequestMeta])

	// StudioAppJsUrl is the URL of the Skir Studio JavaScript bundle that is
	// served when the request body is empty or "studio".
	StudioAppJsUrl string
	// contains filtered or unexported fields
}

ServiceBuilder configures a Service and registers its method implementations. Call ServiceBuilder.Build to create a Service once all methods have been registered with AddMethod.

Quick-start

1. Implement each method as a plain Go function:

func getUser(
	_ context.Context,
	req svc.GetUserRequest,
	_ struct{},    // replace struct{} with your own metadata type if needed
) (svc.GetUserResponse, error) {
	// ... your logic here ...
}

Optional: to signal a structured error to the caller, you can return a *ServiceError:

return nil, &skir_client.ServiceError{
	StatusCode: skir_client.HttpErrorCode_BadRequest,
	Message:    "user name must not be empty",
}

2. Register all methods and build the service:

b := skir_client.NewServiceBuilder[struct{}]()
skir_client.AddMethod(b, svc.GetUser(), getUser)
skir_client.AddMethod(b, svc.AddUser(), addUser)
service := b.Build()

3. Wire the service into an HTTP handler:

http.HandleFunc("/myapi", func(w http.ResponseWriter, r *http.Request) {
	service.HandleRequestFromStandardLib(r, struct{}{}).ServeHttp(w)
})

func NewServiceBuilder

func NewServiceBuilder[RequestMeta any]() *ServiceBuilder[RequestMeta]

NewServiceBuilder creates a new ServiceBuilder with default values pre-filled.

func (*ServiceBuilder[RequestMeta]) Build

func (b *ServiceBuilder[RequestMeta]) Build() *Service[RequestMeta]

Build creates a Service from this builder.

type ServiceClient

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

ServiceClient sends Skir RPC requests to a remote service.

func NewServiceClient

func NewServiceClient(serviceUrl string, opts ...ServiceClientOption) *ServiceClient

NewServiceClient creates a ServiceClient that sends all requests to serviceUrl.

func (*ServiceClient) Close

func (c *ServiceClient) Close()

Close releases idle connections held by the underlying HTTP client. The ServiceClient must not be used after Close returns.

type ServiceClientOption

type ServiceClientOption func(*ServiceClient)

ServiceClientOption is a functional option for NewServiceClient.

func WithDefaultHeader

func WithDefaultHeader(key, value string) ServiceClientOption

WithDefaultHeader returns a ServiceClientOption that adds a default header sent with every request.

func WithHttpClient

func WithHttpClient(client *http.Client) ServiceClientOption

WithHttpClient returns a ServiceClientOption that replaces the default HTTP client with the provided one, useful for testing with httptest servers or for custom transports (e.g. adding TLS configuration).

type ServiceError

type ServiceError struct {
	// StatusCode is the HTTP error status code.
	StatusCode HttpErrorCode
	// Message is a human-readable explanation that is included in the response
	// body.
	Message string
}

ServiceError is an error that carries an HTTP status code. Method implementations may return a *ServiceError to control the HTTP response sent back to the client. Any other error type is treated as an internal server error (HTTP 500).

func (*ServiceError) Error

func (e *ServiceError) Error() string

type StructDescriptor

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

StructDescriptor describes a skir struct type.

func (*StructDescriptor) AsJson

func (d *StructDescriptor) AsJson() string

func (*StructDescriptor) Doc

func (d *StructDescriptor) Doc() string

func (*StructDescriptor) FieldByName

func (d *StructDescriptor) FieldByName(name string) *StructField

FieldByName returns the field with the given name, or nil if not found.

func (*StructDescriptor) FieldByNumber

func (d *StructDescriptor) FieldByNumber(number int) *StructField

FieldByNumber returns the field with the given number, or nil if not found.

func (*StructDescriptor) Fields

func (d *StructDescriptor) Fields() []*StructField

func (*StructDescriptor) ModulePath

func (d *StructDescriptor) ModulePath() string

func (*StructDescriptor) Name

func (d *StructDescriptor) Name() string

func (*StructDescriptor) QualifiedName

func (d *StructDescriptor) QualifiedName() string

func (*StructDescriptor) RemovedNumbers

func (d *StructDescriptor) RemovedNumbers() map[int]struct{}

type StructField

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

StructField describes a single field of a skir struct.

func (*StructField) Doc

func (f *StructField) Doc() string

func (*StructField) Name

func (f *StructField) Name() string

func (*StructField) Number

func (f *StructField) Number() int

func (*StructField) Type

func (f *StructField) Type() TypeDescriptor

type TypeDescriptor

type TypeDescriptor interface {

	// AsJson returns the complete, self-describing JSON representation of this
	// type descriptor as a compact JSON string.
	AsJson() string
	// contains filtered or unexported methods
}

TypeDescriptor describes a skir type.

The concrete types that implement TypeDescriptor are:

  • *PrimitiveDescriptor
  • *OptionalDescriptor
  • *ArrayDescriptor
  • *StructDescriptor
  • *EnumDescriptor

The unexported method sealTypeDescriptor prevents implementations outside this package.

func ParseTypeDescriptorFromJson

func ParseTypeDescriptorFromJson(jsonCode string) (TypeDescriptor, error)

ParseTypeDescriptorFromJson parses a TypeDescriptor from its JSON string representation (as produced by TypeDescriptor.AsJson).

Jump to

Keyboard shortcuts

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