weoscontroller

package module
v0.0.1-alpha Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2021 License: Apache-2.0 Imports: 32 Imported by: 1

README

README

The Controller is meant to handle incoming requests and route to the appropriate business login

What is this repository for?
  • Version: 0.1.0
How do I get set up?

This module should be imported into an api and initialized.

go get github.com/wepala/weos-controller

Then setup a configuration file api.yaml for example

openapi: 3.0.2
info:
  title: WeOS REST API
  version: 1.0.0
  description:  REST API for passing information into WeOS

x-weos-config:
  session:
    key: "${SESSION_KEY}"
    path: ""
  logger:
    level: ${LOG_LEVEL}
    report-caller: true
    formatter: ${LOG_FORMAT}
  applicationId: ${APPLICATION_ID}
  applicationTitle: ${APPLICATION_TITLE}
  accountId: ${ACCOUNT_ID}
  database:
    host: ${POSTGRES_HOST}
    database: ${POSTGRES_DB}
    username: ${POSTGRES_USER}
    password: ${POSTGRES_PASSWORD}
    port: ${POSTGRES_PORT}
  middleware:
    - RequestID
    - Recover
    - Static
  jwtConfig:
    key: ${JWT_KEY}
    tokenLookup: ${JWT_LOOKUP}
    claims: 
      email: string
      real: bool
    authScheme: ${JWT_SCHEME}
    contextKey: ${JWT_CONTEXT}
    signingMethod: ${JWT_SIGNING_METHOD}

paths:
  /health:
    summary: Health Check
    get:
      x-weos-config:
        handler: HealthChecker
      responses:
        "200":
          description: Health Response
        "500":
          description: API Internal Error
  /admin:
    summary: Admin Endpoint
    get:
      x-weos-config:
        group: True
        middleware:
          - Static
      responses:
        200:
          description: Admin Endpoint

NB: The content of the yaml can also be passed into the Initialize method

Config Explained

The configuration uses the OAS 3.0 api specification. Using a standard format allows us to take advantage of the rich tooling that is available. WeOS specific configuration can be found under the weos specific configuration extension x-weos-config. When this extension is applied to a path, the configuration details is available as a path config.

Mock Responses

Getting mock responses couldn't be easier.

Mock Setup

THIS IS CURRENTLY NOT SETUP FOR THE NEW DIRECTION

In your api yaml there are a couple ways you can setup mock responses;

  1. Don't configure the path with a x-weos-config (it will automatically return example responses you have defined on the path or on the component schema of the response)
  2. Setup a sub property mock to true on the x-weos-config

Example Mock Config

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Basic Site
paths:
  /:
    get:
      summary: Landing page of the site
      responses:
        '200':
          description: Landing page
          content:
            text/html:
              example: test
              schema:
                type: string
  /about:
    get:
      summary: About Page
      x-weos-config:
        mock: true
        handler: HelloWorld
      responses:
        '200':
          description: About Page
          content:
            text/html:
              example: test
              schema:
                type: string

You can define mocks in a few ways

  1. example under content in the response
  2. examples these are named examples
  3. example on the component

Read more about examples in swagger - https://swagger.io/docs/specification/adding-examples/

Mock Request

There are a few options you can use when making a mock request

  1. X-Mock-Status-Code - Use this to specify the response code you'd like to receive (this is if the path has multiple responses defined)
  2. X-Mock-Example - Use this to specify which example should be used (this is when the examples option is used on the response)
  3. X-Mock-Example-Length - Use this to specify the amount of items to return (this is useful when the response is an array)
  4. X-Mock-Content-Type - Use this to specify the content type desired. (This is required if there are multiple content types defined)
Contribution guidelines

This project uses gitflow workflow

  • Clone the repo to local
  • Create feature branch from dev branch (e.g. feature/WEOS-1)
  • Push the feature branch to the remote
  • Create PR from the ticket branch to dev branch
  • When the item is merged to master it will be deployed

To aid with this use the git flow cli (you will be able to create feature branches e.g. git flow feature start APO-1)

New Features
Who do I talk to?

Documentation

Index

Constants

View Source
const HeaderXAccountID = "X-Account-ID"

Handlers container for all handlers

Variables

View Source
var (
	// DefaultStaticConfig is the default Static middleware config.
	DefaultStaticConfig = StaticConfig{
		Skipper: middleware.DefaultSkipper,
		Index:   "index.html",
	}
)

Functions

func Initialize

func Initialize(e *echo.Echo, api APIInterface, apiConfig string) *echo.Echo

func LoadHttpRequestFixture

func LoadHttpRequestFixture(filename string) (*http.Request, error)

LoadHttpRequestFixture wrapper around the test helper to make it easier to use it with test table

func LoadHttpResponseFixture

func LoadHttpResponseFixture(filename string, req *http.Request) (*http.Response, error)

LoadHttpResponseFixture wrapper around the test helper to make it easier to use it with test table

func MultiWriter

func MultiWriter(writers ...http.ResponseWriter) http.ResponseWriter

MultiWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command.

Each write is written to each listed writer, one at a time. If a listed writer returns an error, that overall write operation stops and returns the error; it does not continue down the list.

func NewControllerError

func NewControllerError(message string, err error, code int) *echo.HTTPError

func NewLogger

func NewLogger(l echo.Logger) log.Ext1FieldLogger

func NewRespBodyFromBytes

func NewRespBodyFromBytes(body []byte) io.ReadCloser

NewRespBodyFromBytes creates an io.ReadCloser from a byte slice that is suitable for use as an http response body.

func Static

func Static(root string) echo.MiddlewareFunc

Static returns a Static middleware to serves static content from the provided root directory.

func StaticWithConfig

func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc

StaticWithConfig returns a Static middleware with config. See `Static()`.

Types

type API

type API struct {
	Config *APIConfig

	PathConfigs map[string]*PathConfig
	// contains filtered or unexported fields
}

func (*API) AccountID

func (p *API) AccountID(next echo.HandlerFunc) echo.HandlerFunc

func (*API) AddConfig

func (p *API) AddConfig(config *APIConfig) error

func (*API) AddPathConfig

func (p *API) AddPathConfig(path string, config *PathConfig) error

func (*API) Authenticate

func (a *API) Authenticate(handlerFunc echo.HandlerFunc) echo.HandlerFunc

Functionality to check claims will be added here

func (*API) Context

func (p *API) Context(next echo.HandlerFunc) echo.HandlerFunc

func (*API) EchoInstance

func (p *API) EchoInstance() *echo.Echo

func (*API) HTTPSRedirect

func (p *API) HTTPSRedirect(handlerFunc echo.HandlerFunc) echo.HandlerFunc

func (*API) HealthChecker

func (p *API) HealthChecker(c echo.Context) error

func (*API) Initialize

func (p *API) Initialize() error

func (*API) LogLevel

func (p *API) LogLevel(next echo.HandlerFunc) echo.HandlerFunc

func (*API) Logger

func (p *API) Logger(handlerFunc echo.HandlerFunc) echo.HandlerFunc

func (*API) Recover

func (p *API) Recover(handlerFunc echo.HandlerFunc) echo.HandlerFunc

func (*API) RequestID

func (p *API) RequestID(next echo.HandlerFunc) echo.HandlerFunc

func (*API) RequestRecording

func (p *API) RequestRecording(next echo.HandlerFunc) echo.HandlerFunc

func (*API) ResponseRecording

func (p *API) ResponseRecording(next echo.HandlerFunc) echo.HandlerFunc

func (*API) SetEchoInstance

func (p *API) SetEchoInstance(e *echo.Echo)

func (*API) Static

func (p *API) Static(handlerFunc echo.HandlerFunc) echo.HandlerFunc

func (*API) UserID

func (p *API) UserID(next echo.HandlerFunc) echo.HandlerFunc

type APIConfig

type APIConfig struct {
	*weos.ApplicationConfig
	BasePath            string `json:"basePath" ,yaml:"basePath"`
	RecordingBaseFolder string
	Middleware          []string        `json:"middleware"`
	PreMiddleware       []string        `json:"pre-middleware"`
	JWTConfig           *JWTConfig      `json:"jwtConfig"`
	Config              json.RawMessage `json:"config"`
}

type APIInterface

type APIInterface interface {
	AddPathConfig(path string, config *PathConfig) error
	AddConfig(config *APIConfig) error
	Initialize() error
	EchoInstance() *echo.Echo
	SetEchoInstance(e *echo.Echo)
}

define an interface that all plugins must implement

type Context

type Context struct {
	echo.Context
	// contains filtered or unexported fields
}

func (*Context) RequestContext

func (c *Context) RequestContext() context.Context

func (*Context) WithValue

func (c *Context) WithValue(parent *Context, key, val interface{}) *Context

type JWTConfig

type JWTConfig struct {
	Key             string                 `json:"key"`         //Signing key needed for validating token
	SigningKeys     map[string]interface{} `json:"signingKeys"` //Key map used for validating token.  Can be used in place of a single key
	Certificate     []byte                 `json:"certificate"`
	CertificatePath string                 `json:"certificatePath"` //Path the signing certificate used to validate token.  Can  be used in place of a key
	JWKSUrl         string                 `json:"jwksUrl"`         //URL to JSON Web Key set.  Can be used in place of a Key
	TokenLookup     string                 `json:"tokenLookup"`
	Claims          map[string]interface{} `json:"claims"`
	AuthScheme      string                 `json:"authScheme"`
	ContextKey      string                 `json:"contextKey"`
	SigningMethod   string                 `json:"signingMethod"`
}

type LoggerWrapper

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

LoggerWrapper makes a WeOS compatible logger

func (LoggerWrapper) Debug

func (l LoggerWrapper) Debug(args ...interface{})

func (LoggerWrapper) Debugf

func (l LoggerWrapper) Debugf(format string, args ...interface{})

func (LoggerWrapper) Debugln

func (l LoggerWrapper) Debugln(args ...interface{})

func (LoggerWrapper) Error

func (l LoggerWrapper) Error(args ...interface{})

func (LoggerWrapper) Errorf

func (l LoggerWrapper) Errorf(format string, args ...interface{})

func (LoggerWrapper) Errorln

func (l LoggerWrapper) Errorln(args ...interface{})

func (LoggerWrapper) Fatal

func (l LoggerWrapper) Fatal(args ...interface{})

func (LoggerWrapper) Fatalf

func (l LoggerWrapper) Fatalf(format string, args ...interface{})

func (LoggerWrapper) Fatalln

func (l LoggerWrapper) Fatalln(args ...interface{})

func (LoggerWrapper) Info

func (l LoggerWrapper) Info(args ...interface{})

func (LoggerWrapper) Infof

func (l LoggerWrapper) Infof(format string, args ...interface{})

func (LoggerWrapper) Infoln

func (l LoggerWrapper) Infoln(args ...interface{})

func (LoggerWrapper) Panic

func (l LoggerWrapper) Panic(args ...interface{})

func (LoggerWrapper) Panicf

func (l LoggerWrapper) Panicf(format string, args ...interface{})

func (LoggerWrapper) Panicln

func (l LoggerWrapper) Panicln(args ...interface{})

func (LoggerWrapper) Print

func (l LoggerWrapper) Print(args ...interface{})

func (LoggerWrapper) Printf

func (l LoggerWrapper) Printf(format string, args ...interface{})

func (LoggerWrapper) Println

func (l LoggerWrapper) Println(args ...interface{})

func (LoggerWrapper) Trace

func (l LoggerWrapper) Trace(args ...interface{})

func (LoggerWrapper) Tracef

func (l LoggerWrapper) Tracef(format string, args ...interface{})

func (LoggerWrapper) Traceln

func (l LoggerWrapper) Traceln(args ...interface{})

func (LoggerWrapper) Warn

func (l LoggerWrapper) Warn(args ...interface{})

func (LoggerWrapper) Warnf

func (l LoggerWrapper) Warnf(format string, args ...interface{})

func (LoggerWrapper) Warning

func (l LoggerWrapper) Warning(args ...interface{})

func (LoggerWrapper) Warningf

func (l LoggerWrapper) Warningf(format string, args ...interface{})

func (LoggerWrapper) Warningln

func (l LoggerWrapper) Warningln(args ...interface{})

func (LoggerWrapper) Warnln

func (l LoggerWrapper) Warnln(args ...interface{})

func (LoggerWrapper) WithError

func (l LoggerWrapper) WithError(err error) *log.Entry

func (LoggerWrapper) WithField

func (l LoggerWrapper) WithField(key string, value interface{}) *log.Entry

func (LoggerWrapper) WithFields

func (l LoggerWrapper) WithFields(fields log.Fields) *log.Entry

type PathConfig

type PathConfig struct {
	Handler        string          `json:"handler" ,yaml:"handler"`
	Group          bool            `json:"group" ,yaml:"group"`
	Middleware     []string        `json:"middleware"`
	Config         json.RawMessage `json:"config"`
	DisableCors    bool            `json:"disable-cors"`
	AllowedHeaders []string        `json:"allowed-headers" ,yaml:"allowed-headers"`
	AllowedOrigins []string        `json:"allowed-origins" ,yaml:"allowed-origins"`
}

type StaticConfig

type StaticConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper

	// Root directory from where the static content is served.
	// Required.
	Root string `yaml:"root"`

	// Index file for serving a directory.
	// Optional. Default value "index.html".
	Index string `yaml:"index"`

	// Enable HTML5 mode by forwarding all not-found requests to root so that
	// SPA (single-page application) can handle the routing.
	// Optional. Default value false.
	HTML5 bool `yaml:"html5"`

	// Enable directory browsing.
	// Optional. Default value false.
	Browse bool `yaml:"browse"`

	// Enable ignoring of the base of the URL path.
	// Example: when assigning a static middleware to a non root path group,
	// the filesystem path is not doubled
	// Optional. Default value false.
	IgnoreBase bool `yaml:"ignoreBase"`
	FileSystem *embed.FS
}

StaticConfig defines the config for Static middleware.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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