handlers

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2022 License: MIT Imports: 30 Imported by: 1

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	CodeInternalServerError requestContext.ErrorCodes = "Internal server error"
)
View Source
var (
	ContextKeySession = "session"
)
View Source
var (
	ErrApiInternalErrorMissingSession = NewApiError("Missing session", http.StatusBadGateway, string(CodeInternalServerError))
)
View Source
var Ok = models.OkResponse{Ok: boolPointer(true)}

Functions

func AddAccessControl

func AddAccessControl(r *http.Request, rw http.ResponseWriter)

func DiffOfObjects added in v0.8.1

func DiffOfObjects(a, b interface{}) (diff.Changelog, error)

DiffOfObjects returns a changelog with options set for use with for instance i18n-json.

func EndpointsHandler

func EndpointsHandler(
	ctx requestContext.Context,
	userSessions SessionManager,
	pw localuser.PwHasher,
	swaggerYml []byte,
) http.HandlerFunc

Deprecated. Migrating to using httproutermux

func ErrApiDatabase

func ErrApiDatabase(key string, err error) error

func ErrApiInputValidation

func ErrApiInputValidation(msg, key string) error

func ErrApiInternalError added in v0.8.0

func ErrApiInternalError(msg, key string, err error) error

func ErrApiMissingArgument

func ErrApiMissingArgument(key string) error

func ErrApiNotAuthorized

func ErrApiNotAuthorized(key, verb string) error

func ErrApiNotFound

func ErrApiNotFound(key string, input string) error

func ErrApiNotImplemeted added in v0.8.0

func ErrApiNotImplemeted(key string) error

func ExtractParams

func ExtractParams(r *http.Request) (url.Values, error)

Extracts queryparameters from path and query-params. This is useful for caching

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/runar-rkmedia/skiver/handlers"
)

func main() {
	r, _ := http.NewRequest(http.MethodGet, "/api/export/foo=3&feature", nil)
	fmt.Println(handlers.ExtractParams(r))
}
Output:

map[feature:[] foo:[3]] <nil>
Example (Basic)
package main

import (
	"fmt"
	"net/http"

	"github.com/runar-rkmedia/skiver/handlers"
)

func main() {
	r, _ := http.NewRequest(http.MethodGet, "/api/export/?foo=3&feature", nil)
	fmt.Println(handlers.ExtractParams(r))
}
Output:

map[feature:[] foo:[3]] <nil>

func GetParams

func GetParams(r *http.Request) httprouter.Params

func GetRequestSession

func GetRequestSession(r *http.Request) (session types.Session, err error)

func ImportDescriptionsIntoProject added in v0.8.1

func ImportDescriptionsIntoProject(l logger.AppLogger, db types.Storage, createdBy string, project types.Project, dry bool, input map[string]interface{}) (*ImportResult, *Error)

func ImportIntoProject

func ImportIntoProject(
	l logger.AppLogger,
	db types.Storage,
	kind string,
	createdBy string,
	project types.Project,
	localeLike string,

	body []byte,
	r *http.Request,
	opts ...ImportIntoProjectOptions,
) (*ImportResult, *Error)

func NewApiErr

func NewApiErr(err error, statusCode int, code string, details ...interface{}) requestContext.APIError

func NewApiError

func NewApiError(msg string, statusCode int, code string, details ...interface{}) requestContext.APIError

func NewAuthHandler

func NewAuthHandler(
	userSessions SessionManager,
) func(http.ResponseWriter, *http.Request) (*http.Request, error)

func NewWsHandler

func NewWsHandler(l logger.AppLogger, sendChannel chan Msg, options WsOptions) http.HandlerFunc

func PingHandler

func PingHandler(next http.Handler) http.Handler

func StripBeforeLast

func StripBeforeLast(s, sep string) string

Removes the characters before the last occureance of `sep` and the `sep` if available

Example
package main

import (
	"fmt"

	"github.com/runar-rkmedia/skiver/handlers"
)

func main() {
	fmt.Println(handlers.StripBeforeLast("/api/export/foo", "/"))
}
Output:

foo

func UpdateTranslationFromInferrence

func UpdateTranslationFromInferrence(db types.Storage, et types.ExtendedTranslation, additionalValues []AdditionalValue, interpolationMaps []map[string]interface{}) (*types.Translation, error)

updates a Translation based on updates to its values. The additionalValues are meant to be new values to consider for inferrence. If the Translation already has a value for the same LocaleID/Context as an additionalValue, the existing value will not be considered.

func ValidateClientVersion added in v0.8.1

func ValidateClientVersion(rw http.ResponseWriter, r *http.Request) error

temporary check for clients before they upgrade to a version of

Types

type AccessControl

type AccessControl struct {
	AllowOrigin string
	MaxAge      time.Duration
}

type AdditionalValue

type AdditionalValue struct {
	Value    string
	LocaleID string
	Context  string
}

type AppHandler

type AppHandler = func(requestContext.ReqContext, http.ResponseWriter, *http.Request) (interface{}, error)

func ChangePassword

func ChangePassword(db UserStorage, pwKeeper PasswordKeeper, sessionReplace SessionReplacer) AppHandler

func CreateOrganization added in v0.8.0

func CreateOrganization(db types.OrgStorage) AppHandler

func CreateProject added in v0.8.0

func CreateProject(db types.Storage) AppHandler

func CreateToken

func CreateToken(sessionCreator SessionCreator) AppHandler

func CreateTranslation

func CreateTranslation() AppHandler

func DeleteTranslation

func DeleteTranslation() AppHandler

func GetCategory

func GetCategory(db types.Storage) AppHandler

func GetDiff

func GetDiff(exportCache Cache) AppHandler

func GetExport

func GetExport(
	exportCache Cache,
) AppHandler

func GetMissing

func GetMissing(db MissingStorage) AppHandler

func GetOrgForJoinID added in v0.8.0

func GetOrgForJoinID(db types.Storage) AppHandler

func GetOrganization added in v0.8.0

func GetOrganization(db types.OrgStorage) AppHandler

func GetProjects added in v0.8.0

func GetProjects(db types.Storage) AppHandler

func GetServerInfo

func GetServerInfo(sizer Sizer, serverInfo func() *types.ServerInfo) AppHandler

func GetTranslations

func GetTranslations() AppHandler

func JoinOrgFromJoinID added in v0.8.0

func JoinOrgFromJoinID(db types.Storage, pw PasswordKeeper) AppHandler

func ListUsers

func ListUsers(db UserStorage, simpleusers bool) AppHandler

func PostCategory

func PostCategory(db types.Storage) AppHandler

func PostMissing

func PostMissing(db types.Storage) AppHandler

func PostSnapshot

func PostSnapshot(uploaders []uploader.FileUploader) AppHandler

PostSnapshot creates a snapshot if there does not exist one already with the same hash.

func UpdateCategory

func UpdateCategory(db types.Storage) AppHandler

func UpdateOrganization added in v0.8.0

func UpdateOrganization(db types.OrgStorage) AppHandler

func UpdateProject added in v0.8.0

func UpdateProject(db types.Storage) AppHandler

func UpdateTranslation

func UpdateTranslation() AppHandler

type Cache

type Cache interface {
	// Get
	Get(k string) (interface{}, bool)
	Set(k string, x interface{}, d time.Duration)
	SetDefault(k string, x interface{})
}

type CallingClient added in v0.8.1

type CallingClient struct {
	Name    string
	Version string
	GitHash string
	Semver  *semver.Version
}

func GetClientVersionFromRequest added in v0.8.1

func GetClientVersionFromRequest(r *http.Request) (client CallingClient, found bool)

type Client

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

type ClientList

type ClientList struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*ClientList) Subscribe

func (cl *ClientList) Subscribe(c *Client)

func (*ClientList) Unsubscribe

func (cl *ClientList) Unsubscribe(id string)

func (*ClientList) Writer

func (cl *ClientList) Writer(ch chan Msg)

type DiffChangeWithOffset added in v0.8.1

type DiffChangeWithOffset struct {
	diff.Change
	Source *sourcemap.SpanToken `json:"source,omitempty"`
}

type Error

type Error struct {
	models.APIError
	StatusCode int
	Errors     []error
}

func NewError

func NewError(message string, code requestContext.ErrorCodes, details ...interface{}) *Error

func (*Error) AddError

func (e *Error) AddError(err error) *Error

func (Error) Error

func (err Error) Error() string

func (*Error) GetApiError

func (err *Error) GetApiError() models.APIError

func (Error) GetCode

func (err Error) GetCode() requestContext.ErrorCodes

func (Error) GetStatusCode

func (err Error) GetStatusCode() int

type ImportDiff added in v0.8.1

type ImportDiff struct {
	Updates   map[string]DiffChangeWithOffset `json:"updates,omitempty"`
	Creations map[string]DiffChangeWithOffset `json:"creations,omitempty"`
}

type ImportIntoProjectOptions added in v0.8.1

type ImportIntoProjectOptions struct {
	NoDryRun    bool
	ErrOnNoDiff bool
}

type ImportResult

type ImportResult struct {
	Diff      ImportDiff                   `json:"diff,omitempty"`
	ChangeSet []importexport.ChangeRequest `json:"change_set,omitempty"`
	Warnings  []importexport.Warning       `json:"warnings,omitempty"`
}

TODO: Reevaluate this structure.

type MissingStorage

type MissingStorage interface {
	ReportMissing(key types.MissingTranslation) (*types.MissingTranslation, error)
	GetMissingKeysFilter(max int, filter ...types.MissingTranslation) (map[string]types.MissingTranslation, error)
}

type Msg

type Msg struct {
	Kind     string      `json:"kind"`
	Variant  string      `json:"variant,omitempty"`
	Contents interface{} `json:"contents,omitempty"`
}

type PasswordKeeper

type PasswordKeeper interface {
	Verify(hash []byte, pw string) (bool, error)
	Hash(pw string) ([]byte, error)
}

type PubSub

type PubSub struct {
	Ch chan Msg
}

func NewPubSubChannel

func NewPubSubChannel() PubSub

func (*PubSub) Publish

func (ps *PubSub) Publish(kind, variant string, content interface{})

type SessionCreator

type SessionCreator interface {
	NewSession(user types.User, organization types.Organization, userAgent string, opts ...types.UserSessionOptions) (s types.Session)
}

type SessionManager

type SessionManager interface {
	NewSession(user types.User, organization types.Organization, userAgent string, opts ...types.UserSessionOptions) (s types.Session)
	GetSession(token string) (s types.Session, err error)
	SessionsForUser(userId string) (s []types.Session)
	ClearAllSessionsForUser(userId string) error
	ClearSessionById(token string) error
	TTL() time.Duration
}

type SessionReplacer added in v0.8.0

type SessionReplacer interface {
	UpdateAllSessionsForUser(userId string, user types.User) error
}

type Sizer

type Sizer interface {
	Size() (int64, error)
}

type Updates

type Updates struct {
	TranslationValueUpdates    map[string]types.TranslationValue
	TranslationsValueCreations map[string]types.TranslationValue
	TranslationCreations       map[string]types.Translation
	CategoryCreations          map[string]types.Category
}

type UserStorage

type UserStorage interface {
	FindUsers(max int, filter ...types.User) (map[string]types.User, error)
	UpdateUser(id string, payload types.UpdateUserPayload) (types.User, error)
	GetUser(userId string) (*types.User, error)
}

type WsOptions

type WsOptions struct {
	PingInterval,
	WriteTimeout time.Duration
}

Jump to

Keyboard shortcuts

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