Skip to content

Instantly share code, notes, and snippets.

@campoy
Created November 18, 2016 23:48
Show Gist options
  • Select an option

  • Save campoy/e114541600fba4a63c8df492c27f3db2 to your computer and use it in GitHub Desktop.

Select an option

Save campoy/e114541600fba4a63c8df492c27f3db2 to your computer and use it in GitHub Desktop.
Go Echo Server on Flex with Endpoints
// 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
beta_settings:
# Enable Google Cloud Endpoints API management.
use_endpoints_api_management: true
# Specify the Swagger API specification.
endpoints_swagger_spec_file: swagger.yaml
swagger: "2.0"
info:
description: "A simple Google Cloud Endpoints API example."
title: "Endpoints Example"
version: "1.0.0"
host: "cloud-minute-endpoints.appspot.com"
basePath: "/"
consumes:
- "application/json"
produces:
- "application/json"
schemes:
- "https"
paths:
"/echo":
post:
description: "Echo back a given message."
operationId: "echo"
produces:
- "application/json"
responses:
200:
description: "Echo"
schema:
$ref: "#/definitions/echoMessage"
parameters:
- description: "Message to echo"
in: body
name: message
required: true
schema:
$ref: "#/definitions/echoMessage"
security:
- api_key: []
definitions:
echoMessage:
properties:
message:
type: "string"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment