goa

package module
v0.0.0-...-8ffa6c8 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2017 License: MIT Imports: 27 Imported by: 0

README

goa is a framework for building micro-services and REST APIs in Go using a unique design-first approach.


Build Status Windows Build status Godoc Slack

Why goa?

goa takes a different approach to building micro-services. Instead of focusing solely on helping with implementation, goa makes it possible to describe the design of an API using a simple DSL. goa then uses that description to provide specialized helper code to the implementation and to generate documentation, API clients, tests, even custom artifacts.

If DSLs are not your thing then consider this: you need to document your APIs so that clients (be it internal e.g. other services or external e.g. UIs) may consume them. Typically this requires maintaining a completely separate document (for example an OpenAPI specification). Making sure that the document stays up-to-date takes a lot of effort and at the end of the day you have to write that document - why not use a simple and clear Go DSL to do that instead?

Another aspect to consider is the need for properly designing APIs and making sure that the design choices remain consistent across the endpoints or even across multiple APIs. If the source code is the only place where design decisions are kept then not only is it impossible to maintain consistency it's also difficult to think about the design in the first place. The goa DSL makes it possible to think about the design explicitly and - since it's code - to re-use design elements for consistency.

The goa DSL allows writing self-explanatory code that describes the resources exposed by the API and for each resource the properties and actions. goa comes with the goagen tool which runs the DSL and generates various types of artifacts from the resulting data structures.

One of the goagen output is glue code that binds your code with the underlying HTTP server. This code is specific to your API so that for example there is no need to cast or "bind" any handler argument prior to using them. Each generated handler has a signature that is specific to the corresponding resource action. It's not just the parameters though, each handler also has access to specific helper methods that generate the possible responses for that action. The DSL can also define validations in which case the generated code takes care of validating the incoming request parameters and payload prior to invoking the handler.

The end result is controller code that is terse and clean, the boilerplate is all gone. Another big benefit is the clean separation of concern between design and implementation: on bigger projects it's often the case that API design changes require careful review, being able to generate a new version of the documentation without having to write a single line of implementation is a big boon.

This idea of separating design and implementation is not new, the excellent Praxis framework from RightScale follows the same pattern and was an inspiration to goa.

Installation

Assuming you have a working Go setup:

go get -u github.com/goadesign/goa/...
Stable Versions

goa follows Semantic Versioning which is a fancy way of saying it publishes releases with version numbers of the form vX.Y.Z and makes sure that your code can upgrade to new versions with the same X component without having to make changes.

Releases are tagged with the corresponding version number. There is also a branch for each major version (only v1 at the moment). The recommended practice is to vendor the stable branch.

Current Release: v1.1.0 Stable Branch: v1

Teaser

1. Design

Create the file $GOPATH/src/goa-adder/design/design.go with the following content:

package design

import (
        . "github.com/goadesign/goa/design"
        . "github.com/goadesign/goa/design/apidsl"
)

var _ = API("adder", func() {
        Title("The adder API")
        Description("A teaser for goa")
        Host("localhost:8080")
        Scheme("http")
})

var _ = Resource("operands", func() {
        Action("add", func() {
                Routing(GET("add/:left/:right"))
                Description("add returns the sum of the left and right parameters in the response body")
                Params(func() {
                        Param("left", Integer, "Left operand")
                        Param("right", Integer, "Right operand")
                })
                Response(OK, "text/plain")
        })

})

This file contains the design for an adder API which accepts HTTP GET requests to /add/:x/:y where :x and :y are placeholders for integer values. The API returns the sum of x and y in its body.

2. Implement

Now that the design is done, let's run goagen on the design package:

cd $GOPATH/src/goa-adder
goagen bootstrap -d goa-adder/design

This produces the following outputs:

  • main.go and operands.go contain scaffolding code to help bootstrap the implementation. running goagen again does not recreate them so that it's safe to edit their content.
  • an app package which contains glue code that binds the low level HTTP server to your implementation.
  • a client package with a Client struct that implements a AddOperands function which calls the API with the given arguments and returns the http.Response.
  • a tool directory that contains the complete source for a client CLI tool.
  • a swagger package with implements the GET /swagger.json API endpoint. The response contains the full Swagger specificiation of the API.
3. Run

First let's implement the API - edit the file operands.go and replace the content of the Add function with:

// Add import for strconv
import "strconv"

// Add runs the add action.
func (c *OperandsController) Add(ctx *app.AddOperandsContext) error {
        sum := ctx.Left + ctx.Right
        return ctx.OK([]byte(strconv.Itoa(sum)))
}

Now let's compile and run the service:

cd $GOPATH/src/goa-adder
go build
./goa-adder
2016/04/05 20:39:10 [INFO] mount ctrl=Operands action=Add route=GET /add/:left/:right
2016/04/05 20:39:10 [INFO] listen transport=http addr=:8080

Open a new console and compile the generated CLI tool:

cd $GOPATH/src/goa-adder/tool/adder-cli
go build

The tool includes contextual help:

./adder-cli --help
CLI client for the adder service

Usage:
  adder-cli [command]

Available Commands:
  add         add returns the sum of the left and right parameters in the response body

Flags:
      --dump               Dump HTTP request and response.
  -H, --host string        API hostname (default "localhost:8080")
  -s, --scheme string      Set the requests scheme
  -t, --timeout duration   Set the request timeout (default 20s)

Use "adder-cli [command] --help" for more information about a command.

To get information on how to call a specific API use:

./adder-cli add operands --help
Usage:
  adder-cli add operands [/add/LEFT/RIGHT] [flags]

Flags:
      --left int    Left operand
      --pp          Pretty print response body
      --right int   Right operand

Global Flags:
      --dump               Dump HTTP request and response.
  -H, --host string        API hostname (default "localhost:8080")
  -s, --scheme string      Set the requests scheme
  -t, --timeout duration   Set the request timeout (default 20s)

Now let's run it:

./adder-cli add operands /add/1/2
2016/04/05 20:43:18 [INFO] started id=HffVaGiH GET=http://localhost:8080/add/1/2
2016/04/05 20:43:18 [INFO] completed id=HffVaGiH status=200 time=1.028827ms
3⏎

This also works:

$ ./adder-cli add operands --left=1 --right=2
2016/04/25 00:08:59 [INFO] started id=ouKmwdWp GET=http://localhost:8080/add/1/2
2016/04/25 00:08:59 [INFO] completed id=ouKmwdWp status=200 time=1.097749ms
3⏎

The console running the service shows the request that was just handled:

2016/06/06 10:23:03 [INFO] started req_id=rLAtsSThLD-1 GET=/add/1/2 from=::1 ctrl=OperandsController action=Add
2016/06/06 10:23:03 [INFO] params req_id=rLAtsSThLD-1 right=2 left=1
2016/06/06 10:23:03 [INFO] completed req_id=rLAtsSThLD-1 status=200 bytes=1 time=66.25µs

Now let's see how robust our service is and try to use non integer values:

./adder-cli add operands add/1/d
2016/06/06 10:24:22 [INFO] started id=Q2u/lPUc GET=http://localhost:8080/add/1/d
2016/06/06 10:24:22 [INFO] completed id=Q2u/lPUc status=400 time=1.301083ms
error: 400: {"code":"invalid_request","status":400,"detail":"invalid value \"d\" for parameter \"right\", must be a integer"}

As you can see the generated code validated the incoming request against the types defined in the design.

4. Document

The swagger directory contains the API Swagger (OpenAPI) specification in both YAML and JSON format.

For open source projects hosted on github swagger.goa.design provides a free service that renders the Swagger representation dynamically from goa design packages. Simply set the url query string with the import path to the design package. For example displaying the docs for github.com/goadesign/goa-cellar/design is done by browsing to:

http://swagger.goa.design/?url=goadesign%2Fgoa-cellar%2Fdesign

Note that the above generates the swagger spec dynamically and does not require it to be present in the Github repo.

The Swagger JSON can also easily be served from the documented service itself using a simple Files definition in the design. Edit the file design/design.go and add:

var _ = Resource("swagger", func() {
        Origin("*", func() {
               Methods("GET") // Allow all origins to retrieve the Swagger JSON (CORS)
        })
        Files("/swagger.json", "swagger/swagger.json")
})

Re-run goagen bootstrap -d goa-adder/design and note the new file swagger.go containing the implementation for a controller that serves the swagger.json file.

Mount the newly generated controller by adding the following two lines to the main function in main.go:

cs := NewSwaggerController(service)
app.MountSwaggerController(service, cs)

Recompile and restart the service:

^C
go build
./goa-adder
2016/06/06 10:31:14 [INFO] mount ctrl=Operands action=Add route=GET /add/:left/:right
2016/06/06 10:31:14 [INFO] mount ctrl=Swagger files=swagger/swagger.json route=GET /swagger.json
2016/06/06 10:31:14 [INFO] listen transport=http addr=:8080

Note the new route /swagger.json. Requests made to it return the Swagger specification. The generated controller also takes care of adding the proper CORS headers so that the JSON may be retrieved from browsers using JavaScript served from a different origin (e.g. via Swagger UI). The client also has a new download action:

cd tool/adder-cli
go build
./adder-cli download --help
Download file with given path

Usage:
  adder-cli download [PATH] [flags]

Flags:
      --out string   Output file

Global Flags:
      --dump               Dump HTTP request and response.
  -H, --host string        API hostname (default "localhost:8080")
  -s, --scheme string      Set the requests scheme
  -t, --timeout duration   Set the request timeout (default 20s)

Which can be used like this to download the file swagger.json in the current directory:

./adder-cli download swagger.json
2016/06/06 10:36:24 [INFO] started file=swagger.json id=ciHL2VLt GET=http://localhost:8080/swagger.json
2016/06/06 10:36:24 [INFO] completed file=swagger.json id=ciHL2VLt status=200 time=1.013307ms

We now have a self-documenting API and best of all the documentation is automatically updated as the API design changes.

Resources

Consult the following resources to learn more about goa.

goa.design

goa.design contains further information on goa including a getting started guide, detailed DSL documentation as well as information on how to implement a goa service.

Examples

The examples repo contains simple examples illustrating basic concepts.

The goa-cellar repo contains the implementation for a goa service which demonstrates many aspects of the design language. It is kept up-to-date and provides a reference for testing functionality.

Contributing

Did you fix a bug? write docs or additional tests? or implement some new awesome functionality? You're a rock star!! Just make sure that make succeeds (or that TravisCI is green) and send a PR over.

Documentation

Overview

Package goa provides the runtime support for goa microservices.

Code Generation

goa service development begins with writing the *design* of a service. The design is described using the goa language implemented by the github.com/goadesign/goa/design/apidsl package. The `goagen` tool consumes the metadata produced from executing the design language to generate service specific code that glues the underlying HTTP server with action specific code and data structures.

The goa package contains supporting functionality for the generated code including basic request and response state management through the RequestData and ResponseData structs, error handling via error classes, middleware support via the Middleware data structure as well as decoding and encoding algorithms.

Request Context

The RequestData and ResponseData structs provides access to the request and response state. goa request handlers also accept a golang.org/x/net/Context interface as first parameter so that deadlines and cancelation signals may easily be implemented.

The request state exposes the underlying http.Request object as well as the deserialized payload (request body) and parameters (both path and querystring parameters). Generated action specific contexts wrap the context.Context, ResponseData and RequestData data structures. They expose properly typed fields that correspond to the request parameters and body data structure descriptions appearing in the design.

The response state exposes the response status and body length as well as the underlying ResponseWriter. Action contexts provide action specific helper methods that write the responses as described in the design optionally taking an instance of the media type for responses that contain a body.

Here is an example showing an "update" action corresponding to following design (extract):

Resource("bottle", func() {
    DefaultMedia(Bottle)
    Action("update", func() {
        Params(func() {
            Param("bottleID", Integer)
        })
        Payload(UpdateBottlePayload)
        Response(OK)
        Response(NotFound)
    })
})

The action signature generated by goagen is:

type BottleController interface {
    goa.Controller
    Update(*UpdateBottleContext) error
}

where UpdateBottleContext is:

type UpdateBottleContext struct {
    context.Context      // Timeout and deadline support
    *goa.ResponseData    // Response state access
    *goa.RequestData     // Request state access
    Service *goa.Service // Service handling request
    BottleID  int        // Properly typed parameter fields
    Payload   *UpdateBottlePayload // Properly typed payload
}

and implements:

func (ctx *UpdateBottleContext) OK(resp *Bottle) error
func (ctx *UpdateBottleContext) NotFound() error

The definitions of the Bottle and UpdateBottlePayload data structures are ommitted for brievity.

Controllers

There is one controller interface generated per resource defined via the design language. The interface exposes the controller actions. User code must provide data structures that implement these interfaces when mounting a controller onto a service. The controller data structure should include an anonymous field of type *goa.Controller which takes care of implementing the middleware handling.

Middleware

A goa middleware is a function that takes and returns a Handler. A Handler is a the low level function which handles incoming HTTP requests. goagen generates the handlers code so each handler creates the action specific context and calls the controller action with it.

Middleware can be added to a goa service or a specific controller using the corresponding Use methods. goa comes with a few stock middleware that handle common needs such as logging, panic recovery or using the RequestID header to trace requests across multiple services.

Error Handling

The controller action methods generated by goagen such as the Update method of the BottleController interface shown above all return an error value. goa defines an Error struct that action implementations can use to describe the content of the corresponding HTTP response. Errors can be created using error classes which are functions created via NewErrorClass.

The ErrorHandler middleware maps errors to HTTP responses. Errors that are instances of the Error struct are mapped using the struct fields while other types of errors return responses with status code 500 and the error message in the body.

Validation

The goa design language documented in the dsl package makes it possible to attach validations to data structure definitions. One specific type of validation consists of defining the format that a data structure string field must follow. Example of formats include email, data time, hostnames etc. The ValidateFormat function provides the implementation for the format validation invoked from the code generated by goagen.

Encoding

The goa design language makes it possible to specify the encodings supported by the API both as input (Consumes) and output (Produces). goagen uses that information to registed the corresponding packages with the service encoders and decoders via their Register methods. The service exposes the DecodeRequest and EncodeResponse that implement a simple content type negotiation algorithm for picking the right encoder for the "Content-Type" (decoder) or "Accept" (encoder) request header.

Package goa standardizes on structured error responses: a request that fails because of an invalid input or an unexpected condition produces a response that contains a structured error.

The error data structures returned to clients contains five fields: an ID, a code, a status, a detail and metadata. The ID is unique for the occurrence of the error, it helps correlate the content of the response with the content of the service logs. The code defines the class of error (e.g. "invalid_parameter_type") and the status the corresponding HTTP status (e.g. 400). The detail contains a message specific to the error occurrence. The metadata contains key/value pairs that provide contextual information (name of parameters, value of invalid parameter etc.).

Instances of Error can be created via Error Class functions. See http://goa.design/implement/error_handling.html All instance of errors created via a error class implement the ServiceError interface. This interface is leveraged by the error handler middleware to produce the error responses.

The code generated by goagen calls the helper functions exposed in this file when it encounters invalid data (wrong type, validation errors etc.) such as InvalidParamTypeError, InvalidAttributeTypeError etc. These methods return errors that get merged with any previously encountered error via the Error Merge method. The helper functions are error classes stored in global variable. This means your code can override their values to produce arbitrary error responses.

goa includes an error handler middleware that takes care of mapping back any error returned by previously called middleware or action handler into HTTP responses. If the error was created via an error class then the corresponding content including the HTTP status is used otherwise an internal error is returned. Errors that bubble up all the way to the top (i.e. not handled by the error middleware) also generate an internal error response.

Index

Constants

View Source
const (
	// FormatDateTime defines RFC3339 date time values.
	FormatDateTime Format = "date-time"

	// FormatUUID defines RFC4122 uuid values.
	FormatUUID Format = "uuid"

	// FormatEmail defines RFC5322 email addresses.
	FormatEmail = "email"

	// FormatHostname defines RFC1035 Internet host names.
	FormatHostname = "hostname"

	// FormatIPv4 defines RFC2373 IPv4 address values.
	FormatIPv4 = "ipv4"

	// FormatIPv6 defines RFC2373 IPv6 address values.
	FormatIPv6 = "ipv6"

	// FormatIP defines RFC2373 IPv4 or IPv6 address values.
	FormatIP = "ip"

	// FormatURI defines RFC3986 URI values.
	FormatURI = "uri"

	// FormatMAC defines IEEE 802 MAC-48, EUI-48 or EUI-64 MAC address values.
	FormatMAC = "mac"

	// FormatCIDR defines RFC4632 and RFC4291 CIDR notation IP address values.
	FormatCIDR = "cidr"

	// FormatRegexp Regexp defines regular expression syntax accepted by RE2.
	FormatRegexp = "regexp"
)
View Source
const ErrMissingLogValue = "MISSING"

ErrMissingLogValue is the value used to log keys with missing values

Variables

View Source
var (
	// ErrorMediaIdentifier is the media type identifier used for error responses.
	ErrorMediaIdentifier = "application/vnd.goa.error"

	// ErrBadRequest is a generic bad request error.
	ErrBadRequest = NewErrorClass("bad_request", 400)

	// ErrUnauthorized is a generic unauthorized error.
	ErrUnauthorized = NewErrorClass("unauthorized", 401)

	// ErrInvalidRequest is the class of errors produced by the generated code when a request
	// parameter or payload fails to validate.
	ErrInvalidRequest = NewErrorClass("invalid_request", 400)

	// ErrInvalidEncoding is the error produced when a request body fails to be decoded.
	ErrInvalidEncoding = NewErrorClass("invalid_encoding", 400)

	// ErrRequestBodyTooLarge is the error produced when the size of a request body exceeds
	// MaxRequestBodyLength bytes.
	ErrRequestBodyTooLarge = NewErrorClass("request_too_large", 413)

	// ErrNoAuthMiddleware is the error produced when no auth middleware is mounted for a
	// security scheme defined in the design.
	ErrNoAuthMiddleware = NewErrorClass("no_auth_middleware", 500)

	// ErrInvalidFile is the error produced by ServeFiles when requested to serve non-existant
	// or non-readable files.
	ErrInvalidFile = NewErrorClass("invalid_file", 404)

	// ErrNotFound is the error returned to requests that don't match a registered handler.
	ErrNotFound = NewErrorClass("not_found", 404)

	// ErrInternal is the class of error used for uncaught errors.
	ErrInternal = NewErrorClass("internal", 500)
)

Functions

func AddSample

func AddSample(key []string, val float32)

AddSample adds a sample to an aggregated metric reporting count, min, max, mean, and std deviation Usage:

AddSample([]string{"my","namespace","key"}, 15.0)

func ContextAction

func ContextAction(ctx context.Context) string

ContextAction extracts the action name from the given context.

func ContextController

func ContextController(ctx context.Context) string

ContextController extracts the controller name from the given context.

func ContextError

func ContextError(ctx context.Context) error

ContextError extracts the error from the given context.

func ContextRequiredScopes

func ContextRequiredScopes(ctx context.Context) []string

ContextRequiredScopes extracts the security scopes from the given context. This should be used in auth handlers to validate that the required scopes are present in the JWT or OAuth2 token.

func EmitKey

func EmitKey(key []string, val float32)

EmitKey emits a key/value pair Usage:

EmitKey([]string{"my","namespace","key"}, 15.0)

func IncrCounter

func IncrCounter(key []string, val float32)

IncrCounter increments the counter named by `key` Usage:

IncrCounter([]key{"my","namespace","counter"}, 1.0)

func InvalidAttributeTypeError

func InvalidAttributeTypeError(ctx string, val interface{}, expected string) error

InvalidAttributeTypeError is the error produced when the type of payload field does not match the type defined in the design.

func InvalidEnumValueError

func InvalidEnumValueError(ctx string, val interface{}, allowed []interface{}) error

InvalidEnumValueError is the error produced when the value of a parameter or payload field does not match one the values defined in the design Enum validation.

func InvalidFormatError

func InvalidFormatError(ctx, target string, format Format, formatError error) error

InvalidFormatError is the error produced when the value of a parameter or payload field does not match the format validation defined in the design.

func InvalidLengthError

func InvalidLengthError(ctx string, target interface{}, ln, value int, min bool) error

InvalidLengthError is the error produced when the value of a parameter or payload field does not match the length validation defined in the design.

func InvalidParamTypeError

func InvalidParamTypeError(name string, val interface{}, expected string) error

InvalidParamTypeError is the error produced when the type of a parameter does not match the type defined in the design.

func InvalidPatternError

func InvalidPatternError(ctx, target string, pattern string) error

InvalidPatternError is the error produced when the value of a parameter or payload field does not match the pattern validation defined in the design.

func InvalidRangeError

func InvalidRangeError(ctx string, target interface{}, value interface{}, min bool) error

InvalidRangeError is the error produced when the value of a parameter or payload field does not match the range validation defined in the design. value may be a int or a float64.

func LogError

func LogError(ctx context.Context, msg string, keyvals ...interface{})

LogError extracts the logger from the given context and calls Error on it. This is intended for code that needs portable logging such as the internal code of goa and middleware. User code should use the log adapters instead.

func LogInfo

func LogInfo(ctx context.Context, msg string, keyvals ...interface{})

LogInfo extracts the logger from the given context and calls Info on it. This is intended for code that needs portable logging such as the internal code of goa and middleware. User code should use the log adapters instead.

func Logger

func Logger(ctx context.Context) *log.Logger

Logger returns the logger stored in the context if any, nil otherwise.

func MeasureSince

func MeasureSince(key []string, start time.Time)

MeasureSince creates a timing metric that records the duration of elapsed time since `start` Usage:

MeasureSince([]string{"my","namespace","action"}, time.Now())

Frequently used in a defer:

defer MeasureSince([]string{"my","namespace","action"}, time.Now())

func MergeErrors

func MergeErrors(err, other error) error

MergeErrors updates an error by merging another into it. It first converts other into a ServiceError if not already one - producing an internal error in that case. The merge algorithm is:

* If any of e or other is an internal error then the result is an internal error

* If the status or code of e and other don't match then the result is a 400 "bad_request"

The Detail field is updated by concatenating the Detail fields of e and other separated by a semi-colon. The MetaValues field of is updated by merging the map of other MetaValues into e's where values in e with identical keys to values in other get overwritten.

Merge returns the updated error. This is useful in case the error was initially nil in which case other is returned.

func MissingAttributeError

func MissingAttributeError(ctx, name string) error

MissingAttributeError is the error produced when a request payload is missing a required field.

func MissingHeaderError

func MissingHeaderError(name string) error

MissingHeaderError is the error produced when a request is missing a required header.

func MissingParamError

func MissingParamError(name string) error

MissingParamError is the error produced for requests that are missing path or querystring parameters.

func MissingPayloadError

func MissingPayloadError() error

MissingPayloadError is the error produced when a request is missing a required payload.

func NewContext

func NewContext(ctx context.Context, rw http.ResponseWriter, req *http.Request, params url.Values) context.Context

NewContext builds a new goa request context. If ctx is nil then context.Background() is used.

func NewMetrics

func NewMetrics(conf *metrics.Config, sink metrics.MetricSink) (err error)

NewMetrics initializes goa's metrics instance with the supplied configuration and metrics sink This method is deprecated and SetMetrics should be used instead.

func NewNoOpSink

func NewNoOpSink() metrics.MetricSink

NewNoOpSink returns a NOOP sink.

func NoAuthMiddleware

func NoAuthMiddleware(schemeName string) error

NoAuthMiddleware is the error produced when goa is unable to lookup a auth middleware for a security scheme defined in the design.

func SetGauge

func SetGauge(key []string, val float32)

SetGauge sets the named gauge to the specified value Usage:

SetGauge([]string{"my","namespace"}, 2.0)

func SetMetrics

func SetMetrics(m *metrics.Metrics)

SetMetrics initializes goa's metrics instance with the supplied metrics adapter interface.

func ValidateFormat

func ValidateFormat(f Format, val string) error

ValidateFormat validates a string against a standard format. It returns nil if the string conforms to the format, an error otherwise. The format specification follows the json schema draft 4 validation extension. see http://json-schema.org/latest/json-schema-validation.html#anchor105 Supported formats are:

  • "date-time": RFC3339 date time value
  • "email": RFC5322 email address
  • "hostname": RFC1035 Internet host name
  • "ipv4", "ipv6", "ip": RFC2673 and RFC2373 IP address values
  • "uri": RFC3986 URI value
  • "mac": IEEE 802 MAC-48, EUI-48 or EUI-64 MAC address value
  • "cidr": RFC4632 and RFC4291 CIDR notation IP address value
  • "regexp": Regular expression syntax accepted by RE2

func ValidatePattern

func ValidatePattern(p string, val string) bool

ValidatePattern returns an error if val does not match the regular expression p. It makes an effort to minimize the number of times the regular expression needs to be compiled.

func WithAction

func WithAction(ctx context.Context, action string) context.Context

WithAction creates a context with the given action name.

func WithError

func WithError(ctx context.Context, err error) context.Context

WithError creates a context with the given error.

func WithLogContext

func WithLogContext(ctx context.Context, keyvals ...interface{}) context.Context

WithLogContext instantiates a new logger by appending the given key/value pairs to the context logger and setting the resulting logger in the context.

func WithLogger

func WithLogger(ctx context.Context, logger LogAdapter) context.Context

WithLogger sets the request context logger and returns the resulting new context.

func WithRequiredScopes

func WithRequiredScopes(ctx context.Context, scopes []string) context.Context

WithRequiredScopes builds a context containing the given required scopes.

Types

type APIKeySecurity

type APIKeySecurity struct {
	// Description of the security scheme
	Description string
	// In represents where to check for some data, `query` or `header`
	In Location
	// Name is the name of the `header` or `query` parameter to check for data.
	Name string
}

APIKeySecurity represents the `apiKey` security scheme. It handles a key that can be in the headers or in the query parameters, and does authentication based on that. The Name field represents the key of either the query string parameter or the header, depending on the In field.

type BasicAuthSecurity

type BasicAuthSecurity struct {
	// Description of the security scheme
	Description string
}

BasicAuthSecurity represents the `Basic` security scheme, which consists of a simple login/pass, accessible through Request.BasicAuth().

type Controller

type Controller struct {
	// Controller resource name
	Name string
	// Service that exposes the controller
	Service *Service
	// Controller root context
	Context context.Context
	// MaxRequestBodyLength is the maximum length read from request bodies.
	// Set to 0 to remove the limit altogether. Defaults to 1GB.
	MaxRequestBodyLength int64
	// contains filtered or unexported fields
}

Controller defines the common fields and behavior of generated controllers.

func (*Controller) FileHandler

func (ctrl *Controller) FileHandler(path, filename string) Handler

FileHandler returns a handler that serves files under the given filename for the given route path. The logic for what to do when the filename points to a file vs. a directory is the same as the standard http package ServeFile function. The path may end with a wildcard that matches the rest of the URL (e.g. *filepath). If it does the matching path is appended to filename to form the full file path, so:

c.FileHandler("/index.html", "/www/data/index.html")

Returns the content of the file "/www/data/index.html" when requests are sent to "/index.html" and:

c.FileHandler("/assets/*filepath", "/www/data/assets")

returns the content of the file "/www/data/assets/x/y/z" when requests are sent to "/assets/x/y/z".

func (*Controller) MuxHandler

func (ctrl *Controller) MuxHandler(name string, hdlr Handler, unm Unmarshaler) MuxHandler

MuxHandler wraps a request handler into a MuxHandler. The MuxHandler initializes the request context by loading the request state, invokes the handler and in case of error invokes the controller (if there is one) or Service error handler. This function is intended for the controller generated code. User code should not need to call it directly.

func (*Controller) ServeFiles

func (ctrl *Controller) ServeFiles(path, filename string) error

ServeFiles replies to the request with the contents of the named file or directory. See FileHandler for details.

func (*Controller) Use

func (ctrl *Controller) Use(m Middleware)

Use adds a middleware to the controller. Service-wide middleware should be added via the Service Use method instead.

type DecodeFunc

type DecodeFunc func(context.Context, io.ReadCloser, interface{}) error

DecodeFunc is the function that initialize the unmarshaled payload from the request body.

type Decoder

type Decoder interface {
	Decode(v interface{}) error
}

A Decoder unmarshals an io.Reader into an interface.

func NewGobDecoder

func NewGobDecoder(r io.Reader) Decoder

NewGobDecoder is an adapter for the encoding package gob decoder.

func NewJSONDecoder

func NewJSONDecoder(r io.Reader) Decoder

NewJSONDecoder is an adapter for the encoding package JSON decoder.

func NewXMLDecoder

func NewXMLDecoder(r io.Reader) Decoder

NewXMLDecoder is an adapter for the encoding package XML decoder.

type DecoderFunc

type DecoderFunc func(r io.Reader) Decoder

DecoderFunc instantiates a decoder that decodes data read from the given io reader.

type Encoder

type Encoder interface {
	Encode(v interface{}) error
}

An Encoder marshals from an interface into an io.Writer.

func NewGobEncoder

func NewGobEncoder(w io.Writer) Encoder

NewGobEncoder is an adapter for the encoding package gob encoder.

func NewJSONEncoder

func NewJSONEncoder(w io.Writer) Encoder

NewJSONEncoder is an adapter for the encoding package JSON encoder.

func NewXMLEncoder

func NewXMLEncoder(w io.Writer) Encoder

NewXMLEncoder is an adapter for the encoding package XML encoder.

type EncoderFunc

type EncoderFunc func(w io.Writer) Encoder

EncoderFunc instantiates an encoder that encodes data into the given writer.

type ErrorClass

type ErrorClass func(message interface{}, keyvals ...interface{}) error

ErrorClass is an error generating function. It accepts a message and optional key value pairs and produces errors that implement ServiceError. If the message is a string or a fmt.Stringer then the string value is used. If the message is an error then the string returned by Error() is used. Otherwise the string produced using fmt.Sprintf("%v") is used. The optional key value pairs are intended to provide additional contextual information and are returned to the client.

func NewErrorClass

func NewErrorClass(code string, status int) ErrorClass

NewErrorClass creates a new error class. It is the responsibility of the client to guarantee uniqueness of code.

type ErrorResponse

type ErrorResponse struct {
	// ID is the unique error instance identifier.
	ID string `json:"id" xml:"id" form:"id"`
	// Code identifies the class of errors.
	Code string `json:"code" xml:"code" form:"code"`
	// Status is the HTTP status code used by responses that cary the error.
	Status int `json:"status" xml:"status" form:"status"`
	// Detail describes the specific error occurrence.
	Detail string `json:"detail" xml:"detail" form:"detail"`
	// Meta contains additional key/value pairs useful to clients.
	Meta map[string]interface{} `json:"meta,omitempty" xml:"meta,omitempty" form:"meta,omitempty"`
}

ErrorResponse contains the details of a error response. It implements ServiceError. This struct is mainly intended for clients to decode error responses.

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

Error returns the error occurrence details.

func (*ErrorResponse) ResponseStatus

func (e *ErrorResponse) ResponseStatus() int

ResponseStatus is the status used to build responses.

func (*ErrorResponse) Token

func (e *ErrorResponse) Token() string

Token is the unique error occurrence identifier.

type FileServer

type FileServer interface {
	// FileHandler returns a handler that serves files under the given request path.
	FileHandler(path, filename string) Handler
}

FileServer is the interface implemented by controllers that can serve static files.

type Format

type Format string

Format defines a validation format.

type HTTPDecoder

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

HTTPDecoder is a Decoder that decodes HTTP request or response bodies given a set of known Content-Type to decoder mapping.

func NewHTTPDecoder

func NewHTTPDecoder() *HTTPDecoder

NewHTTPDecoder creates a decoder that maps HTTP content types to low level decoders.

func (*HTTPDecoder) Decode

func (decoder *HTTPDecoder) Decode(v interface{}, body io.Reader, contentType string) error

Decode uses registered Decoders to unmarshal a body based on the contentType.

func (*HTTPDecoder) Register

func (decoder *HTTPDecoder) Register(f DecoderFunc, contentTypes ...string)

Register sets a specific decoder to be used for the specified content types. If a decoder is already registered, it is overwritten.

type HTTPEncoder

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

HTTPEncoder is a Encoder that encodes HTTP request or response bodies given a set of known Content-Type to encoder mapping.

func NewHTTPEncoder

func NewHTTPEncoder() *HTTPEncoder

NewHTTPEncoder creates an encoder that maps HTTP content types to low level encoders.

func (*HTTPEncoder) Encode

func (encoder *HTTPEncoder) Encode(v interface{}, resp io.Writer, accept string) error

Encode uses the registered encoders and given content type to marshal and write the given value using the given writer.

func (*HTTPEncoder) Register

func (encoder *HTTPEncoder) Register(f EncoderFunc, contentTypes ...string)

Register sets a specific encoder to be used for the specified content types. If an encoder is already registered, it is overwritten.

type Handler

Handler defines the request handler signatures.

type JWTSecurity

type JWTSecurity struct {
	// Description of the security scheme
	Description string
	// In represents where to check for the JWT, `query` or `header`
	In Location
	// Name is the name of the `header` or `query` parameter to check for data.
	Name string
	// TokenURL defines the URL where you'd get the JWT tokens.
	TokenURL string
	// Scopes defines a list of scopes for the security scheme, along with their description.
	Scopes map[string]string
}

JWTSecurity represents an api key based scheme, with support for scopes and a token URL.

type Location

type Location string

Location is the enum defining where the value of key based security schemes should be read: either a HTTP request header or a URL querystring value

const LocHeader Location = "header"

LocHeader indicates the secret value should be loaded from the request headers.

const LocQuery Location = "query"

LocQuery indicates the secret value should be loaded from the request URL querystring.

type LogAdapter

type LogAdapter interface {
	// Info logs an informational message.
	Info(msg string, keyvals ...interface{})
	// Error logs an error.
	Error(msg string, keyvals ...interface{})
	// New appends to the logger context and returns the updated logger logger.
	New(keyvals ...interface{}) LogAdapter
}

LogAdapter is the logger interface used by goa to log informational and error messages. Adapters to different logging backends are provided in the logging sub-packages. goa takes care of initializing the logging context with the service, controller and action names.

func ContextLogger

func ContextLogger(ctx context.Context) LogAdapter

ContextLogger extracts the logger from the given context.

func NewLogger

func NewLogger(logger *log.Logger) LogAdapter

NewLogger returns a goa log adpater backed by a log logger.

type Middleware

type Middleware func(Handler) Handler

Middleware represents the canonical goa middleware signature.

func NewMiddleware

func NewMiddleware(m interface{}) (mw Middleware, err error)

NewMiddleware creates a middleware from the given argument. The allowed types for the argument are:

- a goa middleware: goa.Middleware or func(goa.Handler) goa.Handler

- a goa handler: goa.Handler or func(context.Context, http.ResponseWriter, *http.Request) error

- an http middleware: func(http.Handler) http.Handler

- or an http handler: http.Handler or func(http.ResponseWriter, *http.Request)

An error is returned if the given argument is not one of the types above.

type MuxHandler

type MuxHandler func(http.ResponseWriter, *http.Request, url.Values)

MuxHandler provides the low level implementation for an API endpoint. The values argument includes both the querystring and path parameter values.

type Muxer

type Muxer interface {
	MuxHandler(string, Handler, Unmarshaler) MuxHandler
}

Muxer implements an adapter that given a request handler can produce a mux handler.

type NoOpSink

type NoOpSink struct{}

NoOpSink default NOOP metrics recorder

func (*NoOpSink) AddSample

func (md *NoOpSink) AddSample(key []string, val float32)

AddSample method

func (*NoOpSink) EmitKey

func (md *NoOpSink) EmitKey(key []string, val float32)

EmitKey method

func (*NoOpSink) IncrCounter

func (md *NoOpSink) IncrCounter(key []string, val float32)

IncrCounter method

func (*NoOpSink) MeasureSince

func (md *NoOpSink) MeasureSince(key []string, start time.Time)

MeasureSince method

func (*NoOpSink) SetGauge

func (md *NoOpSink) SetGauge(key []string, val float32)

SetGauge method

type OAuth2Security

type OAuth2Security struct {
	// Description of the security scheme
	Description string
	// Flow defines the OAuth2 flow type. See http://swagger.io/specification/#securitySchemeObject
	Flow string
	// TokenURL defines the OAuth2 tokenUrl.  See http://swagger.io/specification/#securitySchemeObject
	TokenURL string
	// AuthorizationURL defines the OAuth2 authorizationUrl.  See http://swagger.io/specification/#securitySchemeObject
	AuthorizationURL string
	// Scopes defines a list of scopes for the security scheme, along with their description.
	Scopes map[string]string
}

OAuth2Security represents the `oauth2` security scheme. It is instantiated by the generated code accordingly to the use of the different `*Security()` DSL functions and `Security()` in the design.

type RequestData

type RequestData struct {
	*http.Request

	// Payload returns the decoded request body.
	Payload interface{}
	// Params contains the raw values for the parameters defined in the design including
	// path parameters, query string parameters and header parameters.
	Params url.Values
}

RequestData provides access to the underlying HTTP request.

func ContextRequest

func ContextRequest(ctx context.Context) *RequestData

ContextRequest extracts the request data from the given context.

type ResettableDecoder

type ResettableDecoder interface {
	Decoder
	Reset(r io.Reader)
}

ResettableDecoder is used to determine whether or not a Decoder can be reset and thus safely reused in a sync.Pool.

type ResettableEncoder

type ResettableEncoder interface {
	Encoder
	Reset(w io.Writer)
}

The ResettableEncoder is used to determine whether or not a Encoder can be reset and thus safely reused in a sync.Pool.

type ResponseData

type ResponseData struct {
	http.ResponseWriter

	// The service used to encode the response.
	Service *Service
	// ErrorCode is the code of the error returned by the action if any.
	ErrorCode string
	// Status is the response HTTP status code.
	Status int
	// Length is the response body length.
	Length int
}

ResponseData provides access to the underlying HTTP response.

func ContextResponse

func ContextResponse(ctx context.Context) *ResponseData

ContextResponse extracts the response data from the given context.

func (*ResponseData) SwitchWriter

func (r *ResponseData) SwitchWriter(rw http.ResponseWriter) http.ResponseWriter

SwitchWriter overrides the underlying response writer. It returns the response writer that was previously set.

func (*ResponseData) Write

func (r *ResponseData) Write(b []byte) (int, error)

Write records the amount of data written and calls the underlying writer.

func (*ResponseData) WriteHeader

func (r *ResponseData) WriteHeader(status int)

WriteHeader records the response status code and calls the underlying writer.

func (*ResponseData) Written

func (r *ResponseData) Written() bool

Written returns true if the response was written, false otherwise.

type ServeMux

type ServeMux interface {
	http.Handler
	// Handle sets the MuxHandler for a given HTTP method and path.
	Handle(method, path string, handle MuxHandler)
	// HandleNotFound sets the MuxHandler invoked for requests that don't match any
	// handler registered with Handle. The values argument given to the handler is
	// always nil.
	HandleNotFound(handle MuxHandler)
	// Lookup returns the MuxHandler associated with the given HTTP method and path.
	Lookup(method, path string) MuxHandler
}

ServeMux is the interface implemented by the service request muxes. It implements http.Handler and makes it possible to register request handlers for specific HTTP methods and request path via the Handle method.

func NewMux

func NewMux() ServeMux

NewMux returns a Mux.

type Service

type Service struct {
	// Name of service used for logging, tracing etc.
	Name string
	// Mux is the service request mux
	Mux ServeMux
	// Context is the root context from which all request contexts are derived.
	// Set values in the root context prior to starting the server to make these values
	// available to all request handlers.
	Context context.Context
	// Request body decoder
	Decoder *HTTPDecoder
	// Response body encoder
	Encoder *HTTPEncoder
	// contains filtered or unexported fields
}

Service is the data structure supporting goa services. It provides methods for configuring a service and running it. At the basic level a service consists of a set of controllers, each implementing a given resource actions. goagen generates global functions - one per resource - that make it possible to mount the corresponding controller onto a service. A service contains the middleware, not found handler, encoders and muxes shared by all its controllers.

func New

func New(name string) *Service

New instantiates a service with the given name.

func (*Service) CancelAll

func (service *Service) CancelAll()

CancelAll sends a cancel signals to all request handlers via the context. See https://godoc.org/golang.org/x/net/context for details on how to handle the signal.

func (*Service) DecodeRequest

func (service *Service) DecodeRequest(req *http.Request, v interface{}) error

DecodeRequest uses the HTTP decoder to unmarshal the request body into the provided value based on the request Content-Type header.

func (*Service) EncodeResponse

func (service *Service) EncodeResponse(ctx context.Context, v interface{}) error

EncodeResponse uses the HTTP encoder to marshal and write the response body based on the request Accept header.

func (*Service) ListenAndServe

func (service *Service) ListenAndServe(addr string) error

ListenAndServe starts a HTTP server and sets up a listener on the given host/port.

func (*Service) ListenAndServeTLS

func (service *Service) ListenAndServeTLS(addr, certFile, keyFile string) error

ListenAndServeTLS starts a HTTPS server and sets up a listener on the given host/port.

func (*Service) LogError

func (service *Service) LogError(msg string, keyvals ...interface{})

LogError logs the error and values at odd indeces using the keys at even indeces of the keyvals slice.

func (*Service) LogInfo

func (service *Service) LogInfo(msg string, keyvals ...interface{})

LogInfo logs the message and values at odd indeces using the keys at even indeces of the keyvals slice.

func (*Service) NewController

func (service *Service) NewController(name string) *Controller

NewController returns a controller for the given resource. This method is mainly intended for use by the generated code. User code shouldn't have to call it directly.

func (*Service) Send

func (service *Service) Send(ctx context.Context, code int, body interface{}) error

Send serializes the given body matching the request Accept header against the service encoders. It uses the default service encoder if no match is found.

func (*Service) Serve

func (service *Service) Serve(l net.Listener) error

Serve accepts incoming HTTP connections on the listener l, invoking the service mux handler for each.

func (*Service) ServeFiles

func (service *Service) ServeFiles(path, filename string) error

ServeFiles create a "FileServer" controller and calls ServerFiles on it.

func (*Service) Use

func (service *Service) Use(m Middleware)

Use adds a middleware to the service wide middleware chain. goa comes with a set of commonly used middleware, see the middleware package. Controller specific middleware should be mounted using the Controller struct Use method instead.

func (*Service) WithLogger

func (service *Service) WithLogger(logger LogAdapter)

WithLogger sets the logger used internally by the service and by Log.

type ServiceError

type ServiceError interface {
	// ServiceError extends the error interface
	error
	// ResponseStatus dictates the status used to build the response sent to the client.
	ResponseStatus() int
	// Token is a unique value associated with the occurrence of the error.
	Token() string
}

ServiceError is the interface implemented by all errors created using a ErrorClass function.

type Unmarshaler

type Unmarshaler func(context.Context, *Service, *http.Request) error

Unmarshaler defines the request payload unmarshaler signatures.

Directories

Path Synopsis
_integration_tests
Package cors provides the means for implementing the server side of CORS, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
Package cors provides the means for implementing the server side of CORS, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
Package design defines types which describe the data types used by action controllers.
Package design defines types which describe the data types used by action controllers.
apidsl
Package apidsl implements the goa design language.
Package apidsl implements the goa design language.
apidsl/test
Package test contains a self-contained DSL test.
Package test contains a self-contained DSL test.
Package encoding provide goa adapters to many different encoders.
Package encoding provide goa adapters to many different encoders.
form
Package form provides a "application/x-www-form-encoding" encoder and decoder.
Package form provides a "application/x-www-form-encoding" encoder and decoder.
codegen
Package codegen contains common code used by all code generators.
Package codegen contains common code used by all code generators.
gen_app
Package genapp provides the generator for the handlers, context data structures and tests of a goa application.
Package genapp provides the generator for the handlers, context data structures and tests of a goa application.
gen_client
Package genclient provides a generator for the client tool and package of a goa application.
Package genclient provides a generator for the client tool and package of a goa application.
gen_controller
Package gencontroller generates the controller code for a given design resource.
Package gencontroller generates the controller code for a given design resource.
gen_js
Package genjs provides a goa generator for a javascript client module.
Package genjs provides a goa generator for a javascript client module.
gen_main
Package genmain provides a generator for a skeleton goa application.
Package genmain provides a generator for a skeleton goa application.
gen_schema
Package genschema provides a generator for the JSON schema controller.
Package genschema provides a generator for the JSON schema controller.
gen_swagger
Package genswagger provides a generator for the JSON swagger controller.
Package genswagger provides a generator for the JSON swagger controller.
meta
Package meta is used to bootstrap the code generator.
Package meta is used to bootstrap the code generator.
Package logging contains logger adapters that make it possible for goa to log messages to various logger backends.
Package logging contains logger adapters that make it possible for goa to log messages to various logger backends.
kit
Package goakit contains an adapter that makes it possible to configure goa so it uses the go-kit log package as logger backend.
Package goakit contains an adapter that makes it possible to configure goa so it uses the go-kit log package as logger backend.
log15
Package goalog15 contains an adapter that makes it possible to configure goa so it uses log15 as logger backend.
Package goalog15 contains an adapter that makes it possible to configure goa so it uses log15 as logger backend.
logrus
Package goalogrus contains an adapter that makes it possible to configure goa so it uses logrus as logger backend.
Package goalogrus contains an adapter that makes it possible to configure goa so it uses logrus as logger backend.

Jump to

Keyboard shortcuts

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