goexpose

package module
v0.0.0-...-9b117df Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2016 License: MIT Imports: 29 Imported by: 0

README

Goexpose

Goexpose is lightweight json api server that maps url path to various tasks. Goexpose can be used in various scenarios: either make call commands on your servers (or farm of servers), or you can use it as monitoring tool. Builtin tasks are currently:

  • shell task - list of shell commands
  • http task - call external http request
  • info task - information about server
  • postgres task - run queries on postgres database
  • redis task - run commands on redis
  • cassandra task - run cassandra queries
  • mysql task - task to run mysql queries
  • multi task - run multiple tasks
  • filesystem task - serving file(s) from filesystem

I have a plan to implement other tasks with support for: memcache, mongodb, sqlite, file..

All these commands can accepts variables from route (gorilla mux is used). GOexpose has system for authorization, currently basic (username password) is implemented. In the future more types of authorization will be implemented.

Lets see example configuration file:

{
    "host": "127.0.0.1",
    "port": 9900,
    "ssl": {
        "cert": "./cert.pem",
        "key": "./key.pem"
    },
    "reload_env": true,
    "endpoints": [{
        "path": "/info",
        "authorizers": ["basic"],
        "methods": {
            "GET": {
                "type": "info",
                "description": "Info task"
            }
        }
    }],
    "authorizers": {
        "basic": {
            "type": "basic",
            "config": {
                "username": "hello",
                "password": "world"
            }
        }
    }
}

This means that Goexpose will listen on https://127.0.0.1:9900 "endpoints" is a list of defined endpoints that goexpose responds to.

You can also write your configuration in yaml format(command line arg -format)

Configuration:
  • host - host that we will listen on
  • port - port number
  • ssl - ssl settings
    • cert - cert file
    • key - key file
  • reload_env - reload env variables on every request
  • endpoints - list of endpoints, config for endpoint:
    • path - url path
    • authorizers - list of authorizers applied to this endpoint (see Authorizers)
    • methods - dictionary that maps http method to task

Installation:

Run go install

go install github.com/phonkee/goexpose

Interpolation:

Goexpose provides various variables from url, query, request. This data is available in commands to interpolate various strings. text/template is used and available data is in this structure:

{
    "url": {},
    "query": {},
    "request": {
        "method": "",
        "body": ""
    },
    "env": {}
}
  • env - environment variables
  • url - variables from url regular expressions
  • query - query values from "query_params"
  • request - request vars from goexpose request
    • method - http method from request
    • body - body passed to request

Query Params:

Goexpose has support to use query parameters. But you have to configure all params that you want to use. Goexpose gives you possibility to validate params values with regular expressions and provide default value. You can provide "query_params" on two levels. You can specify them on endpoint level and also on task level.

Configuration:

{
    "query_params": {
        "return_params": true,
        "params": [{
            "name": "page",
            "regexp": "^[0-9]+$",
            "default": "0"
        }, {
            "name": "limit",
            "regexp": "^[0-9]+$",
            "default": "10"
        }]
    }
}

Formats:

http task and shell task have possibility to set format of response. Currently available formats are: "json", "jsonlines", "lines", "text". Format can be combination of multiple formats. e.g.

"format": "json|jsonlines"

First format that returns result without error will be used. If "text" is not found in format, it is automatically inserted to the end.

Tasks:

Tasks can be configured in config["methods"] which is a map[string]TaskConfig - http method to task. Every task config has common part and configuration for given task. Common configuration is:

{
    "type": "http",
    "authorizers": [],
    "config": {},
    "query_params": {
        "params": [{
            "name": "id",
            "regexp": "^[0-9]+$",
            "default": "0"
        }],
        "return_params": true
    }
}
  • type - type of task.
  • authorizers - list of authorizers for given endpoint (see Authorizers)
  • config - configuration for given task type (will describe later in each task)
  • query_params - query params (see Query Params)
  • return_params - whether goexpose should return those params in response
HttpTask:

Http task is task that can do external request. Task configuration is following:

{
    "type": "http",
    "config": {
        "single_result": 0,
        "urls": [{
            "url": "http://127.0.0.1:8000/{{.url.id}}",
            "post_body": false,
            "format": "json",
            "return_headers": false
        }, {
            "url": "http://127.0.0.1:8000/{{.url.id}}",
            "method": "PUT",
            "post_body": false,
            "format": "json",
            "return_headers": false,
            "post_body": true,
        }]
    }
}

Configuration:

  • urls - list of url configurations
    • url - url to send request to, url is interpolated (see Interpolation)
    • method - request to url will not have the same method as request to goexpose, given method value will be used
    • format - format of response, if no format is given goexpose will try to read Content-Type, if application/json (see Formats)
    • return_headers - whether to return response headers from url response to goexpose response
    • post_body - if goexpose should post body of goexpose request to url
  • single_result - only that result will be returned (unwrapped from array)
ShellTask:

ShellTask is task that is able to run shell commands on target server. Every command is interpolated (see Interpolation)

Warning!!! Use appropriate regular expressions for inputs so you don't expose your server to shell injection. Example:

{
    "type": "shell",
    "config": {
        "env": {
            "key": "value"
        },
        "shell": "/bin/bash",
        "commands": [{
            "command": "echo \"{{.url.id}}\"",
            "chdir": "/tmp",
            "format": "json",
            "return_command": true
        }]
    }
}

Configuration:

  • env - custom environment variables
  • shell - shell to run command with
  • commands - list of commands to be called:
    • command - shell command to be run, interpolated (see Interpolation)
    • chdir - change directory before run command
    • format - format of the response (see Formats)
    • return_command - whether to return command in response
  • single_result - index which command will be "unwrapped" from result array
InfoTask:

Info task returns information about goexpose. In result you can find version of goexpose and also all registered tasks with info. Task info has no configuration.

PostgresTask:

Run queries on postgres database. Configuration for postgres task:

{
    "type": "postgres",
    "config": {
        "return_queries": true,
        "queries": [{
            "url": "postgres://username:password@localhost/database",
            "query": "SELECT * FROM product WHERE id = $1",
            "args": [
                "{{.url.id}}"
            ]
        }]
    }
}

Configuration:

  • return_queries - whether queries with args should be added
  • queries - list of queries
    • url - postgres url (passed to sql.Open, refer to https://github.com/lib/pq), interpolated (see Interpolation)
    • methods - allowed methods, if not specified all methods are allowed
    • query - sql query with placeholders $1, $2 ... (query is not interpolated!!!)
    • args - list of arguments to query - all queries are interpolated (see Interpolation).
  • single_result - index which query will be "unwrapped" from result array
RedisTask:

Task that can run multiple commands on redis. Example:

{
    "type": "redis",
    "config": {
        "address": "127.0.0.1:6379",
        "network": "tcp",
        "database": 1,
        "return_queries": true,
        "queries": [{
            "command": "GET",
            "args": [
                "product:{{.url.id}}"
            ],
            "type": "string"
        }]
    }
}

Configuration:

  • address - address to connect to (see http://godoc.org/github.com/garyburd/redigo/redis#Dial) Default: ":6379", interpolated (see Interpolation)
  • network - network (see http://godoc.org/github.com/garyburd/redigo/redis#Dial) Default: "tcp"
  • database - database number Default: 1
  • return_queries - whether to return queries in response
  • queries - list of queries settings
    • command - redis command
    • args - arguments passed to redis command, all arguments are interpolated (see Interpolation)
    • type - type of return value. Possible values are:
      • bool
      • float64
      • int
      • int64
      • ints - list of integers
      • string - default
      • strings - list of strings
      • uint64
      • values
      • stringmap - map[string]string
  • single_result - index which query will be "unwrapped" from result array
CassandraTask:

Run cassandra queries task. Example:

{
    "type": "cassandra",
    "config": {
        "return_queries": true,
        "queries": [{
            "query": "SELECT * from user WHERE id = ?",
            "args": [
                "{{.url.id}}"
            ],
            "cluster": [
                "192.168.1.1",
                "192.168.1.2"
            ],
            "keyspace": "keyspace"
        }]
    }
}

Configuration:

  • return_queries - whether to return query, args in response
  • queries - list of queries configurations, query configuration:
    • query - query with placeholders
    • args - arguments to query which are interpolated (See interpolation)
    • cluster - list of hosts in cluster, all args are interpolated (see Interpolation)
    • keyspace - keyspace to use, interpolated (see Interpolation)
  • single_result - index which query will be "unwrapped" from result array
MySQLTask:

Run mysql queries. Example:

{
    "type": "mysql",
    "config": {
        "return_queries": true,
        "queries": [{
            "url": "user:password@localhost/dbname",
            "query": "SELECT * FROM auth_user WHERE id = ?",
            "args": [
                "{{.url.id}}"
            ]
        }]
    }
}

Configuration:

  • return_queries - whether to return query with args to response
  • queries - list of queries, query config:
    • url - url to connect to (refer to https://github.com/go-sql-driver/mysql), interpolated (see Interpolation)
    • query - query with placeholders
    • args - list of arguments, every argument will be interpolated (see Interpolation)
  • single_result - index which query will be "unwrapped" from result array
MultiTask:

Multi task gives possibility to run multiple tasks in one task. These task can be any tasks (except of embedded multi task).

{
    "type": "multi",
    "config": {
        "single_result": 0,
        "tasks": [{
            "type": "http",
            "config": {
            "single_result": 0,
            "urls": [{
                "url": "http://www.google.com"
            }]
        }
    }]        
}

Configuration:

  • single_result - index which task will be "unwrapped" from result array
  • tasks - list of tasks (these embedded tasks does not support authorizers)
FilesystemTask:

Filesystem task is simple yet powerful task. It can be configured to serve single file or serve all files in directory with optional index page for directories.

In following example we serve only one file on url /file/some. The output will be json with base encoded file content.

{
    "path": "/file/some",
    "methods": {
        "GET": {
            "type": "filesystem",
            "config": {
                "file": "/tmp/file"
            }
        }
    }
}

In next example we will serve files in directory and provide index page for directories and also give possibility to return raw file as response.

{
    "path": "/static/{file:.+}",
    "methods": {
        "GET": {
            "query_params": {
                "params": [{
                    "name": "output",
                    "regexp": "^raw$",
                    "default": ""
                }],
            },                
            "config": {
                "file": "{{.url.file}}",
                "output": "{{.query.output}}",
                "directory": "/tmp",
                "index": true
            }
        }
    }
}

Configuration:

  • file - file to serve (interpolated)
  • directory - base directory (interpolated)
  • output - type of the output (interpolated)
    • "raw" - returns raw file contents, otherwise it's wrapped to json
  • index - whether to serve index endpoint for directory

Authorizers:

Types of authentication ( I know it's silly name..) First you have to define your authorizers in top level "authorizers" and then you can use them in your tasks defined by name. e.g.:

{
    "endpoints": [{
        "path": "/info",
        "authorizers": ["username_pass"],
        "methods": {
            "GET": {
                "type": "info",
            }
        }
    }],
    "authorizers": {
        "username_pass": {
            "type": "basic",
            "config": {
                "username": "hello",
                "password": "world"
            }
        }
    }
}

You can set your authorizers in endpoint configuration, or you can set in every task for fine tuned configuration.

Basic

Support for basic authentication.

{
    "type": "basic",
    "config": {
        "username": "hello",
        "password": "world"
    }
}
LDAP

Support for LDAP authentication.

{
    "type": "ldap",
    "config": {
        "host": "localhost",
        "port": 1234,
        "network": "tls"
    }
}

Configuration:

  • host - host of ldap server (default localhost)
  • port - port of ldap server (default 389)
  • network - one of tcp, tls (default tcp)
  • whitelist - list of usernames that can access goexpose endpoint
  • blacklist - list of usernames that are blacklisted to access endpoint

@TODO - add tls support for certificates

http

Support to call external web services for authentication (such as rest). Request to goexpose is allowed when the http call returns status code 200. Otherwise Unauthorized is raised.

{
    "type": "http",
    "config": {
        "url": "http://localhost:8080/api/users/login",
        "data": "{\"username\": \"{{.username}}\", \"password\": \"{{.password}}\"}",
        "method": "post"
    }
}

Configuration:

  • url - url to which goexpose make request. Interpolated (username, password)
  • data - post data (such as json, url values). Interpolated (username, password)
  • method - http method. Interpolated (username, password)

Example:

in folder example/ there is complete example for couple of tasks. You can find example here! or yaml!

@TODO: Add tasks for: sqlite, memcached, mongodb

Author:

phonkee

Documentation

Overview

Goexpose is lightweight json server that can map url paths to various tasks. Main idea is to have possibility to call shell scripts by http request. These shell scripts can consume mux vars from url(gorilla mux is used). You should be very careful how you construct your regular expressions, so you don't open doors to shell injection. Goexpose supports authorization system (right now only basic auth is supported). Goexpose can be run on https so if you combine https with strong password, you should be not vulnerable.

Various http helpers and utilities

Index

Constants

View Source
const (
	LDAP_DEFAULT_HOST    = "localhost"
	LDAP_DEFAULT_PORT    = 389
	LDAP_DEFAULT_NETWORK = "tcp"
)
View Source
const (
	DEFAULT_TIMEOUT = 10 * time.Second
)

Requester makes http requests

View Source
const (
	VERSION = "1.0.0"
)

Variables

View Source
var (
	ErrUnauthorized               = errors.New("unauthorized")
	ErrBlacklisted                = errors.New("user is blacklisted")
	ErrNotWhitelisted             = errors.New("user is not whitelisted")
	ErrBlacklistWhitelistProvided = errors.New("blacklist and whitelist set, that doesn't make sense.")
	ErrUnknownNetwork             = errors.New("unknown network")
	ErrURLInvalidTemplate         = errors.New("url is invalid template")
)
View Source
var (
	ErrInvalidAuthorizationHeader = errors.New("invalid authorization header")
)

Functions

func AddFormat

func AddFormat(format, id string) (result string)

func AuthorizerExists

func AuthorizerExists(id string) (ok bool)

AuthorizerExists returns if exists authorizer by given id

func Format

func Format(body string, f string) (result interface{}, format string, err error)

Formats body

func FormatJSON

func FormatJSON(body string) (result interface{}, err error)

Formats body as json (map[string]interface{})

func FormatJSONLines

func FormatJSONLines(body string) (result interface{}, err error)

Formats body as json lines

func FormatLines

func FormatLines(body string) (result interface{}, err error)

Formats body as lines of text (delimited by \n)

func FormatText

func FormatText(body string) (result interface{}, err error)

Text format just returns body

func HasFormat

func HasFormat(format, id string) bool

func Interpolate

func Interpolate(strTemplate string, data map[string]interface{}) (result string, err error)

Interpolate

renders template with data

func MethodAllowed

func MethodAllowed(method string, avail []string) bool

Returns if method is allowed

if avail methods is blank it also returns true

func RegisterAuthorizer

func RegisterAuthorizer(id string, factory AuthorizerFactory)

Register authorizer

func RegisterFormat

func RegisterFormat(id string, fn FormatFunc)

Register format function

func RegisterTaskFactory

func RegisterTaskFactory(id string, factory TaskFactory)

Registers task factory to server

func RenderTemplate

func RenderTemplate(tpl *template.Template, data map[string]interface{}) (result string, err error)

RenderTemplate

renders template with data

func VerifyFormat

func VerifyFormat(format string) (result string, err error)

Verify given format

format can be multiple formats separated by "|". if text is not found in format it is automatically added.

Types

type Authorizer

type Authorizer interface {
	Authorize(r *http.Request) error
}

Authorizer implements authorization

func BasicAuthorizerFactory

func BasicAuthorizerFactory(ac *AuthorizerConfig) (result Authorizer, err error)

func HttpAuthorizerFactory

func HttpAuthorizerFactory(ac *AuthorizerConfig) (result Authorizer, err error)

func LDAPAuthorizerFactory

func LDAPAuthorizerFactory(ac *AuthorizerConfig) (result Authorizer, err error)

type AuthorizerConfig

type AuthorizerConfig struct {
	Type   string          `json:"type"`
	Config json.RawMessage `json:"config"`
}

Configuration for authorizer

func (*AuthorizerConfig) Validate

func (a *AuthorizerConfig) Validate() (err error)

Validate

type AuthorizerFactory

type AuthorizerFactory func(config *AuthorizerConfig) (Authorizer, error)

AuthFactory returns new authorizer

type Authorizers

type Authorizers map[string]Authorizer

Authorizers will have method that will check all authorizers

func GetAuthorizers

func GetAuthorizers(config *Config) (result Authorizers, err error)

Returns authorizers for given config First step is that it validates authorizers

func (Authorizers) Authorize

func (a Authorizers) Authorize(r *http.Request, config *EndpointConfig) (err error)

Try all authorizers, first that will fail with error, that error will be returned

func (Authorizers) Names

func (a Authorizers) Names() []string

Returns names of all authorizerse

type BasicAuthorizer

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

Basic auth provides method GetBasicAuth from request headers

func (*BasicAuthorizer) Authorize

func (b *BasicAuthorizer) Authorize(r *http.Request) (err error)

Check username and password

func (*BasicAuthorizer) GetBasicAuth

func (a *BasicAuthorizer) GetBasicAuth(r *http.Request) (username, password string, err error)

Return username and password

type BasicAuthorizerConfig

type BasicAuthorizerConfig struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type CassandraTask

type CassandraTask struct {
	Task
	// contains filtered or unexported fields
}

Cassandra task to run queries on cassandra

func (*CassandraTask) Run

func (c *CassandraTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

Run cassandra task

type CassandraTaskConfig

type CassandraTaskConfig struct {
	Queries       []CassandraTaskConfigQuery `json:"queries"`
	ReturnQueries bool                       `json:"return_queries"`
	SingleResult  *int                       `json:"single_result"`
	// contains filtered or unexported fields
}

func (*CassandraTaskConfig) Validate

func (c *CassandraTaskConfig) Validate() (err error)

Validate config

type CassandraTaskConfigQuery

type CassandraTaskConfigQuery struct {
	Cluster  []string `json:"cluster"`
	Keyspace string   `json:"keyspace"`
	Query    string   `json:"query"`
	Args     []string `json:"args"`
}

Config for Query

func (*CassandraTaskConfigQuery) Validate

func (c *CassandraTaskConfigQuery) Validate() (err error)

Validate query config

type Config

type Config struct {
	Host        string                       `json:"host"`
	Port        int                          `json:"port"`
	SSL         *SSLConfig                   `json:"ssl"`
	PrettyJson  bool                         `json:"pretty_json"`
	Authorizers map[string]*AuthorizerConfig `json:"authorizers"`
	Endpoints   []*EndpointConfig            `json:"endpoints"`
	ReloadEnv   bool                         `json:"reload_env"`
	Directory   string                       `json:"-"`
}

Main config

func NewConfig

func NewConfig() *Config

Returns config with default values

func NewConfigFromFilename

func NewConfigFromFilename(filename, format string) (config *Config, err error)

Returns filename from file

type EndpointConfig

type EndpointConfig struct {
	Authorizers []string              `json:"authorizers"`
	Path        string                `json:"path"`
	Methods     map[string]TaskConfig `json:"methods"`
	Type        string                `json:"type"`
	QueryParams *QueryParams          `json:"query_params"`
	RawResponse bool                  `json:"raw_response"`
}

func (*EndpointConfig) RouteName

func (e *EndpointConfig) RouteName() string

func (*EndpointConfig) Validate

func (e *EndpointConfig) Validate() (err error)

type FilesystemConfig

type FilesystemConfig struct {
	File      string `json:"file"`
	Output    string `json:"output"`
	Directory string `json:"directory"`
	Index     bool   `json:"index"`
}

func NewFilesystemConfig

func NewFilesystemConfig() *FilesystemConfig

func (*FilesystemConfig) Validate

func (f *FilesystemConfig) Validate() (err error)

type FilesystemTask

type FilesystemTask struct {
	Task
	// contains filtered or unexported fields
}

FilesystemTask

serve single file

func (*FilesystemTask) Run

func (f *FilesystemTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

Run method for FilesystemTask

type FormatFunc

type FormatFunc func(string) (interface{}, error)

format function

type HttpAuthorizer

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

HttpAuthorizer implementation

func (*HttpAuthorizer) Authorize

func (h *HttpAuthorizer) Authorize(r *http.Request) (err error)

Authorize main routine to allow user access

type HttpAuthorizerConfig

type HttpAuthorizerConfig struct {
	URL    string `json:"url"`
	Data   string `json:"data"`
	Method string `json:"method"`
}

HttpAuthorizerConfig implementation

configuration for HttpAuthorizer

func NewHttpAuthorizerConfig

func NewHttpAuthorizerConfig(ac *AuthorizerConfig) (hac *HttpAuthorizerConfig, err error)

func (*HttpAuthorizerConfig) RenderData

func (h *HttpAuthorizerConfig) RenderData(data map[string]interface{}) (result string, err error)

func (*HttpAuthorizerConfig) RenderMethod

func (h *HttpAuthorizerConfig) RenderMethod(data map[string]interface{}) (result string, err error)

func (*HttpAuthorizerConfig) RenderURL

func (h *HttpAuthorizerConfig) RenderURL(data map[string]interface{}) (result string, err error)

type HttpTask

type HttpTask struct {
	Task
	// contains filtered or unexported fields
}

HttpTask

task that can make requests to given urls

func (*HttpTask) Run

func (h *HttpTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

Run method is called on request @TODO: please refactor me!

type HttpTaskConfig

type HttpTaskConfig struct {
	URLs         []*HttpTaskConfigURL `json:"urls"`
	SingleResult *int                 `json:"single_result"`
	// contains filtered or unexported fields
}

func (*HttpTaskConfig) Validate

func (h *HttpTaskConfig) Validate() (err error)

Validate config

type HttpTaskConfigURL

type HttpTaskConfigURL struct {
	URL           string `json:"url"`
	Method        string `json:"method"`
	PostBody      bool   `json:"post_body"`
	Format        string `json:"format"`
	ReturnHeaders bool   `json:"return_headers"`
}

type InfoTask

type InfoTask struct {
	Task
	// contains filtered or unexported fields
}

InfoTask - information about goexpose server

func (*InfoTask) Run

func (i *InfoTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

InfoTask Run method.

type LDAPAuthorizer

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

LDAPAuthorizer Main ldap authorizer implementation

func (*LDAPAuthorizer) Authorize

func (l *LDAPAuthorizer) Authorize(r *http.Request) (err error)

type LDAPAuthorizerConfig

type LDAPAuthorizerConfig struct {
	Host      string   `json:"host"`
	Port      int      `json:"port"`
	Network   string   `json:"network"`
	Whitelist []string `json:"whitelist"`
	Blacklist []string `json:"blacklist"`
}

func (*LDAPAuthorizerConfig) Validate

func (l *LDAPAuthorizerConfig) Validate() (err error)

Validate configuration

type MultiTask

type MultiTask struct {
	Task
	// contains filtered or unexported fields
}

Multi task imlpementation

func (*MultiTask) Run

func (m *MultiTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

Run multi task.

type MultiTaskConfig

type MultiTaskConfig struct {
	Tasks        []*TaskConfig `json:"tasks"`
	SingleResult *int          `json:"single_result"`
	// contains filtered or unexported fields
}

func (*MultiTaskConfig) Validate

func (m *MultiTaskConfig) Validate() (err error)

type MySQLTask

type MySQLTask struct {
	Task
	// contains filtered or unexported fields
}

MySQL task imlpementation

func (*MySQLTask) Run

func (m *MySQLTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

Run mysql task.

type MySQLTaskConfig

type MySQLTaskConfig struct {
	ReturnQueries bool                    `json:"return_queries"`
	Queries       []*MySQLTaskConfigQuery `json:"queries"`
	SingleResult  *int                    `json:"single_result"`
	// contains filtered or unexported fields
}

func (*MySQLTaskConfig) Validate

func (m *MySQLTaskConfig) Validate() (err error)

Validate mysql config

type MySQLTaskConfigQuery

type MySQLTaskConfigQuery struct {
	URL   string   `json:"url"`
	Query string   `json:"query"`
	Args  []string `json:"args"`
}

Configuration for single query

func (*MySQLTaskConfigQuery) Validate

func (m *MySQLTaskConfigQuery) Validate() (err error)

type PostgresTask

type PostgresTask struct {
	Task
	// contains filtered or unexported fields
}

Postgres task

func (*PostgresTask) Run

func (p *PostgresTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

Run postgres task

type PostgresTaskConfig

type PostgresTaskConfig struct {
	Queries       []*PostgresTaskConfigQuery `json:"queries"`
	ReturnQueries bool                       `json:"return_queries"`
	SingleResult  *int                       `json:"single_result"`
	// contains filtered or unexported fields
}

func (*PostgresTaskConfig) Validate

func (p *PostgresTaskConfig) Validate() (err error)

type PostgresTaskConfigQuery

type PostgresTaskConfigQuery struct {
	URL   string   `json:"url"`
	Query string   `json:"query"`
	Args  []string `json:"args"`
}

type QueryParams

type QueryParams struct {
	ReturnParams bool                      `json:"return_params"`
	Params       []*QueryParamsConfigParam `json:"params"`
}

func (*QueryParams) GetParams

func (q *QueryParams) GetParams(r *http.Request) (result map[string]string)

Returns params from request

func (*QueryParams) Validate

func (q *QueryParams) Validate() (err error)

type QueryParamsConfigParam

type QueryParamsConfigParam struct {
	Name    string `json:"name"`
	Regexp  string `json:"regexp"`
	Default string `json:"default"`
	// contains filtered or unexported fields
}

Param config

type RedisTask

type RedisTask struct {
	Task
	// contains filtered or unexported fields
}

func (*RedisTask) GetReply

func (r *RedisTask) GetReply(reply interface{}, query RedisTaskConfigQuery) (interface{}, error)

func (*RedisTask) Run

func (rt *RedisTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

Run method runs when request comes...

type RedisTaskConfig

type RedisTaskConfig struct {
	Address       string                 `json:"address"`
	Database      int                    `json:"database"`
	Network       string                 `json:"network"`
	Queries       []RedisTaskConfigQuery `json:"queries"`
	ReturnQueries bool                   `json:"return_queries"`
	SingleResult  *int                   `json:"single_result"`
	// contains filtered or unexported fields
}

func (*RedisTaskConfig) Validate

func (r *RedisTaskConfig) Validate() (err error)

type RedisTaskConfigQuery

type RedisTaskConfigQuery struct {
	Command string   `json:"command"`
	Args    []string `json:"args"`
	Type    string   `json:"type"`
}

func (*RedisTaskConfigQuery) Validate

func (r *RedisTaskConfigQuery) Validate() (err error)

type Requester

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

Making requests

func NewRequester

func NewRequester(funcs ...RequesterSetFunc) (result *Requester)

NewRequester returns new requester instance

func (*Requester) DoNew

func (r *Requester) DoNew(method string, url string, body io.Reader) (req *http.Request, resp *http.Response, err error)

DoNew creates new request and sends it

func (*Requester) DoRequest

func (r *Requester) DoRequest(req *http.Request) (resp *http.Response, err error)

Do performs request and returns response or error

func (*Requester) Set

func (r *Requester) Set(funcs ...RequesterSetFunc) *Requester

With is used to change values directly from constructors

type RequesterSetFunc

type RequesterSetFunc func(r *Requester)

RequesterSetFunc is callback function to be called in Set method.

func WithTimeout

func WithTimeout(timeout time.Duration) RequesterSetFunc

Set functions

type Response

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

Response

func NewResponse

func NewResponse(status int) (response *Response)

Creates new json response

func (*Response) AddValue

func (r *Response) AddValue(key string, value interface{}) *Response

Adds value

func (*Response) DelValue

func (r *Response) DelValue(key string) *Response

Removes value

func (*Response) Error

func (r *Response) Error(err interface{}) *Response

Error method adds error, it's just a shorthand to AddValue("error", err)

@TODO: store just string from error

func (*Response) GetStatus

func (r *Response) GetStatus() int

GetStatus returns status

func (*Response) HasValue

func (r *Response) HasValue(key string) bool

Whether response has value

func (*Response) MarshalJSON

func (r *Response) MarshalJSON() (result []byte, err error)

Marshaler interface support json marshalling

func (*Response) Pretty

func (r *Response) Pretty(pretty bool) *Response

Sets pretty printing of json

func (*Response) Raw

func (r *Response) Raw(raw interface{}) *Response

Set raw response param can be following:

nil => clear raw
raw is fmt.Stringer or string => convert to []byte
[]byte leave as it is
otherwise try to marshal to json []byte

func (*Response) Result

func (r *Response) Result(result interface{}) *Response

Result method adds result, it's just a shorthand to AddValue("result", result)

func (*Response) Status

func (r *Response) Status(status int) *Response

Set status

func (*Response) StripStatusData

func (r *Response) StripStatusData() *Response

Strips status/message from data

func (*Response) UpdateStatusData

func (r *Response) UpdateStatusData() *Response

Updates stripped status data

func (*Response) Write

func (r *Response) Write(w http.ResponseWriter, req *http.Request, start ...time.Time) (err error)

Writes response to response writer and logs request

type SSLConfig

type SSLConfig struct {
	Cert string `json:"cert"`
	Key  string `json:"key"`
}

SSL config

type Server

type Server struct {

	// config instance
	Config *Config

	// Version
	Version string

	// Router
	Router *mux.Router
}

Goexpose server

func NewServer

func NewServer(config *Config) (server *Server, err error)

Returns new server instance

func (*Server) GetEnv

func (s *Server) GetEnv() map[string]interface{}

Get environment variables

func (*Server) GetQueryParams

func (s *Server) GetQueryParams(r *http.Request, ec *EndpointConfig) (result map[string]string)

Returns

func (*Server) Handle

func (s *Server) Handle(task Tasker, authorizers Authorizers, ec *EndpointConfig, tc *TaskConfig) http.HandlerFunc

Handle func

func (*Server) NotFoundHandler

func (s *Server) NotFoundHandler(w http.ResponseWriter, r *http.Request)

Handler for not found

func (*Server) Run

func (s *Server) Run() (err error)

Runs http server

type ShellTask

type ShellTask struct {
	Task

	// config
	Config *ShellTaskConfig
}

ShellTask runs shell commands

func (*ShellTask) Run

func (s *ShellTask) Run(r *http.Request, data map[string]interface{}) (response *Response)

Run method for shell task Run all commands and return results

type ShellTaskConfig

type ShellTaskConfig struct {
	// Custom environment variables
	Env          map[string]string         `json:"env"`
	Shell        string                    `json:"shell"`
	Commands     []*ShellTaskConfigCommand `json:"commands"`
	SingleResult *int                      `json:"single_result"`
	// contains filtered or unexported fields
}

Config for shell task

func NewShellTaskConfig

func NewShellTaskConfig() *ShellTaskConfig

func (*ShellTaskConfig) Validate

func (s *ShellTaskConfig) Validate() (err error)

Validate validates config

type ShellTaskConfigCommand

type ShellTaskConfigCommand struct {
	Command       string `json:"command"`
	Chdir         string `json:"chdir"`
	Format        string `json:"format"`
	ReturnCommand bool   `json:"return_command"`
}

func (*ShellTaskConfigCommand) Validate

func (s *ShellTaskConfigCommand) Validate() (err error)

type Task

type Task struct{}

Base task

func (*Task) Path

func (t *Task) Path() string

Default path is blank

type TaskConfig

type TaskConfig struct {
	Type        string          `json:"type"`
	Authorizers []string        `json:"authorizers"`
	Config      json.RawMessage `json:"config"`
	QueryParams *QueryParams    `json:"query_params"`
	Description string          `json:"description"`
}

Task config

func (*TaskConfig) Validate

func (t *TaskConfig) Validate() (err error)

Validate method validates task config

type TaskFactory

type TaskFactory func(server *Server, config *TaskConfig, ec *EndpointConfig) ([]Tasker, error)

TaskFactory returns instance of task by server and config

type Tasker

type Tasker interface {
	// Returns path for task
	Path() string

	// Run method is called on http request
	Run(r *http.Request, vars map[string]interface{}) *Response
}

Tasker interface Main task

func CassandraTaskFactory

func CassandraTaskFactory(s *Server, tc *TaskConfig, ec *EndpointConfig) (result []Tasker, err error)

func FilesystemFactory

func FilesystemFactory(s *Server, tc *TaskConfig, ec *EndpointConfig) (result []Tasker, err error)

Factory to create filesystem tasks

func HttpTaskFactory

func HttpTaskFactory(server *Server, tc *TaskConfig, ec *EndpointConfig) (tasks []Tasker, err error)

HttpTaskFactory - factory to create HttpTasks

func InfoTaskFactory

func InfoTaskFactory(server *Server, taskconfig *TaskConfig, ec *EndpointConfig) (tasks []Tasker, err error)

Factory for InfoTask task

func MultiTaskFactory

func MultiTaskFactory(s *Server, tc *TaskConfig, ec *EndpointConfig) (result []Tasker, err error)

Factory to create task

func MySQLTaskFactory

func MySQLTaskFactory(s *Server, tc *TaskConfig, ec *EndpointConfig) (result []Tasker, err error)

Factory to create task

func PostgresTaskFactory

func PostgresTaskFactory(server *Server, tc *TaskConfig, ec *EndpointConfig) (tasks []Tasker, err error)

func RedisTaskFactory

func RedisTaskFactory(server *Server, tc *TaskConfig, ec *EndpointConfig) (result []Tasker, err error)

Factory to create task instances

func ShellTaskFactory

func ShellTaskFactory(server *Server, taskconfig *TaskConfig, ec *EndpointConfig) (tasks []Tasker, err error)

Factory for ShellTask

Directories

Path Synopsis
cmd
goexpose
Main package for goexpose binary.
Main package for goexpose binary.

Jump to

Keyboard shortcuts

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