github.com/brycereitano/goa@v0.0.0-20170315073847-8ffa6c85e265/goagen/gen_app/writers.go (about)

     1  package genapp
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"regexp"
     7  	"strings"
     8  	"text/template"
     9  
    10  	"sort"
    11  
    12  	"github.com/goadesign/goa/design"
    13  	"github.com/goadesign/goa/goagen/codegen"
    14  )
    15  
    16  // WildcardRegex is the regex used to capture path parameters.
    17  var WildcardRegex = regexp.MustCompile("(?:[^/]*/:([^/]+))+")
    18  
    19  type (
    20  	// ContextsWriter generate codes for a goa application contexts.
    21  	ContextsWriter struct {
    22  		*codegen.SourceFile
    23  		CtxTmpl     *template.Template
    24  		CtxNewTmpl  *template.Template
    25  		CtxRespTmpl *template.Template
    26  		PayloadTmpl *template.Template
    27  		Finalizer   *codegen.Finalizer
    28  		Validator   *codegen.Validator
    29  	}
    30  
    31  	// ControllersWriter generate code for a goa application handlers.
    32  	// Handlers receive a HTTP request, create the action context, call the action code and send the
    33  	// resulting HTTP response.
    34  	ControllersWriter struct {
    35  		*codegen.SourceFile
    36  		CtrlTmpl    *template.Template
    37  		MountTmpl   *template.Template
    38  		handleCORST *template.Template
    39  		Finalizer   *codegen.Finalizer
    40  		Validator   *codegen.Validator
    41  	}
    42  
    43  	// SecurityWriter generate code for action-level security handlers.
    44  	SecurityWriter struct {
    45  		*codegen.SourceFile
    46  		SecurityTmpl *template.Template
    47  	}
    48  
    49  	// ResourcesWriter generate code for a goa application resources.
    50  	// Resources are data structures initialized by the application handlers and passed to controller
    51  	// actions.
    52  	ResourcesWriter struct {
    53  		*codegen.SourceFile
    54  		ResourceTmpl *template.Template
    55  	}
    56  
    57  	// MediaTypesWriter generate code for a goa application media types.
    58  	// Media types are data structures used to render the response bodies.
    59  	MediaTypesWriter struct {
    60  		*codegen.SourceFile
    61  		MediaTypeTmpl *template.Template
    62  		Validator     *codegen.Validator
    63  	}
    64  
    65  	// UserTypesWriter generate code for a goa application user types.
    66  	// User types are data structures defined in the DSL with "Type".
    67  	UserTypesWriter struct {
    68  		*codegen.SourceFile
    69  		UserTypeTmpl *template.Template
    70  		Finalizer    *codegen.Finalizer
    71  		Validator    *codegen.Validator
    72  	}
    73  
    74  	// ContextTemplateData contains all the information used by the template to render the context
    75  	// code for an action.
    76  	ContextTemplateData struct {
    77  		Name         string // e.g. "ListBottleContext"
    78  		ResourceName string // e.g. "bottles"
    79  		ActionName   string // e.g. "list"
    80  		Params       *design.AttributeDefinition
    81  		Payload      *design.UserTypeDefinition
    82  		Headers      *design.AttributeDefinition
    83  		Routes       []*design.RouteDefinition
    84  		Responses    map[string]*design.ResponseDefinition
    85  		API          *design.APIDefinition
    86  		DefaultPkg   string
    87  		Security     *design.SecurityDefinition
    88  	}
    89  
    90  	// ControllerTemplateData contains the information required to generate an action handler.
    91  	ControllerTemplateData struct {
    92  		API            *design.APIDefinition          // API definition
    93  		Resource       string                         // Lower case plural resource name, e.g. "bottles"
    94  		Actions        []map[string]interface{}       // Array of actions, each action has keys "Name", "Routes", "Context" and "Unmarshal"
    95  		FileServers    []*design.FileServerDefinition // File servers
    96  		Encoders       []*EncoderTemplateData         // Encoder data
    97  		Decoders       []*EncoderTemplateData         // Decoder data
    98  		Origins        []*design.CORSDefinition       // CORS policies
    99  		PreflightPaths []string
   100  	}
   101  
   102  	// ResourceData contains the information required to generate the resource GoGenerator
   103  	ResourceData struct {
   104  		Name              string                      // Name of resource
   105  		Identifier        string                      // Identifier of resource media type
   106  		Description       string                      // Description of resource
   107  		Type              *design.MediaTypeDefinition // Type of resource media type
   108  		CanonicalTemplate string                      // CanonicalFormat represents the resource canonical path in the form of a fmt.Sprintf format.
   109  		CanonicalParams   []string                    // CanonicalParams is the list of parameter names that appear in the resource canonical path in order.
   110  	}
   111  
   112  	// EncoderTemplateData contains the data needed to render the registration code for a single
   113  	// encoder or decoder package.
   114  	EncoderTemplateData struct {
   115  		// PackagePath is the Go package path to the package implmenting the encoder/decoder.
   116  		PackagePath string
   117  		// PackageName is the name of the Go package implementing the encoder/decoder.
   118  		PackageName string
   119  		// Function is the name of the package function implementing the decoder/encoder factory.
   120  		Function string
   121  		// MIMETypes is the list of supported MIME types.
   122  		MIMETypes []string
   123  		// Default is true if this encoder/decoder should be set as the default.
   124  		Default bool
   125  	}
   126  )
   127  
   128  // IsPathParam returns true if the given parameter name corresponds to a path parameter for all
   129  // the context action routes. Such parameter is required but does not need to be validated as
   130  // httptreemux takes care of that.
   131  func (c *ContextTemplateData) IsPathParam(param string) bool {
   132  	params := c.Params
   133  	pp := false
   134  	if params.Type.IsObject() {
   135  		for _, r := range c.Routes {
   136  			pp = false
   137  			for _, p := range r.Params() {
   138  				if p == param {
   139  					pp = true
   140  					break
   141  				}
   142  			}
   143  			if !pp {
   144  				break
   145  			}
   146  		}
   147  	}
   148  	return pp
   149  }
   150  
   151  // HasParamAndHeader returns true if the generated struct field name for the given header name
   152  // matches the generated struct field name of a param in c.Params.
   153  func (c *ContextTemplateData) HasParamAndHeader(name string) bool {
   154  	if c.Params == nil || c.Headers == nil {
   155  		return false
   156  	}
   157  
   158  	headerAtt := c.Headers.Type.ToObject()[name]
   159  	headerName := codegen.GoifyAtt(headerAtt, name, true)
   160  	for paramName, paramAtt := range c.Params.Type.ToObject() {
   161  		paramName = codegen.GoifyAtt(paramAtt, paramName, true)
   162  		if headerName == paramName {
   163  			return true
   164  		}
   165  	}
   166  	return false
   167  }
   168  
   169  // MustValidate returns true if code that checks for the presence of the given param must be
   170  // generated.
   171  func (c *ContextTemplateData) MustValidate(name string) bool {
   172  	return c.Params.IsRequired(name) && !c.IsPathParam(name)
   173  }
   174  
   175  // IterateResponses iterates through the responses sorted by status code.
   176  func (c *ContextTemplateData) IterateResponses(it func(*design.ResponseDefinition) error) error {
   177  	m := make(map[int]*design.ResponseDefinition, len(c.Responses))
   178  	var s []int
   179  	for _, resp := range c.Responses {
   180  		status := resp.Status
   181  		m[status] = resp
   182  		s = append(s, status)
   183  	}
   184  	sort.Ints(s)
   185  	for _, status := range s {
   186  		if err := it(m[status]); err != nil {
   187  			return err
   188  		}
   189  	}
   190  	return nil
   191  }
   192  
   193  // NewContextsWriter returns a contexts code writer.
   194  // Contexts provide the glue between the underlying request data and the user controller.
   195  func NewContextsWriter(filename string) (*ContextsWriter, error) {
   196  	file, err := codegen.SourceFileFor(filename)
   197  	if err != nil {
   198  		return nil, err
   199  	}
   200  	return &ContextsWriter{
   201  		SourceFile: file,
   202  		Finalizer:  codegen.NewFinalizer(),
   203  		Validator:  codegen.NewValidator(),
   204  	}, nil
   205  }
   206  
   207  // Execute writes the code for the context types to the writer.
   208  func (w *ContextsWriter) Execute(data *ContextTemplateData) error {
   209  	if err := w.ExecuteTemplate("context", ctxT, nil, data); err != nil {
   210  		return err
   211  	}
   212  	fn := template.FuncMap{
   213  		"newCoerceData":      newCoerceData,
   214  		"arrayAttribute":     arrayAttribute,
   215  		"printVal":           codegen.PrintVal,
   216  		"canonicalHeaderKey": http.CanonicalHeaderKey,
   217  	}
   218  	if err := w.ExecuteTemplate("new", ctxNewT, fn, data); err != nil {
   219  		return err
   220  	}
   221  	if data.Payload != nil {
   222  		found := false
   223  		for _, t := range design.Design.Types {
   224  			if t.TypeName == data.Payload.TypeName {
   225  				found = true
   226  				break
   227  			}
   228  		}
   229  		if !found {
   230  			fn := template.FuncMap{
   231  				"finalizeCode":   w.Finalizer.Code,
   232  				"validationCode": w.Validator.Code,
   233  			}
   234  			if err := w.ExecuteTemplate("payload", payloadT, fn, data); err != nil {
   235  				return err
   236  			}
   237  		}
   238  	}
   239  	return data.IterateResponses(func(resp *design.ResponseDefinition) error {
   240  		respData := map[string]interface{}{
   241  			"Context":  data,
   242  			"Response": resp,
   243  		}
   244  		var mt *design.MediaTypeDefinition
   245  		if resp.Type != nil {
   246  			var ok bool
   247  			if mt, ok = resp.Type.(*design.MediaTypeDefinition); !ok {
   248  				respData["Type"] = resp.Type
   249  				respData["ContentType"] = resp.MediaType
   250  				return w.ExecuteTemplate("response", ctxTRespT, nil, respData)
   251  			}
   252  		} else {
   253  			mt = design.Design.MediaTypeWithIdentifier(resp.MediaType)
   254  		}
   255  		if mt != nil {
   256  			var views []string
   257  			if resp.ViewName != "" {
   258  				views = []string{resp.ViewName}
   259  			} else {
   260  				views = make([]string, len(mt.Views))
   261  				i := 0
   262  				for name := range mt.Views {
   263  					views[i] = name
   264  					i++
   265  				}
   266  				sort.Strings(views)
   267  			}
   268  			for _, view := range views {
   269  				projected, _, err := mt.Project(view)
   270  				if err != nil {
   271  					return err
   272  				}
   273  				respData["Projected"] = projected
   274  				respData["ViewName"] = view
   275  				respData["MediaType"] = mt
   276  				respData["ContentType"] = mt.ContentType
   277  				if view == "default" {
   278  					respData["RespName"] = codegen.Goify(resp.Name, true)
   279  				} else {
   280  					base := fmt.Sprintf("%s%s", resp.Name, strings.Title(view))
   281  					respData["RespName"] = codegen.Goify(base, true)
   282  				}
   283  				if err := w.ExecuteTemplate("response", ctxMTRespT, fn, respData); err != nil {
   284  					return err
   285  				}
   286  			}
   287  			return nil
   288  		}
   289  		return w.ExecuteTemplate("response", ctxNoMTRespT, nil, respData)
   290  	})
   291  }
   292  
   293  // NewControllersWriter returns a handlers code writer.
   294  // Handlers provide the glue between the underlying request data and the user controller.
   295  func NewControllersWriter(filename string) (*ControllersWriter, error) {
   296  	file, err := codegen.SourceFileFor(filename)
   297  	if err != nil {
   298  		return nil, err
   299  	}
   300  	return &ControllersWriter{
   301  		SourceFile: file,
   302  		Finalizer:  codegen.NewFinalizer(),
   303  		Validator:  codegen.NewValidator(),
   304  	}, nil
   305  }
   306  
   307  // WriteInitService writes the initService function
   308  func (w *ControllersWriter) WriteInitService(encoders, decoders []*EncoderTemplateData) error {
   309  	ctx := map[string]interface{}{
   310  		"API":      design.Design,
   311  		"Encoders": encoders,
   312  		"Decoders": decoders,
   313  	}
   314  	if err := w.ExecuteTemplate("service", serviceT, nil, ctx); err != nil {
   315  		return err
   316  	}
   317  	return nil
   318  }
   319  
   320  // Execute writes the handlers GoGenerator
   321  func (w *ControllersWriter) Execute(data []*ControllerTemplateData) error {
   322  	if len(data) == 0 {
   323  		return nil
   324  	}
   325  	for _, d := range data {
   326  		if err := w.ExecuteTemplate("controller", ctrlT, nil, d); err != nil {
   327  			return err
   328  		}
   329  		if err := w.ExecuteTemplate("mount", mountT, nil, d); err != nil {
   330  			return err
   331  		}
   332  		if len(d.Origins) > 0 {
   333  			if err := w.ExecuteTemplate("handleCORS", handleCORST, nil, d); err != nil {
   334  				return err
   335  			}
   336  		}
   337  		fn := template.FuncMap{
   338  			"finalizeCode":   w.Finalizer.Code,
   339  			"validationCode": w.Validator.Code,
   340  		}
   341  		if err := w.ExecuteTemplate("unmarshal", unmarshalT, fn, d); err != nil {
   342  			return err
   343  		}
   344  	}
   345  	return nil
   346  }
   347  
   348  // NewSecurityWriter returns a security functionality code writer.
   349  // Those functionalities are there to support action-middleware related to security.
   350  func NewSecurityWriter(filename string) (*SecurityWriter, error) {
   351  	file, err := codegen.SourceFileFor(filename)
   352  	if err != nil {
   353  		return nil, err
   354  	}
   355  	return &SecurityWriter{SourceFile: file}, nil
   356  }
   357  
   358  // Execute adds the different security schemes and middleware supporting functions.
   359  func (w *SecurityWriter) Execute(schemes []*design.SecuritySchemeDefinition) error {
   360  	return w.ExecuteTemplate("security_schemes", securitySchemesT, nil, schemes)
   361  }
   362  
   363  // NewResourcesWriter returns a contexts code writer.
   364  // Resources provide the glue between the underlying request data and the user controller.
   365  func NewResourcesWriter(filename string) (*ResourcesWriter, error) {
   366  	file, err := codegen.SourceFileFor(filename)
   367  	if err != nil {
   368  		return nil, err
   369  	}
   370  	return &ResourcesWriter{SourceFile: file}, nil
   371  }
   372  
   373  // Execute writes the code for the context types to the writer.
   374  func (w *ResourcesWriter) Execute(data *ResourceData) error {
   375  	return w.ExecuteTemplate("resource", resourceT, nil, data)
   376  }
   377  
   378  // NewMediaTypesWriter returns a contexts code writer.
   379  // Media types contain the data used to render response bodies.
   380  func NewMediaTypesWriter(filename string) (*MediaTypesWriter, error) {
   381  	file, err := codegen.SourceFileFor(filename)
   382  	if err != nil {
   383  		return nil, err
   384  	}
   385  	return &MediaTypesWriter{SourceFile: file, Validator: codegen.NewValidator()}, nil
   386  }
   387  
   388  // Execute writes the code for the context types to the writer.
   389  func (w *MediaTypesWriter) Execute(mt *design.MediaTypeDefinition) error {
   390  	var (
   391  		mLinks *design.UserTypeDefinition
   392  		fn     = template.FuncMap{"validationCode": w.Validator.Code}
   393  	)
   394  	err := mt.IterateViews(func(view *design.ViewDefinition) error {
   395  		p, links, err := mt.Project(view.Name)
   396  		if mLinks == nil {
   397  			mLinks = links
   398  		}
   399  		if err != nil {
   400  			return err
   401  		}
   402  		if err := w.ExecuteTemplate("mediatype", mediaTypeT, fn, p); err != nil {
   403  			return err
   404  		}
   405  		return nil
   406  	})
   407  	if err != nil {
   408  		return err
   409  	}
   410  	if mLinks != nil {
   411  		if err := w.ExecuteTemplate("mediatypelink", mediaTypeLinkT, fn, mLinks); err != nil {
   412  			return err
   413  		}
   414  	}
   415  	return nil
   416  }
   417  
   418  // NewUserTypesWriter returns a contexts code writer.
   419  // User types contain custom data structured defined in the DSL with "Type".
   420  func NewUserTypesWriter(filename string) (*UserTypesWriter, error) {
   421  	file, err := codegen.SourceFileFor(filename)
   422  	if err != nil {
   423  		return nil, err
   424  	}
   425  	return &UserTypesWriter{
   426  		SourceFile: file,
   427  		Finalizer:  codegen.NewFinalizer(),
   428  		Validator:  codegen.NewValidator(),
   429  	}, nil
   430  }
   431  
   432  // Execute writes the code for the context types to the writer.
   433  func (w *UserTypesWriter) Execute(t *design.UserTypeDefinition) error {
   434  	fn := template.FuncMap{
   435  		"finalizeCode":   w.Finalizer.Code,
   436  		"validationCode": w.Validator.Code,
   437  	}
   438  	return w.ExecuteTemplate("types", userTypeT, fn, t)
   439  }
   440  
   441  // newCoerceData is a helper function that creates a map that can be given to the "Coerce" template.
   442  func newCoerceData(name string, att *design.AttributeDefinition, pointer bool, pkg string, depth int) map[string]interface{} {
   443  	return map[string]interface{}{
   444  		"Name":      name,
   445  		"VarName":   codegen.Goify(name, false),
   446  		"Pointer":   pointer,
   447  		"Attribute": att,
   448  		"Pkg":       pkg,
   449  		"Depth":     depth,
   450  	}
   451  }
   452  
   453  // arrayAttribute returns the array element attribute definition.
   454  func arrayAttribute(a *design.AttributeDefinition) *design.AttributeDefinition {
   455  	return a.Type.(*design.Array).ElemType
   456  }
   457  
   458  const (
   459  	// ctxT generates the code for the context data type.
   460  	// template input: *ContextTemplateData
   461  	ctxT = `// {{ .Name }} provides the {{ .ResourceName }} {{ .ActionName }} action context.
   462  type {{ .Name }} struct {
   463  	context.Context
   464  	*goa.ResponseData
   465  	*goa.RequestData
   466  {{ if .Headers }}{{ range $name, $att := .Headers.Type.ToObject }}{{ if not ($.HasParamAndHeader $name) }}{{/*
   467  */}}	{{ goifyatt $att $name true }} {{ if and $att.Type.IsPrimitive ($.Headers.IsPrimitivePointer $name) }}*{{ end }}{{ gotyperef .Type nil 0 false }}
   468  {{ end }}{{ end }}{{ end }}{{ if .Params }}{{ range $name, $att := .Params.Type.ToObject }}{{/*
   469  */}}	{{ goifyatt $att $name true }} {{ if and $att.Type.IsPrimitive ($.Params.IsPrimitivePointer $name) }}*{{ end }}{{ gotyperef .Type nil 0 false }}
   470  {{ end }}{{ end }}{{ if .Payload }}	Payload {{ gotyperef .Payload nil 0 false }}
   471  {{ end }}}
   472  `
   473  	// coerceT generates the code that coerces the generic deserialized
   474  	// data to the actual type.
   475  	// template input: map[string]interface{} as returned by newCoerceData
   476  	coerceT = `{{ if eq .Attribute.Type.Kind 1 }}{{/*
   477  
   478  */}}{{/* BooleanType */}}{{/*
   479  */}}{{ $varName := or (and (not .Pointer) .VarName) tempvar }}{{/*
   480  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := strconv.ParseBool(raw{{ goify .Name true }}); err2 == nil {
   481  {{ if .Pointer }}{{ tabs .Depth }}	{{ $varName }} := &{{ .VarName }}
   482  {{ end }}{{ tabs .Depth }}	{{ .Pkg }} = {{ $varName }}
   483  {{ tabs .Depth }}} else {
   484  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "boolean"))
   485  {{ tabs .Depth }}}
   486  {{ end }}{{ if eq .Attribute.Type.Kind 2 }}{{/*
   487  
   488  */}}{{/* IntegerType */}}{{/*
   489  */}}{{ $tmp := tempvar }}{{/*
   490  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := strconv.Atoi(raw{{ goify .Name true }}); err2 == nil {
   491  {{ if .Pointer }}{{ $tmp2 := tempvar }}{{ tabs .Depth }}	{{ $tmp2 }} := {{ .VarName }}
   492  {{ tabs .Depth }}	{{ $tmp }} := &{{ $tmp2 }}
   493  {{ tabs .Depth }}	{{ .Pkg }} = {{ $tmp }}
   494  {{ else }}{{ tabs .Depth }}	{{ .Pkg }} = {{ .VarName }}
   495  {{ end }}{{ tabs .Depth }}} else {
   496  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "integer"))
   497  {{ tabs .Depth }}}
   498  {{ end }}{{ if eq .Attribute.Type.Kind 3 }}{{/*
   499  
   500  */}}{{/* NumberType */}}{{/*
   501  */}}{{ $varName := or (and (not .Pointer) .VarName) tempvar }}{{/*
   502  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := strconv.ParseFloat(raw{{ goify .Name true }}, 64); err2 == nil {
   503  {{ if .Pointer }}{{ tabs .Depth }}	{{ $varName }} := &{{ .VarName }}
   504  {{ end }}{{ tabs .Depth }}	{{ .Pkg }} = {{ $varName }}
   505  {{ tabs .Depth }}} else {
   506  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "number"))
   507  {{ tabs .Depth }}}
   508  {{ end }}{{ if eq .Attribute.Type.Kind 4 }}{{/*
   509  
   510  */}}{{/* StringType */}}{{/*
   511  */}}{{ tabs .Depth }}{{ .Pkg }} = {{ if .Pointer }}&{{ end }}raw{{ goify .Name true }}
   512  {{ end }}{{ if eq .Attribute.Type.Kind 5 }}{{/*
   513  
   514  */}}{{/* DateTimeType */}}{{/*
   515  */}}{{ $varName := or (and (not .Pointer) .VarName) tempvar }}{{/*
   516  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := time.Parse(time.RFC3339, raw{{ goify .Name true }}); err2 == nil {
   517  {{ if .Pointer }}{{ tabs .Depth }}	{{ $varName }} := &{{ .VarName }}
   518  {{ end }}{{ tabs .Depth }}	{{ .Pkg }} = {{ $varName }}
   519  {{ tabs .Depth }}} else {
   520  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "datetime"))
   521  {{ tabs .Depth }}}
   522  {{ end }}{{ if eq .Attribute.Type.Kind 6 }}{{/*
   523  
   524  */}}{{/* UUIDType */}}{{/*
   525  */}}{{ $varName := or (and (not .Pointer) .VarName) tempvar }}{{/*
   526  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := uuid.FromString(raw{{ goify .Name true }}); err2 == nil {
   527  {{ if .Pointer }}{{ tabs .Depth }}	{{ $varName }} := &{{ .VarName }}
   528  {{ end }}{{ tabs .Depth }}	{{ .Pkg }} = {{ $varName }}
   529  {{ tabs .Depth }}} else {
   530  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "uuid"))
   531  {{ tabs .Depth }}}
   532  {{ end }}{{ if eq .Attribute.Type.Kind 7 }}{{/*
   533  
   534  */}}{{/* AnyType */}}{{/*
   535  */}}{{ if .Pointer }}{{ $tmp := tempvar }}{{ tabs .Depth }}{{ $tmp }} := interface{}(raw{{ goify .Name true }})
   536  {{ tabs .Depth }}{{ .Pkg }} = &{{ $tmp }}
   537  {{ else }}{{ tabs .Depth }}{{ .Pkg }} = raw{{ goify .Name true }}
   538  {{ end }}{{ end }}`
   539  
   540  	// ctxNewT generates the code for the context factory method.
   541  	// template input: *ContextTemplateData
   542  	ctxNewT = `{{ define "Coerce" }}` + coerceT + `{{ end }}` + `
   543  // New{{ goify .Name true }} parses the incoming request URL and body, performs validations and creates the
   544  // context used by the {{ .ResourceName }} controller {{ .ActionName }} action.
   545  func New{{ .Name }}(ctx context.Context, r *http.Request, service *goa.Service) (*{{ .Name }}, error) {
   546  	var err error
   547  	resp := goa.ContextResponse(ctx)
   548  	resp.Service = service
   549  	req := goa.ContextRequest(ctx)
   550  	req.Request = r
   551  	rctx := {{ .Name }}{Context: ctx, ResponseData: resp, RequestData: req}{{/*
   552  */}}
   553  {{ if .Headers }}{{ range $name, $att := .Headers.Type.ToObject }}	header{{ goify $name true }} := req.Header["{{ canonicalHeaderKey $name }}"]
   554  {{ $mustValidate := $.Headers.IsRequired $name }}{{ if $mustValidate }}	if len(header{{ goify $name true }}) == 0 {
   555  		err = goa.MergeErrors(err, goa.MissingHeaderError("{{ $name }}"))
   556  	} else {
   557  {{ else }}	if len(header{{ goify $name true }}) > 0 {
   558  {{ end }}{{/* if $mustValidate */}}{{ if $att.Type.IsArray }}		req.Params["{{ $name }}"] = header{{ goify $name true }}
   559  {{ if eq (arrayAttribute $att).Type.Kind 4 }}		headers := header{{ goify $name true }}
   560  {{ else }}		headers := make({{ gotypedef $att 2 true false }}, len(header{{ goify $name true }}))
   561  		for i, raw{{ goify $name true}} := range header{{ goify $name true}} {
   562  {{ template "Coerce" (newCoerceData $name (arrayAttribute $att) ($.Headers.IsPrimitivePointer $name) "headers[i]" 3) }}{{/*
   563  */}}		}
   564  {{ end }}		{{ printf "rctx.%s" (goifyatt $att $name true) }} = headers
   565  {{ else }}		raw{{ goify $name true}} := header{{ goify $name true}}[0]
   566  		req.Params["{{ $name }}"] = []string{raw{{ goify $name true }}}
   567  {{ template "Coerce" (newCoerceData $name $att ($.Headers.IsPrimitivePointer $name) (printf "rctx.%s" (goifyatt $att $name true)) 2) }}{{ end }}{{/*
   568  */}}{{ $validation := validationChecker $att ($.Headers.IsNonZero $name) ($.Headers.IsRequired $name) ($.Headers.HasDefaultValue $name) (printf "rctx.%s" (goifyatt $att $name true)) $name 2 false }}{{/*
   569  */}}{{ if $validation }}{{ $validation }}
   570  {{ end }}	}
   571  {{ end }}{{ end }}{{/* if .Headers }}{{/*
   572  
   573  */}}{{ if.Params }}{{ range $name, $att := .Params.Type.ToObject }}	param{{ goify $name true }} := req.Params["{{ $name }}"]
   574  {{ $mustValidate := $.MustValidate $name }}{{ if $mustValidate }}	if len(param{{ goify $name true }}) == 0 {
   575  		{{ if $.Params.HasDefaultValue $name }}{{printf "rctx.%s" (goifyatt $att $name true) }} = {{ printVal $att.Type $att.DefaultValue }}{{else}}{{/*
   576  */}}err = goa.MergeErrors(err, goa.MissingParamError("{{ $name }}")){{end}}
   577  	} else {
   578  {{ else }}{{ if $.Params.HasDefaultValue $name }}	if len(param{{ goify $name true }}) == 0 {
   579  		{{printf "rctx.%s" (goifyatt $att $name true) }} = {{ printVal $att.Type $att.DefaultValue }}
   580  	} else {
   581  {{ else }}	if len(param{{ goify $name true }}) > 0 {
   582  {{ end }}{{ end }}{{/* if $mustValidate */}}{{ if $att.Type.IsArray }}{{ if eq (arrayAttribute $att).Type.Kind 4 }}		params := param{{ goify $name true }}
   583  {{ else }}		params := make({{ gotypedef $att 2 true false }}, len(param{{ goify $name true }}))
   584  		for i, raw{{ goify $name true}} := range param{{ goify $name true}} {
   585  {{ template "Coerce" (newCoerceData $name (arrayAttribute $att) ($.Params.IsPrimitivePointer $name) "params[i]" 3) }}{{/*
   586  */}}		}
   587  {{ end }}		{{ printf "rctx.%s" (goifyatt $att $name true) }} = params
   588  {{ else }}		raw{{ goify $name true}} := param{{ goify $name true}}[0]
   589  {{ template "Coerce" (newCoerceData $name $att ($.Params.IsPrimitivePointer $name) (printf "rctx.%s" (goifyatt $att $name true)) 2) }}{{ end }}{{/*
   590  */}}{{ $validation := validationChecker $att ($.Params.IsNonZero $name) ($.Params.IsRequired $name) ($.Params.HasDefaultValue $name) (printf "rctx.%s" (goifyatt $att $name true)) $name 2 false }}{{/*
   591  */}}{{ if $validation }}{{ $validation }}
   592  {{ end }}	}
   593  {{ end }}{{ end }}{{/* if .Params */}}	return &rctx, err
   594  }
   595  `
   596  
   597  	// ctxMTRespT generates the response helpers for responses with media types.
   598  	// template input: map[string]interface{}
   599  	ctxMTRespT = `// {{ goify .RespName true }} sends a HTTP response with status code {{ .Response.Status }}.
   600  func (ctx *{{ .Context.Name }}) {{ goify .RespName true }}(r {{ gotyperef .Projected .Projected.AllRequired 0 false }}) error {
   601  	ctx.ResponseData.Header().Set("Content-Type", "{{ .ContentType }}")
   602  {{ if .Projected.Type.IsArray }}	if r == nil {
   603  		r = {{ gotyperef .Projected .Projected.AllRequired 0 false }}{}
   604  	}
   605  {{ end }}	return ctx.ResponseData.Service.Send(ctx.Context, {{ .Response.Status }}, r)
   606  }
   607  `
   608  
   609  	// ctxTRespT generates the response helpers for responses with overridden types.
   610  	// template input: map[string]interface{}
   611  	ctxTRespT = `// {{ goify .Response.Name true }} sends a HTTP response with status code {{ .Response.Status }}.
   612  func (ctx *{{ .Context.Name }}) {{ goify .Response.Name true }}(r {{ gotyperef .Type nil 0 false }}) error {
   613  	ctx.ResponseData.Header().Set("Content-Type", "{{ .ContentType }}")
   614  	return ctx.ResponseData.Service.Send(ctx.Context, {{ .Response.Status }}, r)
   615  }
   616  `
   617  
   618  	// ctxNoMTRespT generates the response helpers for responses with no known media type.
   619  	// template input: *ContextTemplateData
   620  	ctxNoMTRespT = `
   621  // {{ goify .Response.Name true }} sends a HTTP response with status code {{ .Response.Status }}.
   622  func (ctx *{{ .Context.Name }}) {{ goify .Response.Name true }}({{ if .Response.MediaType }}resp []byte{{ end }}) error {
   623  {{ if .Response.MediaType }}	ctx.ResponseData.Header().Set("Content-Type", "{{ .Response.MediaType }}")
   624  {{ end }}	ctx.ResponseData.WriteHeader({{ .Response.Status }}){{ if .Response.MediaType }}
   625  	_, err := ctx.ResponseData.Write(resp)
   626  	return err{{ else }}
   627  	return nil{{ end }}
   628  }
   629  `
   630  
   631  	// payloadT generates the payload type definition GoGenerator
   632  	// template input: *ContextTemplateData
   633  	payloadT = `{{ $payload := .Payload }}{{ if .Payload.IsObject }}// {{ gotypename .Payload nil 0 true }} is the {{ .ResourceName }} {{ .ActionName }} action payload.{{/*
   634  */}}{{ $privateTypeName := gotypename .Payload nil 1 true }}
   635  type {{ $privateTypeName }} {{ gotypedef .Payload 0 true true }}
   636  
   637  {{ $assignment := finalizeCode .Payload.AttributeDefinition "payload" 1 }}{{ if $assignment }}// Finalize sets the default values defined in the design.
   638  func (payload {{ gotyperef .Payload .Payload.AllRequired 0 true }}) Finalize() {
   639  {{ $assignment }}
   640  }{{ end }}
   641  
   642  {{ $validation := validationCode .Payload.AttributeDefinition false false false "payload" "raw" 1 true }}{{ if $validation }}// Validate runs the validation rules defined in the design.
   643  func (payload {{ gotyperef .Payload .Payload.AllRequired 0 true }}) Validate() (err error) {
   644  {{ $validation }}
   645  	return
   646  }{{ end }}
   647  {{ $typeName := gotypename .Payload .Payload.AllRequired 1 false }}
   648  // Publicize creates {{ $typeName }} from {{ $privateTypeName }}
   649  func (payload {{ gotyperef .Payload .Payload.AllRequired 0 true }}) Publicize() {{ gotyperef .Payload .Payload.AllRequired 0 false }} {
   650  	var pub {{ $typeName }}
   651  	{{ recursivePublicizer .Payload.AttributeDefinition "payload" "pub" 1 }}
   652  	return &pub
   653  }{{ end }}
   654  
   655  // {{ gotypename .Payload nil 0 false }} is the {{ .ResourceName }} {{ .ActionName }} action payload.
   656  type {{ gotypename .Payload nil 1 false }} {{ gotypedef .Payload 0 true false }}
   657  
   658  {{ $validation := validationCode .Payload.AttributeDefinition false false false "payload" "raw" 1 false }}{{ if $validation }}// Validate runs the validation rules defined in the design.
   659  func (payload {{ gotyperef .Payload .Payload.AllRequired 0 false }}) Validate() (err error) {
   660  {{ $validation }}
   661  	return
   662  }{{ end }}
   663  `
   664  	// ctrlT generates the controller interface for a given resource.
   665  	// template input: *ControllerTemplateData
   666  	ctrlT = `// {{ .Resource }}Controller is the controller interface for the {{ .Resource }} actions.
   667  type {{ .Resource }}Controller interface {
   668  	goa.Muxer
   669  {{ if .FileServers }}	goa.FileServer
   670  {{ end }}{{ range .Actions }}	{{ .Name }}(*{{ .Context }}) error
   671  {{ end }}}
   672  `
   673  
   674  	// serviceT generates the service initialization code.
   675  	// template input: *ControllerTemplateData
   676  	serviceT = `
   677  // initService sets up the service encoders, decoders and mux.
   678  func initService(service *goa.Service) {
   679  	// Setup encoders and decoders
   680  {{ range .Encoders }}{{/*
   681  */}}	service.Encoder.Register({{ .PackageName }}.{{ .Function }}, "{{ join .MIMETypes "\", \"" }}")
   682  {{ end }}{{ range .Decoders }}{{/*
   683  */}}	service.Decoder.Register({{ .PackageName }}.{{ .Function }}, "{{ join .MIMETypes "\", \"" }}")
   684  {{ end }}
   685  
   686  	// Setup default encoder and decoder
   687  {{ range .Encoders }}{{ if .Default }}{{/*
   688  */}}	service.Encoder.Register({{ .PackageName }}.{{ .Function }}, "*/*")
   689  {{ end }}{{ end }}{{ range .Decoders }}{{ if .Default }}{{/*
   690  */}}	service.Decoder.Register({{ .PackageName }}.{{ .Function }}, "*/*")
   691  {{ end }}{{ end }}}
   692  `
   693  
   694  	// mountT generates the code for a resource "Mount" function.
   695  	// template input: *ControllerTemplateData
   696  	mountT = `
   697  // Mount{{ .Resource }}Controller "mounts" a {{ .Resource }} resource controller on the given service.
   698  func Mount{{ .Resource }}Controller(service *goa.Service, ctrl {{ .Resource }}Controller) {
   699  	initService(service)
   700  	var h goa.Handler
   701  {{ $res := .Resource }}{{ if .Origins }}{{ range .PreflightPaths }}{{/*
   702  */}}	service.Mux.Handle("OPTIONS", {{ printf "%q" . }}, ctrl.MuxHandler("preflight", handle{{ $res }}Origin(cors.HandlePreflight()), nil))
   703  {{ end }}{{ end }}{{ range .Actions }}{{ $action := . }}
   704  	h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
   705  		// Check if there was an error loading the request
   706  		if err := goa.ContextError(ctx); err != nil {
   707  			return err
   708  		}
   709  		// Build the context
   710  		rctx, err := New{{ .Context }}(ctx, req, service)
   711  		if err != nil {
   712  			return err
   713  		}
   714  {{ if .Payload }}		// Build the payload
   715  		if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil {
   716  			rctx.Payload = rawPayload.({{ gotyperef .Payload nil 1 false }})
   717  {{ if not .PayloadOptional }}		} else {
   718  			return goa.MissingPayloadError()
   719  {{ end }}		}
   720  {{ end }}		return ctrl.{{ .Name }}(rctx)
   721  	}
   722  {{ if .Security }}	h = handleSecurity({{ printf "%q" .Security.Scheme.SchemeName }}, h{{ range .Security.Scopes }}, {{ printf "%q" . }}{{ end }})
   723  {{ end }}{{ if $.Origins }}	h = handle{{ $res }}Origin(h)
   724  {{ end }}{{ range .Routes }}	service.Mux.Handle("{{ .Verb }}", {{ printf "%q" .FullPath }}, ctrl.MuxHandler({{ printf "%q" $action.Name }}, h, {{ if $action.Payload }}{{ $action.Unmarshal }}{{ else }}nil{{ end }}))
   725  	service.LogInfo("mount", "ctrl", {{ printf "%q" $res }}, "action", {{ printf "%q" $action.Name }}, "route", {{ printf "%q" (printf "%s %s" .Verb .FullPath) }}{{ with $action.Security }}, "security", {{ printf "%q" .Scheme.SchemeName }}{{ end }})
   726  {{ end }}{{ end }}{{ range .FileServers }}
   727  	h = ctrl.FileHandler({{ printf "%q" .RequestPath }}, {{ printf "%q" .FilePath }})
   728  {{ if .Security }}	h = handleSecurity({{ printf "%q" .Security.Scheme.SchemeName }}, h{{ range .Security.Scopes }}, {{ printf "%q" . }}{{ end }})
   729  {{ end }}{{ if $.Origins }}	h = handle{{ $res }}Origin(h)
   730  {{ end }}	service.Mux.Handle("GET", "{{ .RequestPath }}", ctrl.MuxHandler("serve", h, nil))
   731  	service.LogInfo("mount", "ctrl", {{ printf "%q" $res }}, "files", {{ printf "%q" .FilePath }}, "route", {{ printf "%q" (printf "GET %s" .RequestPath) }}{{ with .Security }}, "security", {{ printf "%q" .Scheme.SchemeName }}{{ end }})
   732  {{ end }}}
   733  `
   734  
   735  	// handleCORST generates the code that checks whether a CORS request is authorized
   736  	// template input: *ControllerTemplateData
   737  	handleCORST = `// handle{{ .Resource }}Origin applies the CORS response headers corresponding to the origin.
   738  func handle{{ .Resource }}Origin(h goa.Handler) goa.Handler {
   739  {{ range $i, $policy := .Origins }}{{ if $policy.Regexp }}	spec{{$i}} := regexp.MustCompile({{ printf "%q" $policy.Origin }})
   740  {{ end }}{{ end }}
   741  	return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
   742  		origin := req.Header.Get("Origin")
   743  		if origin == "" {
   744  			// Not a CORS request
   745  			return h(ctx, rw, req)
   746  		}
   747  {{ range $i, $policy := .Origins }}		{{ if $policy.Regexp }}if cors.MatchOriginRegexp(origin, spec{{$i}}){{else}}if cors.MatchOrigin(origin, {{ printf "%q" $policy.Origin }}){{end}} {
   748  			ctx = goa.WithLogContext(ctx, "origin", origin)
   749  			rw.Header().Set("Access-Control-Allow-Origin", origin)
   750  {{ if not (eq $policy.Origin "*") }}			rw.Header().Set("Vary", "Origin")
   751  {{ end }}{{ if $policy.Exposed }}			rw.Header().Set("Access-Control-Expose-Headers", "{{ join $policy.Exposed ", " }}")
   752  {{ end }}{{ if gt $policy.MaxAge 0 }}			rw.Header().Set("Access-Control-Max-Age", "{{ $policy.MaxAge }}")
   753  {{ end }}			rw.Header().Set("Access-Control-Allow-Credentials", "{{ $policy.Credentials }}")
   754  			if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" {
   755  				// We are handling a preflight request
   756  {{ if $policy.Methods }}				rw.Header().Set("Access-Control-Allow-Methods", "{{ join $policy.Methods ", " }}")
   757  {{ end }}{{ if $policy.Headers }}				rw.Header().Set("Access-Control-Allow-Headers", "{{ join $policy.Headers ", " }}")
   758  {{ end }}			}
   759  			return h(ctx, rw, req)
   760  		}
   761  {{ end }}
   762  		return h(ctx, rw, req)
   763  	}
   764  }
   765  `
   766  
   767  	// unmarshalT generates the code for an action payload unmarshal function.
   768  	// template input: *ControllerTemplateData
   769  	unmarshalT = `{{ range .Actions }}{{ if .Payload }}
   770  // {{ .Unmarshal }} unmarshals the request body into the context request data Payload field.
   771  func {{ .Unmarshal }}(ctx context.Context, service *goa.Service, req *http.Request) error {
   772  	{{ if .Payload.IsObject }}payload := &{{ gotypename .Payload nil 1 true }}{}
   773  	if err := service.DecodeRequest(req, payload); err != nil {
   774  		return err
   775  	}{{ $assignment := finalizeCode .Payload.AttributeDefinition "payload" 1 }}{{ if $assignment }}
   776  	payload.Finalize(){{ end }}{{ else }}var payload {{ gotypename .Payload nil 1 false }}
   777  	if err := service.DecodeRequest(req, &payload); err != nil {
   778  		return err
   779  	}{{ end }}{{ $validation := validationCode .Payload.AttributeDefinition false false false "payload" "raw" 1 false }}{{ if $validation }}
   780  	if err := payload.Validate(); err != nil {
   781  		// Initialize payload with private data structure so it can be logged
   782  		goa.ContextRequest(ctx).Payload = payload
   783  		return err
   784  	}{{ end }}
   785  	goa.ContextRequest(ctx).Payload = payload{{ if .Payload.IsObject }}.Publicize(){{ end }}
   786  	return nil
   787  }
   788  {{ end }}
   789  {{ end }}`
   790  
   791  	// resourceT generates the code for a resource.
   792  	// template input: *ResourceData
   793  	resourceT = `{{ if .CanonicalTemplate }}// {{ .Name }}Href returns the resource href.
   794  func {{ .Name }}Href({{ if .CanonicalParams }}{{ join .CanonicalParams ", " }} interface{}{{ end }}) string {
   795  {{ range $param := .CanonicalParams }}	param{{$param}} := strings.TrimLeftFunc(fmt.Sprintf("%v", {{$param}}), func(r rune) bool { return r == '/' })
   796  {{ end }}{{ if .CanonicalParams }}	return fmt.Sprintf("{{ .CanonicalTemplate }}", param{{ join .CanonicalParams ", param" }})
   797  {{ else }}	return "{{ .CanonicalTemplate }}"
   798  {{ end }}}
   799  {{ end }}`
   800  
   801  	// mediaTypeT generates the code for a media type.
   802  	// template input: MediaTypeTemplateData
   803  	mediaTypeT = `// {{ gotypedesc . true }}
   804  //
   805  // Identifier: {{ .Identifier }}{{ $typeName := gotypename . .AllRequired 0 false }}
   806  type {{ $typeName }} {{ gotypedef . 0 true false }}
   807  
   808  {{ $validation := validationCode .AttributeDefinition false false false "mt" "response" 1 false }}{{ if $validation }}// Validate validates the {{$typeName}} media type instance.
   809  func (mt {{ gotyperef . .AllRequired 0 false }}) Validate() (err error) {
   810  {{ $validation }}
   811  	return
   812  }
   813  {{ end }}
   814  `
   815  
   816  	// mediaTypeLinkT generates the code for a media type link.
   817  	// template input: MediaTypeLinkTemplateData
   818  	mediaTypeLinkT = `// {{ gotypedesc . true }}{{ $typeName := gotypename . .AllRequired 0 false }}
   819  type {{ $typeName }} {{ gotypedef . 0 true false }}
   820  {{ $validation := validationCode .AttributeDefinition false false false "ut" "response" 1 false }}{{ if $validation }}// Validate validates the {{$typeName}} type instance.
   821  func (ut {{ gotyperef . .AllRequired 0 false }}) Validate() (err error) {
   822  {{ $validation }}
   823  	return
   824  }{{ end }}
   825  `
   826  
   827  	// userTypeT generates the code for a user type.
   828  	// template input: UserTypeTemplateData
   829  	userTypeT = `// {{ gotypedesc . false }}{{ $privateTypeName := gotypename . .AllRequired 0 true }}
   830  type {{ $privateTypeName }} {{ gotypedef . 0 true true }}
   831  {{ $assignment := finalizeCode .AttributeDefinition "ut" 1 }}{{ if $assignment }}// Finalize sets the default values for {{$privateTypeName}} type instance.
   832  func (ut {{ gotyperef . .AllRequired 0 true }}) Finalize() {
   833  {{ $assignment }}
   834  }{{ end }}
   835  {{ $validation := validationCode .AttributeDefinition false false false "ut" "response" 1 true }}{{ if $validation }}// Validate validates the {{$privateTypeName}} type instance.
   836  func (ut {{ gotyperef . .AllRequired 0 true }}) Validate() (err error) {
   837  {{ $validation }}
   838  	return
   839  }{{ end }}
   840  {{ $typeName := gotypename . .AllRequired 0 false }}
   841  // Publicize creates {{ $typeName }} from {{ $privateTypeName }}
   842  func (ut {{ gotyperef . .AllRequired 0 true }}) Publicize() {{ gotyperef . .AllRequired 0 false }} {
   843  	var pub {{ gotypename . .AllRequired 0 false }}
   844  	{{ recursivePublicizer .AttributeDefinition "ut" "pub" 1 }}
   845  	return &pub
   846  }
   847  
   848  // {{ gotypedesc . true }}
   849  type {{ $typeName }} {{ gotypedef . 0 true false }}
   850  {{ $validation := validationCode .AttributeDefinition false false false "ut" "response" 1 false }}{{ if $validation }}// Validate validates the {{$typeName}} type instance.
   851  func (ut {{ gotyperef . .AllRequired 0 false }}) Validate() (err error) {
   852  {{ $validation }}
   853  	return
   854  }{{ end }}
   855  `
   856  
   857  	// securitySchemesT generates the code for the security module.
   858  	// template input: []*design.SecuritySchemeDefinition
   859  	securitySchemesT = `
   860  type (
   861  	// Private type used to store auth handler info in request context
   862  	authMiddlewareKey string
   863  )
   864  
   865  {{ range . }}
   866  {{ $funcName := printf "Use%sMiddleware" (goify .SchemeName true) }}// {{ $funcName }} mounts the {{ .SchemeName }} auth middleware onto the service.
   867  func {{ $funcName }}(service *goa.Service, middleware goa.Middleware) {
   868  	service.Context = context.WithValue(service.Context, authMiddlewareKey({{ printf "%q" .SchemeName }}), middleware)
   869  }
   870  
   871  {{ $funcName := printf "New%sSecurity" (goify .SchemeName true) }}// {{ $funcName }} creates a {{ .SchemeName }} security definition.
   872  func {{ $funcName }}() *goa.{{ .Context }} {
   873  	def := goa.{{ .Context }}{
   874  {{ if eq .Context "APIKeySecurity" }}{{/*
   875  */}}		In:   {{ if eq .In "header" }}goa.LocHeader{{ else }}goa.LocQuery{{ end }},
   876  		Name: {{ printf "%q" .Name }},
   877  {{ else if eq .Context "OAuth2Security" }}{{/*
   878  */}}		Flow:             {{ printf "%q" .Flow }},
   879  		TokenURL:         {{ printf "%q" .TokenURL }},
   880  		AuthorizationURL: {{ printf "%q" .AuthorizationURL }},{{ with .Scopes }}
   881  		Scopes: map[string]string{
   882  {{ range $k, $v := . }}			{{ printf "%q" $k }}: {{ printf "%q" $v }},
   883  {{ end }}{{/*
   884  */}}		},{{ end }}{{/*
   885  */}}{{ else if eq .Context "BasicAuthSecurity" }}{{/*
   886  */}}{{ else if eq .Context "JWTSecurity" }}{{/*
   887  */}}		In:   {{ if eq .In "header" }}goa.LocHeader{{ else }}goa.LocQuery{{ end }},
   888  		Name:             {{ printf "%q" .Name }},
   889  		TokenURL:         {{ printf "%q" .TokenURL }},{{ with .Scopes }}
   890  		Scopes: map[string]string{
   891  {{ range $k, $v := . }}			{{ printf "%q" $k }}: {{ printf "%q" $v }},
   892  {{ end }}{{/*
   893  */}}		},{{ end }}
   894  {{ end }}{{/*
   895  */}}	}
   896  {{ if .Description }} def.Description = {{ printf "%q" .Description }}
   897  {{ end }}	return &def
   898  }
   899  
   900  {{ end }}// handleSecurity creates a handler that runs the auth middleware for the security scheme.
   901  func handleSecurity(schemeName string, h goa.Handler, scopes ...string) goa.Handler {
   902  	return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
   903  		scheme := ctx.Value(authMiddlewareKey(schemeName))
   904  		am, ok := scheme.(goa.Middleware)
   905  		if !ok {
   906  			return goa.NoAuthMiddleware(schemeName)
   907  		}
   908  		ctx = goa.WithRequiredScopes(ctx, scopes)
   909  		return am(h)(ctx, rw, req)
   910  	}
   911  }
   912  `
   913  )