ign

package module
v2.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2018 License: Apache-2.0 Imports: 38 Imported by: 13

README

Ignition GO

Ignition GO is a general purpose golang library that encapsulates a set of common functionality for a webserver. An example webserver that utilizes Ignition GO is Ignition Fuel.

Test coverage: codecov

Go version

Ignition GO is currently using go 1.9.4

Environment variables

Ignition GO utilizes a set of environment variables for configuration purposes.

  1. IGN_SSL_CERT : Path to an SSL certificate file. This is used for local SSL testing and development.
  2. IGN_SSL_KEY : Path to an SSL key. THis is used for local SSL testing and development
  3. IGN_DB_USERNAME : Username for the database connection.
  4. IGN_DB_PASSWORD : Password for the database connection.
  5. IGN_DB_ADDRESS : URL address for the database server.
  6. IGN_DB_NAME : Name of the database to use on the database sever.
  7. IGN_DB_MAX_OPEN_CONNS : Max number of open connections in connections pool. A value <= 0 means unlimited connections.
  8. IGN_GA_TRACKING_ID : Google Analytics Tracking ID to use. If not set, then GA will not be enabled. The format is UA-XXXX-Y.
  9. IGN_GA_APP_NAME : Google Analytics Application Name. If not set, then GA will not be enabled.
  10. IGN_GA_CAT_PREFIX : (optional) A string to use as a prefix to Google Analytics Event Category.
  11. IGN_ROLLBAR_TOKEN: (optional) Rollbar authentication token. If valid, then log messages will be sent to rollbar.com. It is recommended NOT to use rollbar during local development.
  12. IGN_ROLLBAR_ENV: (optional) Rollbar environment string, such as "staging" or "production".
  13. IGN_ROLLBAR_ROOT: (optional) Path to the application code root, not including the final slash. Such as bitbucket.org/ignitionrobotics/ign-fuelserver

Testing with Ignition GO

Database

Ignition GO creates a separate test database to prevent data corruption. This database is named <DB_Name>_test, where <DB_Name> is your application's default database name which is usually equivalent to the IGN_DB_NAME environment variable.

Documentation

Index

Constants

View Source
const ErrorAuthJWTInvalid = 4001

ErrorAuthJWTInvalid is triggered when is not possible to get a user ID from the JWT in the request

View Source
const ErrorAuthNoUser = 4000

ErrorAuthNoUser is triggered when there's no user in the database with the claimed user ID.

View Source
const ErrorCreatingDir = 100002

ErrorCreatingDir is triggered when the server was unable to create a new directory for a resource (no space on device or a temporary server problem).

View Source
const ErrorCreatingFile = 100004

ErrorCreatingFile is triggered when the server was unable to create a new file for a resource (no space on device or a temporary server problem).

View Source
const ErrorCreatingRepo = 100003

ErrorCreatingRepo is triggered when the server was unable to create a new repository for a resource (no space on device or a temporary server problem).

View Source
const ErrorDbDelete = 1001

ErrorDbDelete is triggered when the database was unable to delete a resource

View Source
const ErrorDbSave = 1002

ErrorDbSave is triggered when the database was unable to save a resource

View Source
const ErrorFileNotFound = 1005

ErrorFileNotFound is triggered when a model's file with the specified name is not found

View Source
const ErrorFileTree = 100009

ErrorFileTree is triggered when there was a problem accessing the model's files.

View Source
const ErrorForm = 3004

ErrorForm is triggered when an expected field is missing in a multipart form request.

View Source
const ErrorFormDuplicateFile = 3014

ErrorFormDuplicateFile is triggered when the POSTed model carries duplicate file entries.

View Source
const ErrorFormDuplicateModelName = 3015

ErrorFormDuplicateModelName is triggered when the POSTed model carries duplicate model name.

View Source
const ErrorFormInvalidValue = 3013

ErrorFormInvalidValue is triggered when a given form field has an invalid value.

View Source
const ErrorFormMissingFiles = 3012

ErrorFormMissingFiles is triggered when the expected "file" field is missing in the multipart form request.

View Source
const ErrorIDNotFound = 1003

ErrorIDNotFound is triggered when a resource with the specified id is not found in the database

View Source
const ErrorIDNotInRequest = 3000

ErrorIDNotInRequest is triggered when a id is not found in the request

View Source
const ErrorIDWrongFormat = 3001

ErrorIDWrongFormat is triggered when an id is not in a valid format

View Source
const ErrorInvalidPaginationRequest = 3016

ErrorInvalidPaginationRequest is triggered when the requested pagination is invalid. eg. invalid page or per_page argument values.

View Source
const ErrorMarshalJSON = 2000

ErrorMarshalJSON is triggered if there is an error marshalling data into JSON

View Source
const ErrorMarshalProto = 2500

ErrorMarshalProto is triggered if there is an error marshalling data into protobuf

View Source
const ErrorMissingField = 3009

ErrorMissingField is triggered when the JSON contained in a request does not contain one or more required fields

View Source
const ErrorModelNotInRequest = 3011

ErrorModelNotInRequest is triggered when a model is not found in the request

View Source
const ErrorNameNotFound = 1004

ErrorNameNotFound is triggered when a resource with the specified name is not found in the database

View Source
const ErrorNameWrongFormat = 3002

ErrorNameWrongFormat is triggered when a name is not in a valid format

View Source
const ErrorNoDatabase = 1000

ErrorNoDatabase is triggered when the database connection is unavailable

View Source
const ErrorNonExistentResource = 100006

ErrorNonExistentResource is triggered when the server was unable to find a resource.

View Source
const ErrorOwnerNotInRequest = 3010

ErrorOwnerNotInRequest is triggered when an owner is not found in the request

View Source
const ErrorPaginationPageNotFound = 3017

ErrorPaginationPageNotFound is triggered when the requested page is empty / not found.

View Source
const ErrorPayloadEmpty = 3003

ErrorPayloadEmpty is triggered when payload is expected but is not found in the request

View Source
const ErrorRemovingDir = 100008

ErrorRemovingDir is triggered when the server was unable to remove a directory.

View Source
const ErrorRepo = 100007

ErrorRepo is triggered when the server was unable to handle repo command.

View Source
const ErrorResourceExists = 100001

ErrorResourceExists is triggered when the server cannot create a new resource because the requested id already exists. E.g.: When the creation of a new model is requested but the server already has a model with the same id.

View Source
const ErrorUnauthorized = 4002

ErrorUnauthorized is triggered when a user is not authorized to perform a given action.

View Source
const ErrorUnexpectedID = 3005

ErrorUnexpectedID is triggered when the id of a file attached in a request is not expected. E.g.: When the attached world file does not end in ".world" during a world creation request.

View Source
const ErrorUnknownSuffix = 3006

ErrorUnknownSuffix is triggered when a suffix for content negotiation is not recognized.

View Source
const ErrorUnmarshalJSON = 2001

ErrorUnmarshalJSON is triggered if there is an error unmarshalling JSON

View Source
const ErrorUnzipping = 100005

ErrorUnzipping is triggered when the server was unable to unzip a zipped file

View Source
const ErrorUserNotInRequest = 3007

ErrorUserNotInRequest is triggered when the user/team is not found in the request.

View Source
const ErrorUserUnknown = 3008

ErrorUserUnknown is triggered when the user/team does not exist on the server

View Source
const ErrorZipNotAvailable = 100000

ErrorZipNotAvailable is triggered when the server does not have a zip file for the requested resource

Variables

View Source
var AuthHeadersOptional = []Header{
	{
		Name: "authorization: Bearer <YOUR_JWT_TOKEN>",
		HeaderDetails: Detail{
			Required: false,
		},
	},
}

AuthHeadersOptional is an array of Headers needed when authentication is optional.

View Source
var AuthHeadersRequired = []Header{
	{
		Name: "authorization: Bearer <YOUR_JWT_TOKEN>",
		HeaderDetails: Detail{
			Required: true,
		},
	},
}

AuthHeadersRequired is an array of Headers needed when authentication is required.

Functions

func Critical

func Critical(interfaces ...interface{})

Critical sends a critical message to rollbar. The valid types are:

*http.Request error string map[string]interface{} int ign.ErrMsg

func Debug

func Debug(interfaces ...interface{})

Debug sends a debug message to rollbar. The valid types are:

*http.Request error string map[string]interface{} int ign.ErrMsg

func Error

func Error(interfaces ...interface{})

Error sends an error message to rollbar. The valid types are:

*http.Request error string map[string]interface{} int ign.ErrMsg

func GetUserIdentity

func GetUserIdentity(r *http.Request) (identity string, ok bool)

GetUserIdentity returns the user identity found in the http request's JWT token.

func Info

func Info(interfaces ...interface{})

Info sends an info message to rollbar. The valid types are:

*http.Request error string map[string]interface{} int ign.ErrMsg

func Max

func Max(x, y int64) int64

Max is an implementation of "int" Max See https://mrekucci.blogspot.com.ar/2015/07/dont-abuse-mathmax-mathmin.html

func Min

func Min(x, y int64) int64

Min is an implementation of "int" Min See https://mrekucci.blogspot.com.ar/2015/07/dont-abuse-mathmax-mathmin.html

func NewPaginationRequest

func NewPaginationRequest(r *http.Request) (*PaginationRequest, *ErrMsg)

NewPaginationRequest creates a new PaginationRequest from the given http request.

func NewRouter

func NewRouter(routes Routes) *mux.Router

NewRouter creates a new Gorilla/mux router

func RandomString

func RandomString(strlen int) string

RandomString creates a random string of a given length. Ref: https://siongui.github.io/2015/04/13/go-generate-random-string/

func ReadEnvVar

func ReadEnvVar(name string) (string, error)

ReadEnvVar reads an environment variable and return an error if not present

func SameElements

func SameElements(a0, b0 []string) bool

SameElements returns True if the two given string slices contain the same elements, even in different order.

func SendEmail

func SendEmail(sender, recipient, subject, body string) error

SendEmail using AWS Simple Email Service (SES) The following environment variables must be set:

AWS_REGION AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY

func StrToSlice

func StrToSlice(tagsStr string) []string

StrToSlice returns the slice of strings with all tags parsed from the input string. It will trim leading and trailing whitespace, and reduce middle whitespaces to 1 space. It will also remove 'empty' tags (ie. whitespaces enclosed with commas, ', ,') The input string contains tags separated with commas. E.g. input string: " tag1, tag2, tag3 , , " E.g. output: ["tag1", "tag2", "tag3"]

func Trace

func Trace(skip int64) string

Trace returns the filename, line and function name of its caller. The skip parameter is the number of stack frames to skip, with 1 identifying the Trace frame itself. Skip will be set to 1 if the passed in value is <= 0. Ref: http://stackoverflow.com/questions/25927660/golang-get-current-scope-of-function-name

func Unzip

func Unzip(buff bytes.Buffer, size int64, dest string, verbose bool) error

Unzip a memory buffer

func UnzipFile

func UnzipFile(zipfile string, dest string, verbose bool) error

UnzipFile extracts a compressed .zip file

func UnzipImpl

func UnzipImpl(reader *zip.Reader, dest string, verbose bool) error

UnzipImpl is a helper unzip implementation

func Warning

func Warning(interfaces ...interface{})

Warning sends a warning message to rollbar. The valid types are:

*http.Request error string map[string]interface{} int ign.ErrMsg

func WritePaginationHeaders

func WritePaginationHeaders(page PaginationResult, w http.ResponseWriter, r *http.Request) error

WritePaginationHeaders writes the 'next', 'last', 'first', and 'prev' Link headers to the given ResponseWriter.

Types

type DatabaseConfig

type DatabaseConfig struct {
	// Username to login to a database.
	UserName string
	// Password to login to a database.
	Password string
	// Address of the database.
	Address string
	// Name of the database.
	Name string
	// Allowed Max Open Connections.
	// A value <= 0 means unlimited connections.
	// See 'https://golang.ir/src/database/sql/sql.go'
	MaxOpenConns int
}

DatabaseConfig contains information about a database connection

type Detail

type Detail struct {
	Type        string `json:"type"`
	Description string `json:"description"`
	Required    bool   `json:"required"`
}

Detail stores information about a paramter.

type ErrMsg

type ErrMsg struct {
	// Internal error code.
	ErrCode int `json:"errcode"`
	// HTTP status code.
	StatusCode int `json:"-"`
	// Error message.
	Msg string `json:"msg"`
	// Extra information/arguments associated to Error message.
	Extra []string `json:"extra"`
	// The root cause error
	BaseError error `json:"-"`
	// Generated ID for easy tracking in server logs
	ErrID string `json:"errid"`
	// Associated request Route, if applicable
	Route string `json:"route"`
	// Associated request User-Agent, if applicable
	UserAgent string `json:"user-agent"`
	// Associated request remote address, if applicable
	RemoteAddress string `json:"remote-address"`
}

ErrMsg is serialized as JSON, and returned if the request does not succeed TODO: consider making ErrMsg an 'error'

func ErrorMessage

func ErrorMessage(err int64) ErrMsg

ErrorMessage receives an error code and generate an error message response

func ErrorMessageOK

func ErrorMessageOK() ErrMsg

ErrorMessageOK creates an ErrMsg initialized with OK (default) values.

func NewErrorMessage

func NewErrorMessage(err int64) *ErrMsg

NewErrorMessage is a convenience function that receives an error code and returns a pointer to an ErrMsg.

func NewErrorMessageWithArgs

func NewErrorMessageWithArgs(err int64, base error, extra []string) *ErrMsg

NewErrorMessageWithArgs receives an error code, a root error, and a slice of extra arguments, and returns a pointer to an ErrMsg.

func NewErrorMessageWithBase

func NewErrorMessageWithBase(err int64, base error) *ErrMsg

NewErrorMessageWithBase receives an error code and a root error and returns a pointer to an ErrMsg.

func (*ErrMsg) LogString

func (e *ErrMsg) LogString() string

LogString creates a verbose error string

type FormatHandler

type FormatHandler struct {
	// Format (eg: .json, .proto, .html)
	Extension string `json:"extension"`

	// Processor for the url pattern
	Handler http.Handler `json:"-"`
}

FormatHandler represents a format type string, and handler function pair. Handlers are called in response to a route request.

type FormatHandlers

type FormatHandlers []FormatHandler

FormatHandlers is a slice of FormatHandler values.

type Handler

type Handler func(http.ResponseWriter, *http.Request) *ErrMsg

Handler represents an HTTP Handler that can also return a ErrMsg See https://blog.golang.org/error-handling-and-go

func (Handler) ServeHTTP

func (fn Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

///////////////////////////////////////////////

type HandlerWithResult

type HandlerWithResult func(w http.ResponseWriter, r *http.Request) (interface{}, *ErrMsg)

HandlerWithResult represents an HTTP Handler that that has a result

type Header struct {
	Name          string `json:"name"`
	HeaderDetails Detail `json:"details"`
}

Header stores the information about headers included in a request.

type Method

type Method struct {
	// GET, POST, PUT, DELETE
	// \todo: Make this an enum
	Type string `json:"type"`

	// Description of the method
	Description string `json:"description"`

	// A slice of hanlders used to process this method.
	Handlers FormatHandlers `json:"handler"`
}

Method associates an HTTP method (GET, POST, PUT, DELETE) with a list of handlers.

type Methods

type Methods []Method

Methods is a slice of Method.

type PaginationRequest

type PaginationRequest struct {
	// Flag that indicates if the request included a "page" argument.
	PageRequested bool
	// The requested page number (value >= 1)
	Page int64
	// The requested number of items per page.
	PerPage int64
	// The original request URL
	URL string
}

PaginationRequest represents the pagination values requested in the URL query (eg. ?page=2&per_page=10)

type PaginationResult

type PaginationResult struct {
	// Page number
	Page int64
	// Page size
	PerPage int64
	// Original request' url
	URL string
	// Query "total" count (ie. this is NOT the "page" count)
	QueryCount int64
	// A page is considered "found" if it is within the range of valid pages,
	// OR if it is the first page and the DB query is empty. In this empty scenario,
	// we want to return status OK with zero elements, rather than a 404 status.
	PageFound bool
}

PaginationResult represents the actual pagination output.

func PaginateQuery

func PaginateQuery(q *gorm.DB, result interface{}, p PaginationRequest) (*PaginationResult, error)

PaginateQuery applies a pagination request to a GORM query and executes it. Param[in] q gorm.DB The query to be paginated Param[out] result [interface{}] The paginated list of items Param[in] p The pagination request Returns a PaginationResult describing the returned page.

type ProtoResult

type ProtoResult HandlerWithResult

ProtoResult provides protobuf serialization for handler results

func (ProtoResult) ServeHTTP

func (fn ProtoResult) ServeHTTP(w http.ResponseWriter, r *http.Request)

///////////////////////////////////////////////

type Route

type Route struct {

	// Name of the route
	Name string `json:"name"`

	// Description of the route
	Description string `json:"description"`

	// URI pattern
	URI string `json:"uri"`

	// Headers required by the route
	Headers []Header `json:"headers"`

	// HTTP methods supported by the route
	Methods Methods `json:"methods"`

	// Secure HTTP methods supported by the route
	SecureMethods SecureMethods `json:"secure_methods"`
}

Route is a definition of a route

type Routes

type Routes []Route

Routes is an array of Route

type SecureMethods

type SecureMethods []Method

SecureMethods is a slice of Method that require authentication.

type Server

type Server struct {
	/// Global database interface
	Db *gorm.DB

	Router *mux.Router

	// Port used for non-secure requests
	HTTPPort string

	// SSLport used for secure requests
	SSLport string

	// SSLCert is the path to the SSL certificate.
	SSLCert string

	// SSLKey is the path to the SSL private key.
	SSLKey string

	// DbConfig contains information about the database
	DbConfig DatabaseConfig

	// IsTest is true when tests are running.
	IsTest bool

	// Google Analytics tracking ID. The format is UA-XXXX-Y
	GaTrackingID string

	// Google Analytics Application Name
	GaAppName string

	// (optional) A string to use as a prefix to GA Event Category.
	GaCategoryPrefix string
	// contains filtered or unexported fields
}

Server encapsulates information needed by a downstream application

func Init

func Init(routes Routes, auth0RSAPublicKey string) (server *Server, err error)

Init initialize this package

func (*Server) Auth0RsaPublicKey

func (s *Server) Auth0RsaPublicKey() string

Auth0RsaPublicKey return the Auth0 public key

func (*Server) Run

func (s *Server) Run()

Run the router and server

func (*Server) SetAuth0RsaPublicKey

func (s *Server) SetAuth0RsaPublicKey(key string)

SetAuth0RsaPublicKey sets the server's Auth0 RSA public key

type TypeJSONResult

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

TypeJSONResult represents a function result that can be exported to JSON

func JSONListResult

func JSONListResult(wrapper string, handler HandlerWithResult) TypeJSONResult

JSONListResult provides JSON serialization for handler results that are slices of objects.

func JSONResult

func JSONResult(handler HandlerWithResult) TypeJSONResult

JSONResult provides JSON serialization for handler results

func (TypeJSONResult) ServeHTTP

func (t TypeJSONResult) ServeHTTP(w http.ResponseWriter, r *http.Request)

///////////////////////////////////////////////

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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