github.com/goldeneggg/goa@v1.3.1/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", "DesignName", "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  		"isPathParam":        data.IsPathParam,
   218  	}
   219  	if err := w.ExecuteTemplate("new", ctxNewT, fn, data); err != nil {
   220  		return err
   221  	}
   222  	if data.Payload != nil {
   223  		found := false
   224  		for _, t := range design.Design.Types {
   225  			if t.TypeName == data.Payload.TypeName {
   226  				found = true
   227  				break
   228  			}
   229  		}
   230  		if !found {
   231  			fn := template.FuncMap{
   232  				"finalizeCode":   w.Finalizer.Code,
   233  				"validationCode": w.Validator.Code,
   234  			}
   235  			if err := w.ExecuteTemplate("payload", payloadT, fn, data); err != nil {
   236  				return err
   237  			}
   238  		}
   239  	}
   240  	return data.IterateResponses(func(resp *design.ResponseDefinition) error {
   241  		respData := map[string]interface{}{
   242  			"Context":  data,
   243  			"Response": resp,
   244  		}
   245  		var mt *design.MediaTypeDefinition
   246  		if resp.Type != nil {
   247  			var ok bool
   248  			if mt, ok = resp.Type.(*design.MediaTypeDefinition); !ok {
   249  				respData["Type"] = resp.Type
   250  				respData["ContentType"] = resp.MediaType
   251  				return w.ExecuteTemplate("response", ctxTRespT, nil, respData)
   252  			}
   253  		} else {
   254  			mt = design.Design.MediaTypeWithIdentifier(resp.MediaType)
   255  		}
   256  		if mt != nil {
   257  			var views []string
   258  			if resp.ViewName != "" {
   259  				views = []string{resp.ViewName}
   260  			} else {
   261  				views = make([]string, len(mt.Views))
   262  				i := 0
   263  				for name := range mt.Views {
   264  					views[i] = name
   265  					i++
   266  				}
   267  				sort.Strings(views)
   268  			}
   269  			for _, view := range views {
   270  				projected, _, err := mt.Project(view)
   271  				if err != nil {
   272  					return err
   273  				}
   274  				respData["Projected"] = projected
   275  				respData["ViewName"] = view
   276  				respData["MediaType"] = mt
   277  				respData["ContentType"] = mt.ContentType
   278  				if view == "default" {
   279  					respData["RespName"] = codegen.Goify(resp.Name, true)
   280  				} else {
   281  					base := fmt.Sprintf("%s%s", resp.Name, strings.Title(view))
   282  					respData["RespName"] = codegen.Goify(base, true)
   283  				}
   284  				if err := w.ExecuteTemplate("response", ctxMTRespT, fn, respData); err != nil {
   285  					return err
   286  				}
   287  			}
   288  			return nil
   289  		}
   290  		return w.ExecuteTemplate("response", ctxNoMTRespT, nil, respData)
   291  	})
   292  }
   293  
   294  // NewControllersWriter returns a handlers code writer.
   295  // Handlers provide the glue between the underlying request data and the user controller.
   296  func NewControllersWriter(filename string) (*ControllersWriter, error) {
   297  	file, err := codegen.SourceFileFor(filename)
   298  	if err != nil {
   299  		return nil, err
   300  	}
   301  	return &ControllersWriter{
   302  		SourceFile: file,
   303  		Finalizer:  codegen.NewFinalizer(),
   304  		Validator:  codegen.NewValidator(),
   305  	}, nil
   306  }
   307  
   308  // WriteInitService writes the initService function
   309  func (w *ControllersWriter) WriteInitService(encoders, decoders []*EncoderTemplateData) error {
   310  	ctx := map[string]interface{}{
   311  		"API":      design.Design,
   312  		"Encoders": encoders,
   313  		"Decoders": decoders,
   314  	}
   315  	return w.ExecuteTemplate("service", serviceT, nil, ctx)
   316  }
   317  
   318  // Execute writes the handlers GoGenerator
   319  func (w *ControllersWriter) Execute(data []*ControllerTemplateData) error {
   320  	if len(data) == 0 {
   321  		return nil
   322  	}
   323  	for _, d := range data {
   324  		if err := w.ExecuteTemplate("controller", ctrlT, nil, d); err != nil {
   325  			return err
   326  		}
   327  		if err := w.ExecuteTemplate("mount", mountT, nil, d); err != nil {
   328  			return err
   329  		}
   330  		if len(d.Origins) > 0 {
   331  			if err := w.ExecuteTemplate("handleCORS", handleCORST, nil, d); err != nil {
   332  				return err
   333  			}
   334  		}
   335  		fn := template.FuncMap{
   336  			"finalizeCode":   w.Finalizer.Code,
   337  			"validationCode": w.Validator.Code,
   338  		}
   339  		if err := w.ExecuteTemplate("unmarshal", unmarshalT, fn, d); err != nil {
   340  			return err
   341  		}
   342  	}
   343  	return nil
   344  }
   345  
   346  // NewSecurityWriter returns a security functionality code writer.
   347  // Those functionalities are there to support action-middleware related to security.
   348  func NewSecurityWriter(filename string) (*SecurityWriter, error) {
   349  	file, err := codegen.SourceFileFor(filename)
   350  	if err != nil {
   351  		return nil, err
   352  	}
   353  	return &SecurityWriter{SourceFile: file}, nil
   354  }
   355  
   356  // Execute adds the different security schemes and middleware supporting functions.
   357  func (w *SecurityWriter) Execute(schemes []*design.SecuritySchemeDefinition) error {
   358  	return w.ExecuteTemplate("security_schemes", securitySchemesT, nil, schemes)
   359  }
   360  
   361  // NewResourcesWriter returns a contexts code writer.
   362  // Resources provide the glue between the underlying request data and the user controller.
   363  func NewResourcesWriter(filename string) (*ResourcesWriter, error) {
   364  	file, err := codegen.SourceFileFor(filename)
   365  	if err != nil {
   366  		return nil, err
   367  	}
   368  	return &ResourcesWriter{SourceFile: file}, nil
   369  }
   370  
   371  // Execute writes the code for the context types to the writer.
   372  func (w *ResourcesWriter) Execute(data *ResourceData) error {
   373  	return w.ExecuteTemplate("resource", resourceT, nil, data)
   374  }
   375  
   376  // NewMediaTypesWriter returns a contexts code writer.
   377  // Media types contain the data used to render response bodies.
   378  func NewMediaTypesWriter(filename string) (*MediaTypesWriter, error) {
   379  	file, err := codegen.SourceFileFor(filename)
   380  	if err != nil {
   381  		return nil, err
   382  	}
   383  	return &MediaTypesWriter{SourceFile: file, Validator: codegen.NewValidator()}, nil
   384  }
   385  
   386  // Execute writes the code for the context types to the writer.
   387  func (w *MediaTypesWriter) Execute(mt *design.MediaTypeDefinition) error {
   388  	var (
   389  		mLinks *design.UserTypeDefinition
   390  		fn     = template.FuncMap{"validationCode": w.Validator.Code}
   391  	)
   392  	err := mt.IterateViews(func(view *design.ViewDefinition) error {
   393  		p, links, err := mt.Project(view.Name)
   394  		if mLinks == nil {
   395  			mLinks = links
   396  		}
   397  		if err != nil {
   398  			return err
   399  		}
   400  		return w.ExecuteTemplate("mediatype", mediaTypeT, fn, p)
   401  	})
   402  	if err != nil {
   403  		return err
   404  	}
   405  	if mLinks != nil {
   406  		if err := w.ExecuteTemplate("mediatypelink", mediaTypeLinkT, fn, mLinks); err != nil {
   407  			return err
   408  		}
   409  	}
   410  	return nil
   411  }
   412  
   413  // NewUserTypesWriter returns a contexts code writer.
   414  // User types contain custom data structured defined in the DSL with "Type".
   415  func NewUserTypesWriter(filename string) (*UserTypesWriter, error) {
   416  	file, err := codegen.SourceFileFor(filename)
   417  	if err != nil {
   418  		return nil, err
   419  	}
   420  	return &UserTypesWriter{
   421  		SourceFile: file,
   422  		Finalizer:  codegen.NewFinalizer(),
   423  		Validator:  codegen.NewValidator(),
   424  	}, nil
   425  }
   426  
   427  // Execute writes the code for the context types to the writer.
   428  func (w *UserTypesWriter) Execute(t *design.UserTypeDefinition) error {
   429  	fn := template.FuncMap{
   430  		"finalizeCode":   w.Finalizer.Code,
   431  		"validationCode": w.Validator.Code,
   432  	}
   433  	return w.ExecuteTemplate("types", userTypeT, fn, t)
   434  }
   435  
   436  // newCoerceData is a helper function that creates a map that can be given to the "Coerce" template.
   437  func newCoerceData(name string, att *design.AttributeDefinition, pointer bool, pkg string, depth int) map[string]interface{} {
   438  	return map[string]interface{}{
   439  		"Name":      name,
   440  		"VarName":   codegen.Goify(name, false),
   441  		"Pointer":   pointer,
   442  		"Attribute": att,
   443  		"Pkg":       pkg,
   444  		"Depth":     depth,
   445  	}
   446  }
   447  
   448  // arrayAttribute returns the array element attribute definition.
   449  func arrayAttribute(a *design.AttributeDefinition) *design.AttributeDefinition {
   450  	return a.Type.(*design.Array).ElemType
   451  }
   452  
   453  const (
   454  	// ctxT generates the code for the context data type.
   455  	// template input: *ContextTemplateData
   456  	ctxT = `// {{ .Name }} provides the {{ .ResourceName }} {{ .ActionName }} action context.
   457  type {{ .Name }} struct {
   458  	context.Context
   459  	*goa.ResponseData
   460  	*goa.RequestData
   461  {{ if .Headers }}{{ range $name, $att := .Headers.Type.ToObject }}{{ if not ($.HasParamAndHeader $name) }}{{/*
   462  */}}	{{ goifyatt $att $name true }} {{ if and $att.Type.IsPrimitive ($.Headers.IsPrimitivePointer $name) }}*{{ end }}{{ gotyperef .Type nil 0 false }}
   463  {{ end }}{{ end }}{{ end }}{{ if .Params }}{{ range $name, $att := .Params.Type.ToObject }}{{/*
   464  */}}	{{ goifyatt $att $name true }} {{ if and $att.Type.IsPrimitive ($.Params.IsPrimitivePointer $name) }}*{{ end }}{{ gotyperef .Type nil 0 false }}
   465  {{ end }}{{ end }}{{ if .Payload }}	Payload {{ gotyperef .Payload nil 0 false }}
   466  {{ end }}}
   467  `
   468  	// coerceT generates the code that coerces the generic deserialized
   469  	// data to the actual type.
   470  	// template input: map[string]interface{} as returned by newCoerceData
   471  	coerceT = `{{ if eq .Attribute.Type.Kind 1 }}{{/*
   472  
   473  */}}{{/* BooleanType */}}{{/*
   474  */}}{{ $varName := or (and (not .Pointer) .VarName) tempvar }}{{/*
   475  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := strconv.ParseBool(raw{{ goify .Name true }}); err2 == nil {
   476  {{ if .Pointer }}{{ tabs .Depth }}	{{ $varName }} := &{{ .VarName }}
   477  {{ end }}{{ tabs .Depth }}	{{ .Pkg }} = {{ $varName }}
   478  {{ tabs .Depth }}} else {
   479  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "boolean"))
   480  {{ tabs .Depth }}}
   481  {{ end }}{{ if eq .Attribute.Type.Kind 2 }}{{/*
   482  
   483  */}}{{/* IntegerType */}}{{/*
   484  */}}{{ $tmp := tempvar }}{{/*
   485  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := strconv.Atoi(raw{{ goify .Name true }}); err2 == nil {
   486  {{ if .Pointer }}{{ $tmp2 := tempvar }}{{ tabs .Depth }}	{{ $tmp2 }} := {{ .VarName }}
   487  {{ tabs .Depth }}	{{ $tmp }} := &{{ $tmp2 }}
   488  {{ tabs .Depth }}	{{ .Pkg }} = {{ $tmp }}
   489  {{ else }}{{ tabs .Depth }}	{{ .Pkg }} = {{ .VarName }}
   490  {{ end }}{{ tabs .Depth }}} else {
   491  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "integer"))
   492  {{ tabs .Depth }}}
   493  {{ end }}{{ if eq .Attribute.Type.Kind 3 }}{{/*
   494  
   495  */}}{{/* NumberType */}}{{/*
   496  */}}{{ $varName := or (and (not .Pointer) .VarName) tempvar }}{{/*
   497  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := strconv.ParseFloat(raw{{ goify .Name true }}, 64); err2 == nil {
   498  {{ if .Pointer }}{{ tabs .Depth }}	{{ $varName }} := &{{ .VarName }}
   499  {{ end }}{{ tabs .Depth }}	{{ .Pkg }} = {{ $varName }}
   500  {{ tabs .Depth }}} else {
   501  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "number"))
   502  {{ tabs .Depth }}}
   503  {{ end }}{{ if eq .Attribute.Type.Kind 4 }}{{/*
   504  
   505  */}}{{/* StringType */}}{{/*
   506  */}}{{ tabs .Depth }}{{ .Pkg }} = {{ if .Pointer }}&{{ end }}raw{{ goify .Name true }}
   507  {{ end }}{{ if eq .Attribute.Type.Kind 5 }}{{/*
   508  
   509  */}}{{/* DateTimeType */}}{{/*
   510  */}}{{ $varName := or (and (not .Pointer) .VarName) tempvar }}{{/*
   511  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := time.Parse(time.RFC3339, raw{{ goify .Name true }}); err2 == nil {
   512  {{ if .Pointer }}{{ tabs .Depth }}	{{ $varName }} := &{{ .VarName }}
   513  {{ end }}{{ tabs .Depth }}	{{ .Pkg }} = {{ $varName }}
   514  {{ tabs .Depth }}} else {
   515  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "datetime"))
   516  {{ tabs .Depth }}}
   517  {{ end }}{{ if eq .Attribute.Type.Kind 6 }}{{/*
   518  
   519  */}}{{/* UUIDType */}}{{/*
   520  */}}{{ $varName := or (and (not .Pointer) .VarName) tempvar }}{{/*
   521  */}}{{ tabs .Depth }}if {{ .VarName }}, err2 := uuid.FromString(raw{{ goify .Name true }}); err2 == nil {
   522  {{ if .Pointer }}{{ tabs .Depth }}	{{ $varName }} := &{{ .VarName }}
   523  {{ end }}{{ tabs .Depth }}	{{ .Pkg }} = {{ $varName }}
   524  {{ tabs .Depth }}} else {
   525  {{ tabs .Depth }}	err = goa.MergeErrors(err, goa.InvalidParamTypeError("{{ .Name }}", raw{{ goify .Name true }}, "uuid"))
   526  {{ tabs .Depth }}}
   527  {{ end }}{{ if eq .Attribute.Type.Kind 7 }}{{/*
   528  
   529  */}}{{/* AnyType */}}{{/*
   530  */}}{{ if .Pointer }}{{ $tmp := tempvar }}{{ tabs .Depth }}{{ $tmp }} := interface{}(raw{{ goify .Name true }})
   531  {{ tabs .Depth }}{{ .Pkg }} = &{{ $tmp }}
   532  {{ else }}{{ tabs .Depth }}{{ .Pkg }} = raw{{ goify .Name true }}
   533  {{ end }}{{ end }}`
   534  
   535  	// ctxNewT generates the code for the context factory method.
   536  	// template input: *ContextTemplateData
   537  	ctxNewT = `{{ define "Coerce" }}` + coerceT + `{{ end }}` + `
   538  // New{{ goify .Name true }} parses the incoming request URL and body, performs validations and creates the
   539  // context used by the {{ .ResourceName }} controller {{ .ActionName }} action.
   540  func New{{ .Name }}(ctx context.Context, r *http.Request, service *goa.Service) (*{{ .Name }}, error) {
   541  	var err error
   542  	resp := goa.ContextResponse(ctx)
   543  	resp.Service = service
   544  	req := goa.ContextRequest(ctx)
   545  	req.Request = r
   546  	rctx := {{ .Name }}{Context: ctx, ResponseData: resp, RequestData: req}{{/*
   547  */}}
   548  {{ if .Headers }}{{ range $name, $att := .Headers.Type.ToObject }}	header{{ goify $name true }} := req.Header["{{ canonicalHeaderKey $name }}"]
   549  {{ $mustValidate := $.Headers.IsRequired $name }}{{ if $mustValidate }}	if len(header{{ goify $name true }}) == 0 {
   550  		err = goa.MergeErrors(err, goa.MissingHeaderError("{{ $name }}"))
   551  	} else {
   552  {{ else }}	if len(header{{ goify $name true }}) > 0 {
   553  {{ end }}{{/* if $mustValidate */}}{{ if $att.Type.IsArray }}		req.Params["{{ $name }}"] = header{{ goify $name true }}
   554  {{ if eq (arrayAttribute $att).Type.Kind 4 }}		headers := header{{ goify $name true }}
   555  {{ else }}		headers := make({{ gotypedef $att 2 true false }}, len(header{{ goify $name true }}))
   556  		for i, raw{{ goify $name true}} := range header{{ goify $name true}} {
   557  {{ template "Coerce" (newCoerceData $name (arrayAttribute $att) ($.Headers.IsPrimitivePointer $name) "headers[i]" 3) }}{{/*
   558  */}}		}
   559  {{ end }}		{{ printf "rctx.%s" (goifyatt $att $name true) }} = headers
   560  {{ else }}		raw{{ goify $name true}} := header{{ goify $name true}}[0]
   561  		req.Params["{{ $name }}"] = []string{raw{{ goify $name true }}}
   562  {{ template "Coerce" (newCoerceData $name $att ($.Headers.IsPrimitivePointer $name) (printf "rctx.%s" (goifyatt $att $name true)) 2) }}{{ end }}{{/*
   563  */}}{{ $validation := validationChecker $att ($.Headers.IsNonZero $name) ($.Headers.IsRequired $name) ($.Headers.HasDefaultValue $name) (printf "rctx.%s" (goifyatt $att $name true)) $name 2 false }}{{/*
   564  */}}{{ if $validation }}{{ $validation }}
   565  {{ end }}	}
   566  {{ end }}{{ end }}{{/* if .Headers }}{{/*
   567  
   568  */}}{{ if .Params }}{{ range $name, $att := .Params.Type.ToObject }}{{/*
   569  */}}	param{{ goify $name true }} := req.Params["{{ $name }}"]
   570  {{ $mustValidate := $.MustValidate $name }}{{ if $mustValidate }}	if len(param{{ goify $name true }}) == 0 {
   571  		{{ if $.Params.HasDefaultValue $name }}{{printf "rctx.%s" (goifyatt $att $name true) }} = {{ printVal $att.Type $att.DefaultValue }}{{else}}{{/*
   572  */}}err = goa.MergeErrors(err, goa.MissingParamError("{{ $name }}")){{end}}
   573  	} else {
   574  {{ else }}{{ if $.Params.HasDefaultValue $name }}	if len(param{{ goify $name true }}) == 0 {
   575  		{{printf "rctx.%s" (goifyatt $att $name true) }} = {{ printVal $att.Type $att.DefaultValue }}
   576  	} else {
   577  {{ else }}	if len(param{{ goify $name true }}) > 0 {
   578  {{ end }}{{ end }}{{/* if $mustValidate */}}{{ if $att.Type.IsArray }}{{ if eq (arrayAttribute $att).Type.Kind 4 }}		params := param{{ goify $name true }}
   579  {{ else }}		params := make({{ gotypedef $att 2 true false }}, len(param{{ goify $name true }}))
   580  		for i, raw{{ goify $name true}} := range param{{ goify $name true}} {
   581  {{ template "Coerce" (newCoerceData $name (arrayAttribute $att) ($.Params.IsPrimitivePointer $name) "params[i]" 3) }}{{/*
   582  */}}		}
   583  {{ end }}		{{ printf "rctx.%s" (goifyatt $att $name true) }} = params
   584  {{ else }}		raw{{ goify $name true}} := param{{ goify $name true}}[0]
   585  {{ template "Coerce" (newCoerceData $name $att ($.Params.IsPrimitivePointer $name) (printf "rctx.%s" (goifyatt $att $name true)) 2) }}{{ end }}{{/*
   586  */}}{{ $validation := validationChecker $att ($.Params.IsNonZero $name) ($.Params.IsRequired $name) ($.Params.HasDefaultValue $name) (printf "rctx.%s" (goifyatt $att $name true)) $name 2 false }}{{/*
   587  */}}{{ if $validation }}{{ $validation }}
   588  {{ end }}	}
   589  {{ end }}{{ end }}{{/* if .Params */}}	return &rctx, err
   590  }
   591  `
   592  
   593  	// ctxMTRespT generates the response helpers for responses with media types.
   594  	// template input: map[string]interface{}
   595  	ctxMTRespT = `// {{ goify .RespName true }} sends a HTTP response with status code {{ .Response.Status }}.
   596  func (ctx *{{ .Context.Name }}) {{ goify .RespName true }}(r {{ gotyperef .Projected .Projected.AllRequired 0 false }}) error {
   597  	if ctx.ResponseData.Header().Get("Content-Type") == "" {
   598  		ctx.ResponseData.Header().Set("Content-Type", "{{ .ContentType }}")
   599  	}
   600  {{ if .Projected.Type.IsArray }}	if r == nil {
   601  		r = {{ gotyperef .Projected .Projected.AllRequired 0 false }}{}
   602  	}
   603  {{ end }}	return ctx.ResponseData.Service.Send(ctx.Context, {{ .Response.Status }}, r)
   604  }
   605  `
   606  
   607  	// ctxTRespT generates the response helpers for responses with overridden types.
   608  	// template input: map[string]interface{}
   609  	ctxTRespT = `// {{ goify .Response.Name true }} sends a HTTP response with status code {{ .Response.Status }}.
   610  func (ctx *{{ .Context.Name }}) {{ goify .Response.Name true }}(r {{ gotyperef .Type nil 0 false }}) error {
   611  	if ctx.ResponseData.Header().Get("Content-Type") == "" {
   612  		ctx.ResponseData.Header().Set("Content-Type", "{{ .ContentType }}")
   613  	}
   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 }}	if ctx.ResponseData.Header().Get("Content-Type") == "" {
   624  		ctx.ResponseData.Header().Set("Content-Type", "{{ .Response.MediaType }}")
   625  	}
   626  {{ end }}	ctx.ResponseData.WriteHeader({{ .Response.Status }}){{ if .Response.MediaType }}
   627  	_, err := ctx.ResponseData.Write(resp)
   628  	return err{{ else }}
   629  	return nil{{ end }}
   630  }
   631  `
   632  
   633  	// payloadT generates the payload type definition GoGenerator
   634  	// template input: *ContextTemplateData
   635  	payloadT = `{{ $payload := .Payload }}{{ if .Payload.IsObject }}// {{ gotypename .Payload nil 0 true }} is the {{ .ResourceName }} {{ .ActionName }} action payload.{{/*
   636  */}}{{ $privateTypeName := gotypename .Payload nil 1 true }}
   637  type {{ $privateTypeName }} {{ gotypedef .Payload 0 true true }}
   638  
   639  {{ $assignment := finalizeCode .Payload.AttributeDefinition "payload" 1 }}{{ if $assignment }}// Finalize sets the default values defined in the design.
   640  func (payload {{ gotyperef .Payload .Payload.AllRequired 0 true }}) Finalize() {
   641  {{ $assignment }}
   642  }{{ end }}
   643  
   644  {{ $validation := validationCode .Payload.AttributeDefinition false false false "payload" "raw" 1 true }}{{ if $validation }}// Validate runs the validation rules defined in the design.
   645  func (payload {{ gotyperef .Payload .Payload.AllRequired 0 true }}) Validate() (err error) {
   646  {{ $validation }}
   647  	return
   648  }{{ end }}
   649  {{ $typeName := gotypename .Payload .Payload.AllRequired 1 false }}
   650  // Publicize creates {{ $typeName }} from {{ $privateTypeName }}
   651  func (payload {{ gotyperef .Payload .Payload.AllRequired 0 true }}) Publicize() {{ gotyperef .Payload .Payload.AllRequired 0 false }} {
   652  	var pub {{ $typeName }}
   653  	{{ recursivePublicizer .Payload.AttributeDefinition "payload" "pub" 1 }}
   654  	return &pub
   655  }{{ end }}
   656  
   657  // {{ gotypename .Payload nil 0 false }} is the {{ .ResourceName }} {{ .ActionName }} action payload.
   658  type {{ gotypename .Payload nil 1 false }} {{ gotypedef .Payload 0 true false }}
   659  
   660  {{ $validation := validationCode .Payload.AttributeDefinition false false false "payload" "raw" 1 false }}{{ if $validation }}// Validate runs the validation rules defined in the design.
   661  func (payload {{ gotyperef .Payload .Payload.AllRequired 0 false }}) Validate() (err error) {
   662  {{ $validation }}
   663  	return
   664  }{{ end }}
   665  `
   666  	// ctrlT generates the controller interface for a given resource.
   667  	// template input: *ControllerTemplateData
   668  	ctrlT = `// {{ .Resource }}Controller is the controller interface for the {{ .Resource }} actions.
   669  type {{ .Resource }}Controller interface {
   670  	goa.Muxer
   671  {{ if .FileServers }}	goa.FileServer
   672  {{ end }}{{ range .Actions }}	{{ .Name }}(*{{ .Context }}) error
   673  {{ end }}}
   674  `
   675  
   676  	// serviceT generates the service initialization code.
   677  	// template input: *ControllerTemplateData
   678  	serviceT = `
   679  // initService sets up the service encoders, decoders and mux.
   680  func initService(service *goa.Service) {
   681  	// Setup encoders and decoders
   682  {{ range .Encoders }}{{/*
   683  */}}	service.Encoder.Register({{ .PackageName }}.{{ .Function }}, "{{ join .MIMETypes "\", \"" }}")
   684  {{ end }}{{ range .Decoders }}{{/*
   685  */}}	service.Decoder.Register({{ .PackageName }}.{{ .Function }}, "{{ join .MIMETypes "\", \"" }}")
   686  {{ end }}
   687  
   688  	// Setup default encoder and decoder
   689  {{ range .Encoders }}{{ if .Default }}{{/*
   690  */}}	service.Encoder.Register({{ .PackageName }}.{{ .Function }}, "*/*")
   691  {{ end }}{{ end }}{{ range .Decoders }}{{ if .Default }}{{/*
   692  */}}	service.Decoder.Register({{ .PackageName }}.{{ .Function }}, "*/*")
   693  {{ end }}{{ end }}}
   694  `
   695  
   696  	// mountT generates the code for a resource "Mount" function.
   697  	// template input: *ControllerTemplateData
   698  	mountT = `
   699  // Mount{{ .Resource }}Controller "mounts" a {{ .Resource }} resource controller on the given service.
   700  func Mount{{ .Resource }}Controller(service *goa.Service, ctrl {{ .Resource }}Controller) {
   701  	initService(service)
   702  	var h goa.Handler
   703  {{ $res := .Resource }}{{ if .Origins }}{{ range .PreflightPaths }}{{/*
   704  */}}	service.Mux.Handle("OPTIONS", {{ printf "%q" . }}, ctrl.MuxHandler("preflight", handle{{ $res }}Origin(cors.HandlePreflight()), nil))
   705  {{ end }}{{ end }}{{ range .Actions }}{{ $action := . }}
   706  	h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
   707  		// Check if there was an error loading the request
   708  		if err := goa.ContextError(ctx); err != nil {
   709  			return err
   710  		}
   711  		// Build the context
   712  		rctx, err := New{{ .Context }}(ctx, req, service)
   713  		if err != nil {
   714  			return err
   715  		}
   716  {{ if .Payload }}		// Build the payload
   717  		if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil {
   718  			rctx.Payload = rawPayload.({{ gotyperef .Payload nil 1 false }})
   719  {{ if not .PayloadOptional }}		} else {
   720  			return goa.MissingPayloadError()
   721  {{ end }}		}
   722  {{ end }}		return ctrl.{{ .Name }}(rctx)
   723  	}
   724  {{ if .Security }}	h = handleSecurity({{ printf "%q" .Security.Scheme.SchemeName }}, h{{ range .Security.Scopes }}, {{ printf "%q" . }}{{ end }})
   725  {{ end }}{{ if $.Origins }}	h = handle{{ $res }}Origin(h)
   726  {{ end }}{{ range .Routes }}	service.Mux.Handle("{{ .Verb }}", {{ printf "%q" .FullPath }}, ctrl.MuxHandler({{ printf "%q" $action.DesignName }}, h, {{ if $action.Payload }}{{ $action.Unmarshal }}{{ else }}nil{{ end }}))
   727  	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 }})
   728  {{ end }}{{ end }}{{ range .FileServers }}
   729  	h = ctrl.FileHandler({{ printf "%q" .RequestPath }}, {{ printf "%q" .FilePath }})
   730  {{ if .Security }}	h = handleSecurity({{ printf "%q" .Security.Scheme.SchemeName }}, h{{ range .Security.Scopes }}, {{ printf "%q" . }}{{ end }})
   731  {{ end }}{{ if $.Origins }}	h = handle{{ $res }}Origin(h)
   732  {{ end }}	service.Mux.Handle("GET", "{{ .RequestPath }}", ctrl.MuxHandler("serve", h, nil))
   733  	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 }})
   734  {{ end }}}
   735  `
   736  
   737  	// handleCORST generates the code that checks whether a CORS request is authorized
   738  	// template input: *ControllerTemplateData
   739  	handleCORST = `// handle{{ .Resource }}Origin applies the CORS response headers corresponding to the origin.
   740  func handle{{ .Resource }}Origin(h goa.Handler) goa.Handler {
   741  {{ range $i, $policy := .Origins }}{{ if $policy.Regexp }}	spec{{$i}} := regexp.MustCompile({{ printf "%q" $policy.Origin }})
   742  {{ end }}{{ end }}
   743  	return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
   744  		origin := req.Header.Get("Origin")
   745  		if origin == "" {
   746  			// Not a CORS request
   747  			return h(ctx, rw, req)
   748  		}
   749  {{ range $i, $policy := .Origins }}		{{ if $policy.Regexp }}if cors.MatchOriginRegexp(origin, spec{{$i}}){{else}}if cors.MatchOrigin(origin, {{ printf "%q" $policy.Origin }}){{end}} {
   750  			ctx = goa.WithLogContext(ctx, "origin", origin)
   751  			rw.Header().Set("Access-Control-Allow-Origin", origin)
   752  {{ if not (eq $policy.Origin "*") }}			rw.Header().Set("Vary", "Origin")
   753  {{ end }}{{ if $policy.Exposed }}			rw.Header().Set("Access-Control-Expose-Headers", "{{ join $policy.Exposed ", " }}")
   754  {{ end }}{{ if gt $policy.MaxAge 0 }}			rw.Header().Set("Access-Control-Max-Age", "{{ $policy.MaxAge }}")
   755  {{ end }}			rw.Header().Set("Access-Control-Allow-Credentials", "{{ $policy.Credentials }}")
   756  			if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" {
   757  				// We are handling a preflight request
   758  {{ if $policy.Methods }}				rw.Header().Set("Access-Control-Allow-Methods", "{{ join $policy.Methods ", " }}")
   759  {{ end }}{{ if $policy.Headers }}				rw.Header().Set("Access-Control-Allow-Headers", "{{ join $policy.Headers ", " }}")
   760  {{ end }}			}
   761  			return h(ctx, rw, req)
   762  		}
   763  {{ end }}
   764  		return h(ctx, rw, req)
   765  	}
   766  }
   767  `
   768  
   769  	// unmarshalT generates the code for an action payload unmarshal function.
   770  	// template input: *ControllerTemplateData
   771  	unmarshalT = `{{ range .Actions }}{{ if .Payload }}
   772  // {{ .Unmarshal }} unmarshals the request body into the context request data Payload field.
   773  func {{ .Unmarshal }}(ctx context.Context, service *goa.Service, req *http.Request) error {
   774  	{{ if .Payload.IsObject }}payload := &{{ gotypename .Payload nil 1 true }}{}
   775  	if err := service.DecodeRequest(req, payload); err != nil {
   776  		return err
   777  	}{{ $assignment := finalizeCode .Payload.AttributeDefinition "payload" 1 }}{{ if $assignment }}
   778  	payload.Finalize(){{ end }}{{ else }}var payload {{ gotypename .Payload nil 1 false }}
   779  	if err := service.DecodeRequest(req, &payload); err != nil {
   780  		return err
   781  	}{{ end }}{{ $validation := validationCode .Payload.AttributeDefinition false false false "payload" "raw" 1 false }}{{ if $validation }}
   782  	if err := payload.Validate(); err != nil {
   783  		// Initialize payload with private data structure so it can be logged
   784  		goa.ContextRequest(ctx).Payload = payload
   785  		return err
   786  	}{{ end }}
   787  	goa.ContextRequest(ctx).Payload = payload{{ if .Payload.IsObject }}.Publicize(){{ end }}
   788  	return nil
   789  }
   790  {{ end }}
   791  {{ end }}`
   792  
   793  	// resourceT generates the code for a resource.
   794  	// template input: *ResourceData
   795  	resourceT = `{{ if .CanonicalTemplate }}// {{ .Name }}Href returns the resource href.
   796  func {{ .Name }}Href({{ if .CanonicalParams }}{{ join .CanonicalParams ", " }} interface{}{{ end }}) string {
   797  {{ range $param := .CanonicalParams }}	param{{$param}} := strings.TrimLeftFunc(fmt.Sprintf("%v", {{$param}}), func(r rune) bool { return r == '/' })
   798  {{ end }}{{ if .CanonicalParams }}	return fmt.Sprintf("{{ .CanonicalTemplate }}", param{{ join .CanonicalParams ", param" }})
   799  {{ else }}	return "{{ .CanonicalTemplate }}"
   800  {{ end }}}
   801  {{ end }}`
   802  
   803  	// mediaTypeT generates the code for a media type.
   804  	// template input: MediaTypeTemplateData
   805  	mediaTypeT = `// {{ gotypedesc . true }}
   806  //
   807  // Identifier: {{ .Identifier }}{{ $typeName := gotypename . .AllRequired 0 false }}
   808  type {{ $typeName }} {{ gotypedef . 0 true false }}
   809  
   810  {{ $validation := validationCode .AttributeDefinition false false false "mt" "response" 1 false }}{{ if $validation }}// Validate validates the {{$typeName}} media type instance.
   811  func (mt {{ gotyperef . .AllRequired 0 false }}) Validate() (err error) {
   812  {{ $validation }}
   813  	return
   814  }
   815  {{ end }}
   816  `
   817  
   818  	// mediaTypeLinkT generates the code for a media type link.
   819  	// template input: MediaTypeLinkTemplateData
   820  	mediaTypeLinkT = `// {{ gotypedesc . true }}{{ $typeName := gotypename . .AllRequired 0 false }}
   821  type {{ $typeName }} {{ gotypedef . 0 true false }}
   822  {{ $validation := validationCode .AttributeDefinition false false false "ut" "response" 1 false }}{{ if $validation }}// Validate validates the {{$typeName}} type instance.
   823  func (ut {{ gotyperef . .AllRequired 0 false }}) Validate() (err error) {
   824  {{ $validation }}
   825  	return
   826  }{{ end }}
   827  `
   828  
   829  	// userTypeT generates the code for a user type.
   830  	// template input: UserTypeTemplateData
   831  	userTypeT = `// {{ gotypedesc . false }}{{ $privateTypeName := gotypename . .AllRequired 0 true }}
   832  type {{ $privateTypeName }} {{ gotypedef . 0 true true }}
   833  {{ $assignment := finalizeCode .AttributeDefinition "ut" 1 }}{{ if $assignment }}// Finalize sets the default values for {{$privateTypeName}} type instance.
   834  func (ut {{ gotyperef . .AllRequired 0 true }}) Finalize() {
   835  {{ $assignment }}
   836  }{{ end }}
   837  {{ $validation := validationCode .AttributeDefinition false false false "ut" "request" 1 true }}{{ if $validation }}// Validate validates the {{$privateTypeName}} type instance.
   838  func (ut {{ gotyperef . .AllRequired 0 true }}) Validate() (err error) {
   839  {{ $validation }}
   840  	return
   841  }{{ end }}
   842  {{ $typeName := gotypename . .AllRequired 0 false }}
   843  // Publicize creates {{ $typeName }} from {{ $privateTypeName }}
   844  func (ut {{ gotyperef . .AllRequired 0 true }}) Publicize() {{ gotyperef . .AllRequired 0 false }} {
   845  	var pub {{ gotypename . .AllRequired 0 false }}
   846  	{{ recursivePublicizer .AttributeDefinition "ut" "pub" 1 }}
   847  	return &pub
   848  }
   849  
   850  // {{ gotypedesc . true }}
   851  type {{ $typeName }} {{ gotypedef . 0 true false }}
   852  {{ $validation := validationCode .AttributeDefinition false false false "ut" "type" 1 false }}{{ if $validation }}// Validate validates the {{$typeName}} type instance.
   853  func (ut {{ gotyperef . .AllRequired 0 false }}) Validate() (err error) {
   854  {{ $validation }}
   855  	return
   856  }{{ end }}
   857  `
   858  
   859  	// securitySchemesT generates the code for the security module.
   860  	// template input: []*design.SecuritySchemeDefinition
   861  	securitySchemesT = `
   862  type (
   863  	// Private type used to store auth handler info in request context
   864  	authMiddlewareKey string
   865  )
   866  
   867  {{ range . }}
   868  {{ $funcName := printf "Use%sMiddleware" (goify .SchemeName true) }}// {{ $funcName }} mounts the {{ .SchemeName }} auth middleware onto the service.
   869  func {{ $funcName }}(service *goa.Service, middleware goa.Middleware) {
   870  	service.Context = context.WithValue(service.Context, authMiddlewareKey({{ printf "%q" .SchemeName }}), middleware)
   871  }
   872  
   873  {{ $funcName := printf "New%sSecurity" (goify .SchemeName true) }}// {{ $funcName }} creates a {{ .SchemeName }} security definition.
   874  func {{ $funcName }}() *goa.{{ .Context }} {
   875  	def := goa.{{ .Context }}{
   876  {{ if eq .Context "APIKeySecurity" }}{{/*
   877  */}}		In:   {{ if eq .In "header" }}goa.LocHeader{{ else }}goa.LocQuery{{ end }},
   878  		Name: {{ printf "%q" .Name }},
   879  {{ else if eq .Context "OAuth2Security" }}{{/*
   880  */}}		Flow:             {{ printf "%q" .Flow }},
   881  		TokenURL:         {{ printf "%q" .TokenURL }},
   882  		AuthorizationURL: {{ printf "%q" .AuthorizationURL }},{{ with .Scopes }}
   883  		Scopes: map[string]string{
   884  {{ range $k, $v := . }}			{{ printf "%q" $k }}: {{ printf "%q" $v }},
   885  {{ end }}{{/*
   886  */}}		},{{ end }}{{/*
   887  */}}{{ else if eq .Context "BasicAuthSecurity" }}{{/*
   888  */}}{{ else if eq .Context "JWTSecurity" }}{{/*
   889  */}}		In:   {{ if eq .In "header" }}goa.LocHeader{{ else }}goa.LocQuery{{ end }},
   890  		Name:             {{ printf "%q" .Name }},
   891  		TokenURL:         {{ printf "%q" .TokenURL }},{{ with .Scopes }}
   892  		Scopes: map[string]string{
   893  {{ range $k, $v := . }}			{{ printf "%q" $k }}: {{ printf "%q" $v }},
   894  {{ end }}{{/*
   895  */}}		},{{ end }}
   896  {{ end }}{{/*
   897  */}}	}
   898  {{ if .Description }} def.Description = {{ printf "%q" .Description }}
   899  {{ end }}	return &def
   900  }
   901  
   902  {{ end }}// handleSecurity creates a handler that runs the auth middleware for the security scheme.
   903  func handleSecurity(schemeName string, h goa.Handler, scopes ...string) goa.Handler {
   904  	return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
   905  		scheme := ctx.Value(authMiddlewareKey(schemeName))
   906  		am, ok := scheme.(goa.Middleware)
   907  		if !ok {
   908  			return goa.NoAuthMiddleware(schemeName)
   909  		}
   910  		ctx = goa.WithRequiredScopes(ctx, scopes)
   911  		return am(h)(ctx, rw, req)
   912  	}
   913  }
   914  `
   915  )