Match content-type of incoming request. Fix for Alexa.

This commit is contained in:
Alex 2017-01-28 12:26:30 +00:00
parent b9838291b2
commit 52266a6741
13 changed files with 161 additions and 61 deletions

View File

@ -72,7 +72,6 @@ services:
environment:
no_proxy: "gateway"
https_proxy: $https_proxy
nodeinfo:
image: alexellis2/faas-nodeinfo:latest
depends_on:
@ -105,6 +104,19 @@ services:
no_proxy: "gateway"
https_proxy: $https_proxy
# alexacolorchange:
# image: alexellis2/faas-alexachangecolorintent
# depends_on:
# - gateway
# networks:
# - functions
# environment:
# no_proxy: "gateway"
# https_proxy: $https_proxy
networks:
functions:
driver: overlay

View File

@ -10,4 +10,4 @@ docker rm -f gateway_extract
echo Building alexellis2/faas-gateway:latest
docker build -t alexellis2/faas-gateway:latest-dev3 .
docker build -t alexellis2/faas-gateway:latest-dev4 .

View File

@ -3,24 +3,21 @@ package handlers
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/alexellis/faas/gateway/metrics"
"github.com/alexellis/faas/gateway/requests"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/gorilla/mux"
)
// makeProxy creates a proxy for HTTP web requests which can be routed to a function.
// MakeProxy creates a proxy for HTTP web requests which can be routed to a function.
func MakeProxy(metrics metrics.MetricOptions, wildcard bool, c *client.Client, logger *logrus.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
metrics.GatewayRequestsTotal.Inc()
@ -40,43 +37,13 @@ func MakeProxy(metrics metrics.MetricOptions, wildcard bool, c *client.Client, l
} else if len(header) > 0 {
lookupInvoke(w, r, metrics, header[0], c, logger)
defer r.Body.Close()
} else {
requestBody, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
alexaService := IsAlexa(requestBody)
fmt.Println(alexaService)
defer r.Body.Close()
if len(alexaService.Session.SessionId) > 0 &&
len(alexaService.Session.Application.ApplicationId) > 0 &&
len(alexaService.Request.Intent.Name) > 0 {
fmt.Println("Alexa SDK request found")
fmt.Printf("SessionId=%s, Intent=%s, AppId=%s\n", alexaService.Session.SessionId, alexaService.Request.Intent.Name, alexaService.Session.Application.ApplicationId)
invokeService(w, r, metrics, alexaService.Request.Intent.Name, requestBody, logger)
} else {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Provide an x-function header or a valid Alexa SDK request."))
w.Write([]byte("Provide a named /function URL or an x-function header."))
defer r.Body.Close()
}
}
}
}
}
func IsAlexa(requestBody []byte) requests.AlexaRequestBody {
body := requests.AlexaRequestBody{}
buf := bytes.NewBuffer(requestBody)
// fmt.Println(buf)
str := buf.String()
parts := strings.Split(str, "sessionId")
if len(parts) > 1 {
json.Unmarshal(requestBody, &body)
}
return body
}
func lookupInvoke(w http.ResponseWriter, r *http.Request, metrics metrics.MetricOptions, name string, c *client.Client, logger *logrus.Logger) {
@ -112,9 +79,14 @@ func invokeService(w http.ResponseWriter, r *http.Request, metrics metrics.Metri
start := time.Now()
buf := bytes.NewBuffer(requestBody)
url := "http://" + service + ":" + strconv.Itoa(8080) + "/"
fmt.Printf("[%s] Forwarding request to: %s\n", stamp, url)
contentType := r.Header.Get("Content-Type")
if len(contentType) == 0 {
contentType = "text/plain"
}
response, err := http.Post(url, "text/plain", buf)
fmt.Printf("[%s] Forwarding request [%s] to: %s\n", stamp, contentType, url)
response, err := http.Post(url, r.Header.Get("Content-Type"), buf)
if err != nil {
logger.Infoln(err)
w.WriteHeader(500)
@ -132,6 +104,9 @@ func invokeService(w http.ResponseWriter, r *http.Request, metrics metrics.Metri
return
}
// Match header for strict services
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
w.WriteHeader(http.StatusOK)
w.Write(responseBody)

View File

@ -33,7 +33,11 @@ func main() {
metrics.RegisterMetrics(metricsOptions)
r := mux.NewRouter()
r.HandleFunc("/function/{name:[a-zA-Z_]+}", faashandlers.MakeProxy(metricsOptions, true, dockerClient, &logger))
// r.StrictSlash(false)
functionHandler := faashandlers.MakeProxy(metricsOptions, true, dockerClient, &logger)
r.HandleFunc("/function/{name:[a-zA-Z_]+}", functionHandler)
r.HandleFunc("/function/{name:[a-zA-Z_]+}/", functionHandler)
r.HandleFunc("/system/alert", faashandlers.MakeAlertHandler(dockerClient))
r.HandleFunc("/system/functions", faashandlers.MakeFunctionReader(metricsOptions, dockerClient)).Methods("GET")

View File

@ -1,7 +1,8 @@
FROM alpine:latest
RUN apk --update add nodejs
ADD https://github.com/alexellis/faas/releases/download/v0.3-alpha/fwatchdog /usr/bin
#ADD https://github.com/alexellis/faas/releases/download/v0.3-alpha/fwatchdog /usr/bin
COPY ./fwatchdog /usr/bin/
RUN chmod +x /usr/bin/fwatchdog
COPY package.json .

View File

@ -0,0 +1,29 @@
{
"session": {
"sessionId": "SessionId.3f589830-c369-45a3-9c8d-7f5271777dd8",
"application": {
"applicationId": "amzn1.ask.skill.b32fb0db-f0f0-4e64-b862-48e506f4ea68"
},
"attributes": {},
"user": {
"userId": "amzn1.ask.account.AEUHSFGVXWOYRSM2A7SVAK47L3I44TVOG6DBCTY2ACYSCUYQ65MWDZLUBZHLDD3XEMCYRLS4VSA54PQ7QBQW6FZLRJSMP5BOZE2B52YURUOSNOWORL44QGYDRXR3H7A7Y33OP3XKMUSJXIAFH7T2ZA6EQBLYRD34BPLTJXE3PDZE3V4YNFYUECXQNNH4TRG3ZBOYH2BF4BTKIIQ"
},
"new": true
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.9ddf1ea0-c582-4dd0-8547-359f71639c1d",
"locale": "en-GB",
"timestamp": "2017-01-28T11:02:59Z",
"intent": {
"name": "ChangeColorIntent",
"slots": {
"LedColor": {
"name": "LedColor",
"value": "blue"
}
}
}
},
"version": "1.0"
}

View File

@ -0,0 +1,4 @@
#!/bin/bash
docker build -t alexellis2/faas-alexachangecolorintent .

View File

@ -0,0 +1,29 @@
{
"session": {
"sessionId": "SessionId.ce487e6e-9975-4c95-b305-2a0b354f3ee0",
"application": {
"applicationId": "amzn1.ask.skill.dc0c07b4-e18d-4f6f-a571-90cd1aca3bc6"
},
"attributes": {},
"user": {
"userId": "amzn1.ask.account.AEFGBTDIPL5K3HYKXGNAXDHANW2MPMFRRM5QX7FCMUEOJYCGNIVUTVR7IUUHZ2VFPIDNOPIUBWZLGYSSLOBLZ6FR5FRUJMP3OAZKUI3ZZ4ADLR7M4ROICY5H5RFASQLTV5IUNIOTA7OP6N2ZNCXXZDXS7BVGPB6GKIWZAJRHOGUYSBHX2JMSLNPQ6V6HMFKGKZLAWLHKGYEUDBI"
},
"new": true
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.ee57cb67-a465-4d93-9ea8-29229f2634bc",
"locale": "en-GB",
"timestamp": "2017-01-28T11:32:04Z",
"intent": {
"name": "ChangeColorIntent",
"slots": {
"LedColor": {
"name": "LedColor",
"value": "green"
}
}
}
},
"version": "1.0"
}

View File

@ -2,7 +2,7 @@
let fs = require('fs');
let sample = require("./sample.json");
let SendColor = require('./sendColor');
let sendColor = new SendColor("alexellis.io/tree1")
let sendColor = new SendColor("alexellis.io/officelights")
const getStdin = require('get-stdin');
@ -14,7 +14,7 @@ getStdin().then(content => {
function tellWithCard(speechOutput) {
sample.response.outputSpeech.text = speechOutput
sample.response.card.content = speechOutput
sample.response.card.title = "Christmas Lights";
sample.response.card.title = "Office Lights";
console.log(JSON.stringify(sample));
process.exit(0);
}

View File

@ -0,0 +1,29 @@
{
"session": {
"sessionId": "SessionId.3f589830-c369-45a3-9c8d-7f5271777dd8",
"application": {
"applicationId": "amzn1.ask.skill.b32fb0db-f0f0-4e64-b862-48e506f4ea68"
},
"attributes": {},
"user": {
"userId": "amzn1.ask.account.AEUHSFGVXWOYRSM2A7SVAK47L3I44TVOG6DBCTY2ACYSCUYQ65MWDZLUBZHLDD3XEMCYRLS4VSA54PQ7QBQW6FZLRJSMP5BOZE2B52YURUOSNOWORL44QGYDRXR3H7A7Y33OP3XKMUSJXIAFH7T2ZA6EQBLYRD34BPLTJXE3PDZE3V4YNFYUECXQNNH4TRG3ZBOYH2BF4BTKIIQ"
},
"new": true
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.9ddf1ea0-c582-4dd0-8547-359f71639c1d",
"locale": "en-GB",
"timestamp": "2017-01-28T11:02:59Z",
"intent": {
"name": "ChangeColorIntent",
"slots": {
"LedColor": {
"name": "LedColor",
"value": "red"
}
}
}
},
"version": "1.0"
}

View File

@ -1,16 +0,0 @@
{
"version": "1.0",
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "There's currently 6 people in space"
},
"card": {
"content": "There's currently 6 people in space",
"title": "People in space",
"type": "Simple"
},
"shouldEndSession": true
},
"sessionAttributes": {}
}

View File

@ -0,0 +1,29 @@
{
"session": {
"sessionId": "SessionId.3f589830-c369-45a3-9c8d-7f5271777dd8",
"application": {
"applicationId": "amzn1.ask.skill.b32fb0db-f0f0-4e64-b862-48e506f4ea68"
},
"attributes": {},
"user": {
"userId": "amzn1.ask.account.AEUHSFGVXWOYRSM2A7SVAK47L3I44TVOG6DBCTY2ACYSCUYQ65MWDZLUBZHLDD3XEMCYRLS4VSA54PQ7QBQW6FZLRJSMP5BOZE2B52YURUOSNOWORL44QGYDRXR3H7A7Y33OP3XKMUSJXIAFH7T2ZA6EQBLYRD34BPLTJXE3PDZE3V4YNFYUECXQNNH4TRG3ZBOYH2BF4BTKIIQ"
},
"new": true
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.9ddf1ea0-c582-4dd0-8547-359f71639c1d",
"locale": "en-GB",
"timestamp": "2017-01-28T11:02:59Z",
"intent": {
"name": "ChangeColorIntent",
"slots": {
"LedColor": {
"name": "LedColor",
"value": "blue"
}
}
}
},
"version": "1.0"
}

View File

@ -50,6 +50,10 @@ func makeRequestHandler(config *WatchdogConfig) func(http.ResponseWriter, *http.
os.Stdout.Write(out)
}
// Match header for strict services
if r.Header.Get("Content-Type") == "application/json" {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(200)
w.Write(out)
} else {