quickstub

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2024 License: MIT Imports: 11 Imported by: 0

README

quickstub - quick http server stub

Quickstub is a HTTP server which can be configured in a very simple manner with a .yaml file.

The program is intended mainly for mocking some API responses when testing your applications.

In addition to primary configuration quickstab may be reconfigured on the fly using the "magic endpoint" (see below).

Quickstart

Install the binary

go install github.com/dmfed/quickstub/cmd/quickstub@latest

Generate the config

quickstub -sample > myconfig.yaml

Edit the config as required (examples are included in the sample) then launch your server.

quickstub -conf myconfig.yaml

Configuring the server

Let's take a look at the sample configuration file.

version: 2
listen_addr: ':8080'
magic_endpoint: '/magic'
endpoints:
  # simple response with text body
  'GET /hello':
    code: 200
    body: "hello world"

  # responds with 201 code and text body
  'POST /hello':
    code: 201
    body: "created"

  # responds with 200 code a header and JSON body
  'GET /hello':
    code: 200
    headers:
        'Content-Type': 'application/json'
    body: '{"hello": "world"}'

  # redirects to /hello endpoint on the same host
  'GET /redirect':
    code: 301
    headers: 
      'Connection': 'keep-alive'
      'Location': '/hello'

  # responds with 400 code 
  'GET /badrequest':
    code: 400
    body: 'These are not the droids you are looking for!'

The first part configures the server itself.

version: 2
listen_addr: ':8080'
magic_endpoint: '/magic'

version is the version of API.

listen_addr tells the server the hostname and port to listen on. It may take the following forms: "172.0.0.1:8080" or just ":8080". This field is reauired and must not be empty.

magic_endpoint is the path of endpoint where server accepts reconfigure requests (see below).

The endpoints part of the config is a configuration of responses of the server.

Plain text response
'GET /hello':
    code: 200
    body: 'hello world'

The above tells quickstub to repond with 200 and "hello world" text on endpoint "/hello".

JSON response
'GET /hello':
    code: 200
    headers:
        'Content-Type': 'application/json'
    body: '{"hello": "world"}'

This will instruct quickstub to repon with JSON in the body.

Response with file.
'GET /config':
    code: 200
    headers: 
      'Content-Type': 'application/octet-stream'
      'Content-Disposition': 'attachment; filename=myconfig.yaml'
    body: '@myconfig.yaml'

This tells the server to accept GET requests to "/config" endpoint and respond with provided headers and contents of file "myconfig.yaml" in response body.

Note the "@" character. It tells qucikstub that the remaining part of the string is a local path to look for file. It may take form of "@/home/myuser/somefile" etc. If you want a string starting with "@" in response body, just escape it like this: "\@myresponse body" for double-quoted strings and like this '@myresponse body' for single-quoted string. (Note that yaml distinguishes between double and single quotes for strings).

Note: the actual contents of the file is preloaded into RAM on server start (or reconfiguration) so be midfull of what files to use. This program is just an http stub it is not intended to actually server huge files etc. So JSON is OK while ISO image is not.

Reconfigure endpoint or "magic endpoint"

If "magic_endpoint" is not empty in the config file then the server will listen to GET and PATCH requests on this endpoint.

version: 2
listen_addr: ':8080'
magic_endpoint: '/magic'

In the above example doing

curl -X GET localhost:8080/magic

will return the current configuration of the server.

To reconfigure the server do.

curl -X POST --data-binary '@my_new_config.yaml' localhost:8080/magic

This will result in pushing your file "my_new_config.yaml" to the server. The server will validate the new config config and respond with 201 OK. Then quickstub will be restarted with new parameters.

If any validation errors occur quickstub will respond with 400 and error text in response body.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewMux

func NewMux(endpoints Endpoints) (*http.ServeMux, error)

NewMux creates handler functions returning HTTP code and body as specified in the coniguration and registers it with an instance of *http.ServeMux then return this instance of ServeMux.

func NewServer

func NewServer(listenAddr string, endpoints Endpoints) (*http.Server, error)

NewServer returns *http.Server with Addr set to conf.ListenAddr and Handler set to ServeMux initialized with handlers as cpecified by conf.

Types

type Config

type Config struct {
	Version       Version   `yaml:"version" validate:"required,gte=1"`             // Version indicates version of the config (may bee ommitted for current version)
	ListenAddr    string    `yaml:"listen_addr" validate:"required,hostname_port"` // ListenAddr is the address for webserver to listen in form "host:port" (like "127.0.0.1:8080 or somehost:80") or simply port :8080 to accept connections on any interface.
	MagicEndpoint string    `yaml:"magic_endpoint"`                                // path to use for magic endpoint
	Endpoints     Endpoints `yaml:"endpoints" validate:"required"`                 // Endpoints tell Quickstub how to configure stub handlers.
}

Config is used to initialize Quickstub, http.Server of http.ServeMux with this package with specific request handlers.

func ParseConfig

func ParseConfig(b []byte) (*Config, error)

type Endpoints

type Endpoints map[Pattern]Response

Endpoints keys must be populated with Patterns. Corresponding Response values tell server what to respond when a Pattern matches.

type Pattern

type Pattern string

Pattern must take a form of either request method followed by path as in "POST /post/path" or just the path is in "/some/endpoint". See https://pkg.go.dev/net/http#ServeMux for description of acceptable patterns.

type QuickStub

type QuickStub interface {
	ListenAndServe() error
	ListenAndServeTLS(certFile string, keyFile string) error
	Shutdown(ctx context.Context) error
}

QuickStub is the main app interface under the hood it initializes http.Server accepting requests on endpoints provided in the Config and sets up the "magic endpoint" for on the fly reconfiguration of the server.

func NewQuickStub

func NewQuickStub(conf *Config) (QuickStub, error)

type Response

type Response struct {
	Code    int               `yaml:"code"`    // HTTP response code to be returned.
	Headers map[string]string `yaml:"headers"` // HTTP response headers.
	Body    string            `yaml:"body"`    // HTTP response body. If string in this field is prefixed with "@" symbol it is considered a path to file to read contents from.
}

type Version

type Version uint
const (
	Version1 Version = iota + 1
	Version2
)

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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