コード例 #1
0
ファイル: api.go プロジェクト: bketelsen/goa
// ResponseTemplate defines a response template that action definitions can use to describe their
// responses. The template may specify the HTTP response status, header specification and body media
// type. The template consists of a name and an anonymous function. The function is called when an
// action uses the template to define a response. Response template functions accept string
// parameters they can use to define the response fields. Here is an example of a response template
// definition that uses a function with one argument corresponding to the name of the response body
// media type:
//
//	ResponseTemplate(OK, func(mt string) {
//		Status(200)				// OK response uses status code 200
//		Media(mt)				// Media type name set by action definition
//		Headers(func() {
//			Header("X-Request-Id", func() {	// X-Request-Id header contains a string
//				Pattern("[0-9A-F]+")	// Regexp used to validate the response header content
//			})
//			Required("X-Request-Id")	// Header is mandatory
//		})
//	})
//
// This template can the be used by actions to define the OK response as follows:
//
//	Response(OK, "vnd.goa.example")
//
// goa comes with a set of predefined response templates (one per standard HTTP status code). The
// OK template is the only one that accepts an argument. It is used as shown in the example above to
// set the response media type. Other predefined templates do not use arguments. ResponseTemplate
// makes it possible to define additional response templates specific to the API.
func ResponseTemplate(name string, p interface{}) {
	var v *design.APIVersionDefinition
	if a, ok := apiDefinition(false); ok {
		v = a.APIVersionDefinition
	} else if ver, ok := versionDefinition(true); ok {
		v = ver
	}
	if v == nil {
		return
	}
	if v.Responses == nil {
		v.Responses = make(map[string]*design.ResponseDefinition)
	}
	if v.ResponseTemplates == nil {
		v.ResponseTemplates = make(map[string]*design.ResponseTemplateDefinition)
	}
	if _, ok := v.Responses[name]; ok {
		ReportError("multiple definitions for response template %s", name)
		return
	}
	if _, ok := v.ResponseTemplates[name]; ok {
		ReportError("multiple definitions for response template %s", name)
		return
	}

	setupResponseTemplate(v, name, p)
}