types

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-backend-types

Types shared by every service in the go-backend-* family, plus a small typed JSON client for service contracts. Standard library only, so any module can import it cheaply.

go get github.com/ahmedbaig/go-backend-types
Type
types.User the gateway's X-User session: id, email, name, roles, features, tenant, impersonator. ParseUser, Header(), Has, HasAny, Can, WithUser / UserFrom / MustUser
types.PageRequest take/skip from query or JSON with validation tags; Limit() (default 20, max 100), Offset()
types.Page[T] {items, total, take, skip}; NewPage, MapPage, HasMore
types.Sort, Direction ?sort=field&order=desc
types.Timestamps embed for createdAt / updatedAt
types.IDRequest, UUIDRequest {id} path parameter with validation
types.ErrorEnvelope, ErrorItem, FieldError the error response every service returns
types.APIError what a client gets back for a non-2xx: status, envelope, Code(), NotFound(), Conflict(), Invalid(), Unauthorized()

Contract clients

A service publishes an api module with its request/response types and a client built on client:

type Client struct{ c *client.Client }

func NewClient(baseURL string, opts ...client.Option) *Client {
	return &Client{c: client.New(baseURL, opts...)}
}

func (c *Client) GetOrder(ctx context.Context, id int64) (Order, error) {
	return client.Get[Order](ctx, c.c, client.Path("/api/v1/orders/{id}", id), nil)
}

client.Get / Post / Put / Patch / Delete encode JSON, turn query:"..." struct fields into the query string, and decode the error envelope into *types.APIError. Options: WithHeader, WithHTTPClient, WithIDs(httpx.IDs) (forward the correlation ID) and ForwardUser() (pass the caller's X-User on).

License

MIT

Documentation

Index

Constants

View Source
const (
	HeaderCorrelationID = "X-Correlation-ID"
	HeaderRequestID     = "X-Request-ID"
)
View Source
const (
	DefaultTake = 20
	MaxTake     = 100
)
View Source
const HeaderUser = "X-User"

Variables

View Source
var ErrNoUser = errors.New("no user in request")

Functions

func WithUser

func WithUser(ctx context.Context, u User) context.Context

Types

type APIError

type APIError struct {
	Status   int
	Envelope ErrorEnvelope
	Body     string
}

func (*APIError) Code

func (e *APIError) Code() string

func (*APIError) Conflict

func (e *APIError) Conflict() bool

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Invalid

func (e *APIError) Invalid() bool

func (*APIError) NotFound

func (e *APIError) NotFound() bool

func (*APIError) Unauthorized

func (e *APIError) Unauthorized() bool

type Direction

type Direction string
const (
	Asc  Direction = "asc"
	Desc Direction = "desc"
)

type Empty

type Empty struct{}

type ErrorEnvelope

type ErrorEnvelope struct {
	RequestID     string      `json:"requestId,omitempty"`
	CorrelationID string      `json:"correlationId,omitempty"`
	Errors        []ErrorItem `json:"errors"`
}

type ErrorItem

type ErrorItem struct {
	Code            string       `json:"code"`
	Message         string       `json:"message"`
	CustomerActions []string     `json:"customerActions,omitempty"`
	SupportActions  []string     `json:"supportActions,omitempty"`
	Fields          []FieldError `json:"fields,omitempty"`
}

type FieldError

type FieldError struct {
	Field   string `json:"field"`
	Rule    string `json:"rule"`
	Message string `json:"message"`
}

type IDRequest

type IDRequest struct {
	ID int64 `path:"id" validate:"required,min=1"`
}

type Page

type Page[T any] struct {
	Items []T   `json:"items"`
	Total int64 `json:"total"`
	Take  int   `json:"take"`
	Skip  int   `json:"skip"`
}

func MapPage

func MapPage[A, B any](p Page[A], fn func(A) B) Page[B]

func NewPage

func NewPage[T any](items []T, total int64, req PageRequest) Page[T]

func (Page[T]) HasMore

func (p Page[T]) HasMore() bool

type PageRequest

type PageRequest struct {
	Take int `query:"take" json:"take,omitempty" validate:"omitempty,min=1,max=100"`
	Skip int `query:"skip" json:"skip,omitempty" validate:"omitempty,min=0"`
}

func (PageRequest) Limit

func (p PageRequest) Limit() int

func (PageRequest) Offset

func (p PageRequest) Offset() int

type Sort

type Sort struct {
	Field     string    `query:"sort" json:"field"`
	Direction Direction `query:"order" json:"direction,omitempty" validate:"omitempty,oneof=asc desc"`
}

type Timestamps

type Timestamps struct {
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

type UUIDRequest

type UUIDRequest struct {
	ID string `path:"id" validate:"required,uuid"`
}

type User

type User struct {
	ID           int64             `json:"id"`
	Email        string            `json:"email,omitempty"`
	Name         string            `json:"name,omitempty"`
	Roles        []string          `json:"roles,omitempty"`
	Features     []string          `json:"features,omitempty"`
	Tenant       string            `json:"tenant,omitempty"`
	Impersonator *int64            `json:"impersonator,omitempty"`
	Claims       map[string]string `json:"claims,omitempty"`
}

func MustUser

func MustUser(ctx context.Context) User

func ParseUser

func ParseUser(header string) (User, error)

func UserFrom

func UserFrom(ctx context.Context) (User, bool)

func (User) Can

func (u User) Can(feature string) bool

func (User) Has

func (u User) Has(role string) bool

func (User) HasAny

func (u User) HasAny(roles ...string) bool

func (User) Header

func (u User) Header() string

func (User) Impersonated

func (u User) Impersonated() bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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