Created
November 18, 2016 23:43
-
-
Save campoy/7b44f6ec2d9e82d956d34b4989b33192 to your computer and use it in GitHub Desktop.
Go Echo server on App Engine Flex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
runtime: go | |
env: flex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment