Skip to content

Instantly share code, notes, and snippets.

@campoy
Created November 18, 2016 23:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save campoy/7b44f6ec2d9e82d956d34b4989b33192 to your computer and use it in GitHub Desktop.
Save campoy/7b44f6ec2d9e82d956d34b4989b33192 to your computer and use it in GitHub Desktop.
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 (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"google.golang.org/appengine"
)
func main() {
r := mux.NewRouter()
r.Path("/echo").Methods("POST").
HandlerFunc(echoHandler)
http.Handle("/", r)
appengine.Main()
}
// 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)
return
}
errorf(w, http.StatusInternalServerError, "Could not get body: %v", err)
return
}
b, err := json.Marshal(msg)
if err != nil {
errorf(w, http.StatusInternalServerError, "Could not marshal JSON: %v", err)
return
}
w.Write(b)
}
// 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)
return
}
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