// BottleMedia defines the media type used to render bottles. var BottleMedia = MediaType("application/vnd.goa.example.bottle+json", func() { Description("A bottle of wine") Attributes(func() { // Attributes define the media type shape. Attribute("id", Integer, "Unique bottle ID") Attribute("href", String, "API href for making requests on the bottle") Attribute("name", String, "Name of wine") Required("id", "href", "name") }) View("default", func() { // View defines a rendering of the media type. Attribute("id") // Media types may have multiple views and must Attribute("href") // have a "default" view. Attribute("name") }) })
type BottleController interface { goa.Muxer Show(*ShowBottleContext) error }
看下 app/contexts.go 中的 ShowBottleContext:
1 2 3 4 5 6 7 8
// ShowBottleContext provides the bottle show action context. type ShowBottleContext struct { context.Context *goa.ResponseData *goa.RequestData BottleID int }
// OK sends a HTTP response with status code 200. func(ctx *ShowBottleContext) OK(r *GoaExampleBottle) error { ctx.ResponseData.Header().Set("Content-Type", "application/vnd.goa.example.bottle") return ctx.Service.Send(ctx.Context, 200, r) }
// NotFound sends a HTTP response with status code 404. func(ctx *ShowBottleContext) NotFound() error { ctx.ResponseData.WriteHeader(404) returnnil }
goagen 还在 bottle.go 中生成了一个空的控制器实现,所以我们剩下要做的就是提供一个实际的实现。打开文件 bottle.go 并用现有的 Show 方法替换:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Show implements the "show" action of the "bottles" controller. func(c *BottleController) Show(ctx *app.ShowBottleContext) error { if ctx.BottleID == 0 { // Emulate a missing record with ID 0 return ctx.NotFound() } // Build the resource using the generated data structure bottle := app.GoaExampleBottle{ ID: ctx.BottleID, Name: fmt.Sprintf("Bottle #%d", ctx.BottleID), Href: app.BottleHref(ctx.BottleID), }
// Let the generated code produce the HTTP response using the // media type described in the design (BottleMedia). return ctx.OK(&bottle) }
在我们构建和运行应用程序之前,让我们先来看看 main.go:该文件包含 main 的默认实现,它实例化一个新的 goa 服务,初始化默认中间件,安装 bottle 控制器并运行 HTTP 服务器。