Google App Engine

Google App Engine recipe for Echo

Google App Engine (GAE) provides a range of hosting options from pure PaaS (App Engine Classic)
through Managed VMs to fully self-managed or container-driven Compute Engine instances. Echo
works great with all of these but requires a few changes to the usual examples to run on the
AppEngine Classic and Managed VM options. With a small amount of effort though it’s possible
to produce a codebase that will run on these and also non-managed platforms automatically.

We’ll walk through the changes needed to support each option.

Standalone

Wait? What? I thought this was about AppEngine! Bear with me - the easiest way to show the changes
required is to start with a setup for standalone and work from there plus there’s no reason we
wouldn’t want to retain the ability to run our app anywhere, right?

We take advantage of the go build constraints or tags to change
how we create and run the Echo server for each platform while keeping the rest of the application
(e.g. handler wireup) the same across all of them.

First, we have the normal setup based on the examples but we split it into two files - app.go will
be common to all variations and holds the Echo instance variable. We initialise it from a function
and because it is a var this will happen before any init() functions run - a feature that we’ll
use to connect our handlers later.

app.go

  1. package main
  2. // reference our echo instance and create it early
  3. var e = createMux()

A separate source file contains the function to create the Echo instance and add the static
file handlers and middleware. Note the build tag on the first line which says to use this when not
bulding with appengine or appenginevm tags (which thoese platforms automatically add for us). We also
have the main() function to start serving our app as normal. This should all be very familiar.

app-standalone.go

  1. // +build !appengine,!appenginevm
  2. package main
  3. import (
  4. "github.com/labstack/echo"
  5. "github.com/labstack/echo/middleware"
  6. )
  7. func createMux() *echo.Echo {
  8. e := echo.New()
  9. e.Use(middleware.Recover())
  10. e.Use(middleware.Logger())
  11. e.Use(middleware.Gzip())
  12. e.Static("/", "public")
  13. return e
  14. }
  15. func main() {
  16. e.Logger.Fatal(e.Start(":8080"))
  17. }

The handler-wireup that would normally also be a part of this Echo setup moves to separate files which
take advantage of the ability to have multiple init() functions which run after the e Echo var is
initialised but before the main() function is executed. These allow additional handlers to attach
themselves to the instance - I’ve found the Group feature naturally fits into this pattern with a file
per REST endpoint, often with a higher-level api group created that they attach to instead of the root
Echo instance directly (so things like CORS middleware can be added at this higher common-level).

users.go

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/labstack/echo"
  5. "github.com/labstack/echo/middleware"
  6. )
  7. type (
  8. user struct {
  9. ID string `json:"id"`
  10. Name string `json:"name"`
  11. }
  12. )
  13. var (
  14. users map[string]user
  15. )
  16. func init() {
  17. users = map[string]user{
  18. "1": user{
  19. ID: "1",
  20. Name: "Wreck-It Ralph",
  21. },
  22. }
  23. // hook into the echo instance to create an endpoint group
  24. // and add specific middleware to it plus handlers
  25. g := e.Group("/users")
  26. g.Use(middleware.CORS())
  27. g.POST("", createUser)
  28. g.GET("", getUsers)
  29. g.GET("/:id", getUser)
  30. }
  31. func createUser(c echo.Context) error {
  32. u := new(user)
  33. if err := c.Bind(u); err != nil {
  34. return err
  35. }
  36. users[u.ID] = *u
  37. return c.JSON(http.StatusCreated, u)
  38. }
  39. func getUsers(c echo.Context) error {
  40. return c.JSON(http.StatusOK, users)
  41. }
  42. func getUser(c echo.Context) error {
  43. return c.JSON(http.StatusOK, users[c.Param("id")])
  44. }

If we run our app it should execute as it did before when everything was in one file although we have
at least gained the ability to organize our handlers a little more cleanly.

AppEngine Classic and Managed VMs

So far we’ve seen how to split apart the Echo creation and setup but still have the same app that
still only runs standalone. Now we’ll see how those changes allow us to add support for AppEngine
hosting.

Refer to the AppEngine site for full configuration
and deployment information.

app.yaml configuration file

Both of these are Platform as as Service options running on either sandboxed micro-containers
or managed Compute Engine instances. Both require an app.yaml file to describe the app to
the service. While the app could still serve all it’s static files itself, one of the benefits
of the platform is having Google’s infrastructure handle that for us so it can be offloaded and
the app only has to deal with dynamic requests. The platform also handles logging and http gzip
compression so these can be removed from the codebase as well.

The yaml file also contains other options to control instance size and auto-scaling so for true
deployment freedom you would likely have separate app-classic.yaml and app-vm.yaml files and
this can help when making the transition from AppEngine Classic to Managed VMs.

app-engine.yaml

  1. application: my-application-id # defined when you create your app using google dev console
  2. module: default # see https://cloud.google.com/appengine/docs/go/
  3. version: alpha # you can run multiple versions of an app and A/B test
  4. runtime: go # see https://cloud.google.com/appengine/docs/go/
  5. api_version: go1 # used when appengine supports different go versions
  6. default_expiration: "1d" # for CDN serving of static files (use url versioning if long!)
  7. handlers:
  8. # all the static files that we normally serve ourselves are defined here and Google will handle
  9. # serving them for us from it's own CDN / edge locations. For all the configuration options see:
  10. # https://cloud.google.com/appengine/docs/go/config/appconfig#Go_app_yaml_Static_file_handlers
  11. - url: /
  12. mime_type: text/html
  13. static_files: public/index.html
  14. upload: public/index.html
  15. - url: /favicon.ico
  16. mime_type: image/x-icon
  17. static_files: public/favicon.ico
  18. upload: public/favicon.ico
  19. - url: /scripts
  20. mime_type: text/javascript
  21. static_dir: public/scripts
  22. # static files normally don't touch the server that the app runs on but server-side template files
  23. # needs to be readable by the app. The application_readable option makes sure they are available as
  24. # part of the app deployment onto the instance.
  25. - url: /templates
  26. static_dir: /templates
  27. application_readable: true
  28. # finally, we route all other requests to our application. The script name just means "the go app"
  29. - url: /.*
  30. script: _go_app

Router configuration

We’ll now use the build constraints again like we did when creating
our app-standalone.go instance but this time with the opposite tags to use this file if the build has
the appengine or appenginevm tags (added automatically when deploying to these platforms).

This allows us to replace the createMux() function to create our Echo server without any of the
static file handling and logging + gzip middleware which is no longer required. Also worth nothing is
that GAE classic provides a wrapper to handle serving the app so instead of a main() function where
we run the server, we instead wire up the router to the default http.Handler instead.

app-engine.go

  1. // +build appengine
  2. package main
  3. import (
  4. "net/http"
  5. "github.com/labstack/echo"
  6. )
  7. func createMux() *echo.Echo {
  8. e := echo.New()
  9. // note: we don't need to provide the middleware or static handlers, that's taken care of by the platform
  10. // app engine has it's own "main" wrapper - we just need to hook echo into the default handler
  11. http.Handle("/", e)
  12. return e
  13. }

Managed VMs are slightly different. They are expected to respond to requests on port 8080 as well
as special health-check requests used by the service to detect if an instance is still running in
order to provide automated failover and instance replacement. The google.golang.org/appengine
package provides this for us so we have a slightly different version for Managed VMs:

app-managed.go

  1. // +build appenginevm
  2. package main
  3. import (
  4. "net/http"
  5. "github.com/labstack/echo"
  6. "google.golang.org/appengine"
  7. )
  8. func createMux() *echo.Echo {
  9. e := echo.New()
  10. // note: we don't need to provide the middleware or static handlers
  11. // for the appengine vm version - that's taken care of by the platform
  12. return e
  13. }
  14. func main() {
  15. // the appengine package provides a convenient method to handle the health-check requests
  16. // and also run the app on the correct port. We just need to add Echo to the default handler
  17. e := echo.New(":8080")
  18. http.Handle("/", e)
  19. appengine.Main()
  20. }

So now we have three different configurations. We can build and run our app as normal so it can
be executed locally, on a full Compute Engine instance or any other traditional hosting provider
(including EC2, Docker etc…). This build will ignore the code in appengine and appenginevm tagged
files and the app.yaml file is meaningless to anything other than the AppEngine platform.

We can also run locally using the Google AppEngine SDK for Go
either emulating AppEngine Classic:

  1. goapp serve

Or Managed VMs:

  1. gcloud config set project [your project id]
  2. gcloud preview app run .

And of course we can deploy our app to both of these platforms for easy and inexpensive auto-scaling joy.

Depending on what your app actually does it’s possible you may need to make other changes to allow
switching between AppEngine provided service such as Datastore and alternative storage implementations
such as MongoDB. A combination of go interfaces and build constraints can make this fairly straightforward
but is outside the scope of this example.

Source Code

Maintainers