Skip to content

Instantly share code, notes, and snippets.

Created Nov 18, 2016
What would you like to do?
Go Echo server on App Engine Flex
// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Sample endpoints demonstrates a Cloud Endpoints API.
package main
import (
func main() {
r := mux.NewRouter()
http.Handle("/", r)
// echoHandler reads a JSON object from the body, and writes it back out.
func echoHandler(w http.ResponseWriter, r *http.Request) {
var msg interface{}
if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
if _, ok := err.(*json.SyntaxError); ok {
errorf(w, http.StatusBadRequest, "Body was not valid JSON: %v", err)
errorf(w, http.StatusInternalServerError, "Could not get body: %v", err)
b, err := json.Marshal(msg)
if err != nil {
errorf(w, http.StatusInternalServerError, "Could not marshal JSON: %v", err)
// errorf writes a swagger-compliant error response.
func errorf(w http.ResponseWriter, code int, format string, a ...interface{}) {
var out struct {
Code int `json:"code"`
Message string `json:"message"`
out.Code = code
out.Message = fmt.Sprintf(format, a...)
b, err := json.Marshal(out)
if err != nil {
http.Error(w, `{"code": 500, "message": "Could not format JSON for original message."}`, 500)
http.Error(w, string(b), code)
runtime: go
env: flex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment