Documentation ¶
Overview ¶
Package lys is used for rapid development of REST APIs handling database CRUD actions.
Please see the README and wiki for an overview.
Index ¶
- Constants
- func AuthorizeRole(allowedRoles []string) func(http.Handler) http.Handler
- func DecodeJsonBody[T any](body []byte) (dest T, err error)
- func Delete(env Env, store iDeletable) http.HandlerFunc
- func ExtractFields(r *http.Request, validJsonFields []string, fieldsReqParamName string) (fields []string, err error)
- func ExtractFilters(urlValues url.Values, validJsonFields []string, getOptions GetOptions) (conds []lyspg.Condition, err error)
- func ExtractJsonBody(r *http.Request, maxBodySize int64) (body []byte, err error)
- func ExtractPaging(r *http.Request, pageReqParamName, perPageReqParamName string, ...) (page int, perPage int, err error)
- func ExtractSorts(r *http.Request, validJsonFields []string, sortReqParamName string) (sortCols []string, err error)
- func Get[T any](env Env, store iGetable[T]) http.HandlerFunc
- func GetById[T any](env Env, store iGetablebyId[T]) http.HandlerFunc
- func GetByUuid[T any](env Env, store iGetablebyUuid[T]) http.HandlerFunc
- func GetEnumValues(env Env, db *pgxpool.Pool, schema, enum string) http.HandlerFunc
- func GetSimple[T any](env Env, ...) http.HandlerFunc
- func GetUserNameFromCtx(ctx context.Context, defaultVal string) string
- func HandleDbError(ctx context.Context, stmt string, err error, errorLog *slog.Logger, ...)
- func HandleInternalError(ctx context.Context, err error, errorLog *slog.Logger, w http.ResponseWriter)
- func HandlePostgresError(ctx context.Context, stmt, callerFunc string, pgErr *pgconn.PgError, ...)
- func HandleUserError(statusCode int, userErrMsg string, w http.ResponseWriter)
- func JsonResponse(resp StdResponse, httpStatus int, headers []RespHeader, w http.ResponseWriter)
- func Message(msg string) http.HandlerFunc
- func MoveRecordsById(env Env, db *pgxpool.Pool, ...) http.HandlerFunc
- func NotFound() http.HandlerFunc
- func Patch(env Env, store iPatchable) http.HandlerFunc
- func PgSleep(db lyspg.PoolOrTx, errorLog *slog.Logger, secs int) http.HandlerFunc
- func Post[inputT any, itemT any](env Env, store iPostable[inputT, itemT]) http.HandlerFunc
- func Put[T any](env Env, store iPutable[T]) http.HandlerFunc
- func Restore(env Env, db *pgxpool.Pool, store iSoftDeletable) http.HandlerFunc
- func SoftDelete(env Env, db *pgxpool.Pool, store iSoftDeletable) http.HandlerFunc
- type Env
- type GetOptions
- type GetReqModifiers
- type PostOptions
- type ReqUserInfo
- type RespHeader
- type RouteAdderFunc
- type StdResponse
- type SubRoute
Constants ¶
const ( ErrDescBodyMissing string = "request body missing" ErrDescIdMissing string = "id missing" ErrDescIdNotAUuid string = "id not a uuid" ErrDescIdNotAnInteger string = "id not an integer" ErrDescIdNotUnique string = "id not unique" // the handling func was expecting id to be unique, but it is not ErrDescInvalidContentType string = "content type must be application/json" ErrDescInvalidId string = "invalid id" // the Id sent is not present in the relevant table ErrDescRouteNotFound string = "route not found" ErrDescUserInfoMissing string = "userInfo missing" // failed to get ReqUserInfo from context ErrDescPermissionDenied string = "permission denied" // authorization failed )
validation user errors
const ( // status ReqSucceeded string = "succeeded" ReqFailed string = "failed" // data DataDeleted string = "deleted" DataSoftDeleted string = "soft-deleted" DataRestored string = "restored" DataUpdated string = "updated" )
response constants
const ReqUserInfoCtxKey contextKey = "ReqUserInfoKey"
ReqUserInfoCtxKey is the key to be used when binding a ReqUserInfo to a request via context
Variables ¶
This section is empty.
Functions ¶
func AuthorizeRole ¶
AuthorizeRole is middleware that checks that the user has one of the supplied allowedRoles is intended for use in subroutes
func DecodeJsonBody ¶
DecodeJsonBody decodes the supplied json body into dest and checks for a variety of error conditions adapted from https://www.alexedwards.net/blog/how-to-properly-parse-a-json-request-body
func Delete ¶
func Delete(env Env, store iDeletable) http.HandlerFunc
Delete handles deletion of a single item using the supplied store
func ExtractFields ¶
func ExtractFields(r *http.Request, validJsonFields []string, fieldsReqParamName string) (fields []string, err error)
ExtractFields returns a slice of strings parsed from the request's fields param
func ExtractFilters ¶
func ExtractFilters(urlValues url.Values, validJsonFields []string, getOptions GetOptions) (conds []lyspg.Condition, err error)
ExtractFilters returns a slice of conditions parsed from the request's params to get urlValues from a request: r.Url.Query()
func ExtractJsonBody ¶
ExtractJsonBody reads and validates the body of the supplied request
func ExtractPaging ¶
func ExtractPaging(r *http.Request, pageReqParamName, perPageReqParamName string, defaultPerPage, maxPerPage int) (page int, perPage int, err error)
ExtractPaging returns paging variables parsed from a request's paging params page defaults to 1, perPage defaults to defaultPerPage
func ExtractSorts ¶
func ExtractSorts(r *http.Request, validJsonFields []string, sortReqParamName string) (sortCols []string, err error)
ExtractSorts returns an array of SQL sorting statements parsed from the request's sort param
func Get ¶
func Get[T any](env Env, store iGetable[T]) http.HandlerFunc
Get handles retrieval of multiple items from the supplied store
func GetById ¶
func GetById[T any](env Env, store iGetablebyId[T]) http.HandlerFunc
GetById handles retrieval of a single item from the supplied store using an integer id
func GetByUuid ¶
func GetByUuid[T any](env Env, store iGetablebyUuid[T]) http.HandlerFunc
GetByUuid handles retrieval of a single item from the supplied store using a text id
func GetEnumValues ¶
GetEnumValues returns enum values from the supplied schema and enum type name
func GetSimple ¶
func GetSimple[T any](env Env, selectFunc func(ctx context.Context) (items []T, stmt string, err error)) http.HandlerFunc
GetSimple handles retrieval of all items returned by selectFunc, which may only take ctx as param
func HandleDbError ¶
func HandleDbError(ctx context.Context, stmt string, err error, errorLog *slog.Logger, w http.ResponseWriter)
HandleDbError returns a generic error message to the API user and includes the failing statement in the error log
func HandleInternalError ¶
func HandleInternalError(ctx context.Context, err error, errorLog *slog.Logger, w http.ResponseWriter)
HandleInternalError returns a generic error message to the API user and logs the error
func HandlePostgresError ¶
func HandlePostgresError(ctx context.Context, stmt, callerFunc string, pgErr *pgconn.PgError, errorLog *slog.Logger, w http.ResponseWriter)
HandlePostgresError handles an error that is of type PgError
func HandleUserError ¶
func HandleUserError(statusCode int, userErrMsg string, w http.ResponseWriter)
HandleUserError returns a helpful message to the API user, but does not log the error
func JsonResponse ¶
func JsonResponse(resp StdResponse, httpStatus int, headers []RespHeader, w http.ResponseWriter)
JsonResponse writes the supplied params to w
func Message ¶
func Message(msg string) http.HandlerFunc
Message returns the supplied msg in the Data field
func MoveRecordsById ¶
func MoveRecordsById(env Env, db *pgxpool.Pool, moveFunc func(context.Context, pgx.Tx, int64) (string, error), msg string) http.HandlerFunc
MoveRecordsById handles moving record(s) back and forth between the main table and its corresponding deleted table
func NotFound ¶
func NotFound() http.HandlerFunc
NotFound provides a response informing the user that the requested route was not found
func Patch ¶
func Patch(env Env, store iPatchable) http.HandlerFunc
Patch handles changing some of an item's fields using the supplied store
func PgSleep ¶
PgSleep creates an artifical longrunning query in the db which can be viewed using pg_stat_activity used for testing context cancelation
func Post ¶
func Post[inputT any, itemT any](env Env, store iPostable[inputT, itemT]) http.HandlerFunc
Post handles creating a new item using the supplied store and returning it in the response
func Put ¶
func Put[T any](env Env, store iPutable[T]) http.HandlerFunc
Put handles changing an item using the supplied store
func Restore ¶
func Restore(env Env, db *pgxpool.Pool, store iSoftDeletable) http.HandlerFunc
Restore handles moving a record from the store's deleted table back to the main table
func SoftDelete ¶
func SoftDelete(env Env, db *pgxpool.Pool, store iSoftDeletable) http.HandlerFunc
SoftDelete handles moving a record from the supplied store into its deleted table
Types ¶
type Env ¶
type Env struct { ErrorLog *slog.Logger Validate *validator.Validate GetOptions GetOptions PostOptions PostOptions }
Env (environment) contains objects and options needed by API calls
type GetOptions ¶
type GetOptions struct { FieldsParamName string // param name to limit the fields returned by a GET request, e.g. "xfields" PageParamName string // param name to define the page offset returned by a GET request, e.g. "xpage" PerPageParamName string // param name to define the number of records returned by a GET request, e.g. "xper_page" SortParamName string // param name to identify the sort param used by a GET request, e.g. "xsort" MultipleValueSeparator string // the string used by a GET request to separate values in a filter where each value should be returned, e.g. "|", usage: "name=Bill|Sam" DefaultPerPage int // default number of results returned by a GET request, e.g. 20 DefaultMaxPerPage int // default max number of results returned per GET request, regardless of what the caller enters in the "PerPageParamName" param, e.g. 500 }
GetOptions contains the options used when processing GET requests, such as paging param names and default values Since the json field names are used as filters, param names should be chosen which will never appear as json field names
func FillGetOptions ¶
func FillGetOptions(input GetOptions) (ret GetOptions)
FillGetOptions returns input GetOptions if they are passed, and sets any unset fields to a sensible default value
type GetReqModifiers ¶
type GetReqModifiers struct { Fields []string Conditions []lyspg.Condition Page int PerPage int Sorts []string }
GetReqModifiers contains data from a GET request's Url params which is used to modify a database SELECT statement
func ExtractGetRequestModifiers ¶
func ExtractGetRequestModifiers(r *http.Request, validJsonFields []string, getOptions GetOptions) (getReqModifiers GetReqModifiers, err error)
ExtractGetRequestModifiers reads the Url params of the supplied GET request and converts them into a GetReqModifiers
type PostOptions ¶
type PostOptions struct {
MaxBodySize int64 // bytes
}
PostOptions contains the options used when processing POST or PUT requests
func FillPostOptions ¶
func FillPostOptions(input PostOptions) (ret PostOptions)
FillPostOptions returns input PostOptions if they are passed, and sets any unset fields to a sensible default value
type ReqUserInfo ¶
type ReqUserInfo struct { Roles []string `json:"roles"` UserId int64 `json:"user_id"` UserName string `json:"user_name"` }
ReqUserInfo contains data about the API user which is added to request context after authentication
type RespHeader ¶
RespHeader contains the data in a HTTP reponse header
type RouteAdderFunc ¶
RouteAdderFunc is a function returning a subrouter
type StdResponse ¶
type StdResponse struct { Status string `json:"status"` Data any `json:"data,omitempty"` ErrType string `json:"err_type,omitempty"` ErrDescription string `json:"err_description,omitempty"` ExternalMessage string `json:"external_message,omitempty"` // user-readable messages passed on from 3rd party API calls }
StdResponse is the return type of all API routes
type SubRoute ¶
type SubRoute struct { Url string RouteAdder RouteAdderFunc }
SubRoute contains a Url path and the function returning the subrouter to process that path
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
internal
|
|
Package lysclient contains types and functions to help test a REST API which was created using lys functions.
|
Package lysclient contains types and functions to help test a REST API which was created using lys functions. |
Package lyserr contains structs related to error handling used in lys and lyspg.
|
Package lyserr contains structs related to error handling used in lys and lyspg. |
Package lysgen contains experimental functions to generate code from Postgres database tables.
|
Package lysgen contains experimental functions to generate code from Postgres database tables. |
Package lysmeta contains functions that analyze structs.
|
Package lysmeta contains functions that analyze structs. |
Package lyspg contains structs and functions providing generic CRUD operations on a Postgres database.
|
Package lyspg contains structs and functions providing generic CRUD operations on a Postgres database. |
Package lyspgdb contains functions for creating and monitoring Postgres databases.
|
Package lyspgdb contains functions for creating and monitoring Postgres databases. |
Package lysstring contains string functions.
|
Package lysstring contains string functions. |
Package lystype contains date/time types used in lys and lyspg.
|
Package lystype contains date/time types used in lys and lyspg. |