From ab875cc4a343dd8104a96e6cb9e5a57f39098208 Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Wed, 6 Mar 2019 10:57:58 -0800 Subject: [PATCH 01/11] initial commit --- action.go | 1 + api/api.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/action.go b/action.go index 3c36f2e..d4cc0e4 100644 --- a/action.go +++ b/action.go @@ -125,6 +125,7 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { if uri := act.settings.URI; uri != "" { if resData := api.GetResource(uri); resData != nil { actionData = resData + fmt.Println("actionData:",actionData) } else { // Load action data from resources resData := f.Manager.GetResource(uri) diff --git a/api/api.go b/api/api.go index 1b92e33..03f31e6 100644 --- a/api/api.go +++ b/api/api.go @@ -5,6 +5,8 @@ import ( "fmt" "reflect" "sync" + "net/url" + "net/http" "github.com/project-flogo/core/activity" "github.com/project-flogo/core/api" @@ -21,6 +23,35 @@ func GetResource(name string) *Microgateway { resourcesMutex.RLock() defer resourcesMutex.RUnlock() return resources[name] + +} + +func GetResourceFile(URL string){ + url, err := url.Parse(URL) + if err != nil { + panic(err) + } + if url.Scheme == "http"{ + res, err := http.Get(URL) + if err != nil { + log.Fatal(err) + } + response, err := ioutil.ReadAll(res.Body) + response.Body.Close() + if err != nil { + log.Fatal(err) + } + fmt.Printf("%s", response) + + } + if url.Scheme == "file"{ + data, err := ioutil.ReadFile(name[7:]) + if err != nil { + fmt.Println("File reading error", err) + return + } + fmt.Println("Contents of file:", string(data)) + } } // ClearResources clears the resources for testing From 1db78441472c991908fc1b198c368431e46f0557 Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Wed, 6 Mar 2019 11:07:07 -0800 Subject: [PATCH 02/11] fix --- api/api.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/api/api.go b/api/api.go index 03f31e6..0d3bd2a 100644 --- a/api/api.go +++ b/api/api.go @@ -7,6 +7,7 @@ import ( "sync" "net/url" "net/http" + "io/ioutil" "github.com/project-flogo/core/activity" "github.com/project-flogo/core/api" @@ -34,18 +35,18 @@ func GetResourceFile(URL string){ if url.Scheme == "http"{ res, err := http.Get(URL) if err != nil { - log.Fatal(err) + fmt.Println(err) } response, err := ioutil.ReadAll(res.Body) response.Body.Close() if err != nil { - log.Fatal(err) + fmt.Println(err) } fmt.Printf("%s", response) } if url.Scheme == "file"{ - data, err := ioutil.ReadFile(name[7:]) + data, err := ioutil.ReadFile(URL[7:]) if err != nil { fmt.Println("File reading error", err) return From 02220e261f9f65cf9c07bddc200c30cc2a2b1e37 Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Wed, 6 Mar 2019 14:16:30 -0800 Subject: [PATCH 03/11] 1. Added http and file support 2. Added json file example --- action.go | 36 ++++++++++++++-- api/api.go | 28 ------------ examples/json/resource-handler/flogo.json | 43 +++++++++++++++++++ .../resource-handler/resources/resource.json | 38 ++++++++++++++++ 4 files changed, 114 insertions(+), 31 deletions(-) create mode 100644 examples/json/resource-handler/flogo.json create mode 100644 examples/json/resource-handler/resources/resource.json diff --git a/action.go b/action.go index d4cc0e4..298e775 100644 --- a/action.go +++ b/action.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "strings" + "net/url" _ "github.com/project-flogo/contrib/function" "github.com/project-flogo/core/action" @@ -58,7 +59,6 @@ func (m *Manager) LoadResource(config *resource.Config) (*resource.Resource, err if err != nil { return nil, fmt.Errorf("error marshalling microgateway definition resource with id '%s', %s", config.ID, err.Error()) } - return resource.New("microgateway", definition), nil } @@ -123,10 +123,40 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { var actionData *api.Microgateway if uri := act.settings.URI; uri != "" { + url, err := url.Parse(uri) + if err != nil { + panic(err) + } if resData := api.GetResource(uri); resData != nil { actionData = resData - fmt.Println("actionData:",actionData) - } else { + }else if url.Scheme == "http://"{ + //get resource from http + res, err := http.Get(url) + if err != nil { + return nil, fmt.Errorf("Error in accessing specified HTTP url") + } + resData, err := ioutil.ReadAll(res.Body) + res.Body.Close() + if err != nil { + return nil, fmt.Errorf("Error receving HTTP resource data") + } + err = json.Unmarshal(resData, &actionData) + if err != nil { + return nil, fmt.Errorf("error marshalling microgateway definition resource with id '%s', %s", config.ID, err.Error()) + } + }else if url.Scheme == "file:///"{ + //get resource from local file system + resData, err := ioutil.ReadFile(uri[7:]) + if err != nil { + fmt.Println("File reading error", err) + return + } + fmt.Println("Contents of file:", string(resData)) + err = json.Unmarshal(resData, &actionData) + if err != nil { + return nil, fmt.Errorf("error marshalling microgateway definition resource with id '%s', %s", config.ID, err.Error()) + } + }else { // Load action data from resources resData := f.Manager.GetResource(uri) if resData == nil { diff --git a/api/api.go b/api/api.go index 0d3bd2a..d3887b7 100644 --- a/api/api.go +++ b/api/api.go @@ -27,34 +27,6 @@ func GetResource(name string) *Microgateway { } -func GetResourceFile(URL string){ - url, err := url.Parse(URL) - if err != nil { - panic(err) - } - if url.Scheme == "http"{ - res, err := http.Get(URL) - if err != nil { - fmt.Println(err) - } - response, err := ioutil.ReadAll(res.Body) - response.Body.Close() - if err != nil { - fmt.Println(err) - } - fmt.Printf("%s", response) - - } - if url.Scheme == "file"{ - data, err := ioutil.ReadFile(URL[7:]) - if err != nil { - fmt.Println("File reading error", err) - return - } - fmt.Println("Contents of file:", string(data)) - } -} - // ClearResources clears the resources for testing func ClearResources() { resources = make(map[string]*Microgateway) diff --git a/examples/json/resource-handler/flogo.json b/examples/json/resource-handler/flogo.json new file mode 100644 index 0000000..343f11e --- /dev/null +++ b/examples/json/resource-handler/flogo.json @@ -0,0 +1,43 @@ +{ + "name": "MyProxy", + "type": "flogo:app", + "version": "1.0.0", + "description": "This is a simple proxy.", + "properties": null, + "channels": null, + "triggers": [ + { + "name": "flogo-rest", + "id": "MyProxy", + "ref": "github.com/project-flogo/contrib/trigger/rest", + "settings": { + "port": "9096" + }, + "handlers": [ + { + "settings": { + "method": "GET", + "path": "/pets/:petId" + }, + "actions": [ + { + "id": "microgateway:Pets" + } + ] + } + ] + } + ], + "resources": [ + ], + "actions": [ + { + "ref": "github.com/project-flogo/microgateway", + "settings": { + "uri": "file:///examples/json/resource-handler/resources/resource.json" + }, + "id": "microgateway:Pets", + "metadata": null + } + ] +} diff --git a/examples/json/resource-handler/resources/resource.json b/examples/json/resource-handler/resources/resource.json new file mode 100644 index 0000000..864fdfa --- /dev/null +++ b/examples/json/resource-handler/resources/resource.json @@ -0,0 +1,38 @@ +{ + "id": "microgateway:Pets", + "compressed": false, + "data": { + "name": "Pets", + "steps": [ + { + "service": "PetStorePets", + "input": { + "pathParams": "=$.payload.pathParams" + } + } + ], + "responses": [ + { + "error": false, + "output": { + "code": 200, + "data": "=$.PetStorePets.outputs.data" + } + } + ], + "services": [ + { + "name": "PetStorePets", + "description": "Get pets by ID from the petstore", + "ref": "github.com/project-flogo/contrib/activity/rest", + "settings": { + "uri": "http://petstore.swagger.io/v2/pet/:petId", + "method": "GET", + "headers": { + "Accept": "application/json" + } + } + } + ] + } +} \ No newline at end of file From df9b0d89c5595df6c57748f2e517701230f62a12 Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Wed, 6 Mar 2019 15:42:33 -0800 Subject: [PATCH 04/11] Fix - getting resource from file system(working) --- action.go | 33 ++++++---- examples/json/resource-handler/flogo.json | 2 - .../resource-handler/resources/resource.json | 60 ++++++++----------- 3 files changed, 47 insertions(+), 48 deletions(-) diff --git a/action.go b/action.go index 298e775..86a69ba 100644 --- a/action.go +++ b/action.go @@ -8,6 +8,8 @@ import ( "os" "strings" "net/url" + "net/http" + "io/ioutil" _ "github.com/project-flogo/contrib/function" "github.com/project-flogo/core/action" @@ -129,9 +131,9 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { } if resData := api.GetResource(uri); resData != nil { actionData = resData - }else if url.Scheme == "http://"{ + }else if url.Scheme == "http"{ //get resource from http - res, err := http.Get(url) + res, err := http.Get(uri) if err != nil { return nil, fmt.Errorf("Error in accessing specified HTTP url") } @@ -140,22 +142,31 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { if err != nil { return nil, fmt.Errorf("Error receving HTTP resource data") } - err = json.Unmarshal(resData, &actionData) + var definition *api.Microgateway + err = json.Unmarshal(resData, &definition) if err != nil { - return nil, fmt.Errorf("error marshalling microgateway definition resource with id '%s', %s", config.ID, err.Error()) + return nil, fmt.Errorf("error marshalling microgateway definition resource") } - }else if url.Scheme == "file:///"{ + actionData = definition + }else if url.Scheme == "file"{ //get resource from local file system - resData, err := ioutil.ReadFile(uri[7:]) + resData, err := ioutil.ReadFile("/Users/agadikar/microgateway/examples/json/resource-handler/resources/resource.json") if err != nil { - fmt.Println("File reading error", err) - return + return nil, fmt.Errorf("File reading error") } - fmt.Println("Contents of file:", string(resData)) - err = json.Unmarshal(resData, &actionData) + //fmt.Println("Contents of file:", string(resData)) + + err = schema.Validate(resData) + if err != nil { + return nil, fmt.Errorf("error validating schema: %s", err.Error()) + } + var definition *api.Microgateway + err = json.Unmarshal(resData, &definition) if err != nil { - return nil, fmt.Errorf("error marshalling microgateway definition resource with id '%s', %s", config.ID, err.Error()) + return nil, fmt.Errorf("error marshalling microgateway definition resource") } + actionData = definition + fmt.Println("%v\n", actionData) }else { // Load action data from resources resData := f.Manager.GetResource(uri) diff --git a/examples/json/resource-handler/flogo.json b/examples/json/resource-handler/flogo.json index 343f11e..ea81d53 100644 --- a/examples/json/resource-handler/flogo.json +++ b/examples/json/resource-handler/flogo.json @@ -28,8 +28,6 @@ ] } ], - "resources": [ - ], "actions": [ { "ref": "github.com/project-flogo/microgateway", diff --git a/examples/json/resource-handler/resources/resource.json b/examples/json/resource-handler/resources/resource.json index 864fdfa..f343a9e 100644 --- a/examples/json/resource-handler/resources/resource.json +++ b/examples/json/resource-handler/resources/resource.json @@ -1,38 +1,28 @@ { - "id": "microgateway:Pets", - "compressed": false, - "data": { - "name": "Pets", - "steps": [ - { - "service": "PetStorePets", - "input": { - "pathParams": "=$.payload.pathParams" - } + "name": "Pets", + "steps": [{ + "service": "PetStorePets", + "input": { + "pathParams": "=$.payload.pathParams" + } + }], + "responses": [{ + "error": false, + "output": { + "code": 200, + "data": "=$.PetStorePets.outputs.data" + } + }], + "services": [{ + "name": "PetStorePets", + "description": "Get pets by ID from the petstore", + "ref": "github.com/project-flogo/contrib/activity/rest", + "settings": { + "uri": "http://petstore.swagger.io/v2/pet/:petId", + "method": "GET", + "headers": { + "Accept": "application/json" } - ], - "responses": [ - { - "error": false, - "output": { - "code": 200, - "data": "=$.PetStorePets.outputs.data" - } - } - ], - "services": [ - { - "name": "PetStorePets", - "description": "Get pets by ID from the petstore", - "ref": "github.com/project-flogo/contrib/activity/rest", - "settings": { - "uri": "http://petstore.swagger.io/v2/pet/:petId", - "method": "GET", - "headers": { - "Accept": "application/json" - } - } - } - ] - } + } + }] } \ No newline at end of file From 4bc7606692501b88833e8f47f69a533b8c642808 Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Wed, 6 Mar 2019 15:48:18 -0800 Subject: [PATCH 05/11] fix --- api/api.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/api/api.go b/api/api.go index d3887b7..427aabd 100644 --- a/api/api.go +++ b/api/api.go @@ -5,9 +5,6 @@ import ( "fmt" "reflect" "sync" - "net/url" - "net/http" - "io/ioutil" "github.com/project-flogo/core/activity" "github.com/project-flogo/core/api" From 8a14a95db19e5e372b65865e9476de0558a49a5a Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Wed, 6 Mar 2019 16:29:57 -0800 Subject: [PATCH 06/11] Added http resource example and server handler --- action.go | 8 +-- .../{ => fileResource}/flogo.json | 0 .../{resources => fileResource}/resource.json | 0 .../resource-handler/httpResource/flogo.json | 41 +++++++++++ .../resource-handler/httpResource/main.go | 69 +++++++++++++++++++ 5 files changed, 113 insertions(+), 5 deletions(-) rename examples/json/resource-handler/{ => fileResource}/flogo.json (100%) rename examples/json/resource-handler/{resources => fileResource}/resource.json (100%) create mode 100644 examples/json/resource-handler/httpResource/flogo.json create mode 100644 examples/json/resource-handler/httpResource/main.go diff --git a/action.go b/action.go index 86a69ba..9ee3676 100644 --- a/action.go +++ b/action.go @@ -142,19 +142,18 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { if err != nil { return nil, fmt.Errorf("Error receving HTTP resource data") } - var definition *api.Microgateway - err = json.Unmarshal(resData, &definition) + //var definition *api.Microgateway + err = json.Unmarshal(resData, &actionData) if err != nil { return nil, fmt.Errorf("error marshalling microgateway definition resource") } - actionData = definition + //actionData = definition }else if url.Scheme == "file"{ //get resource from local file system resData, err := ioutil.ReadFile("/Users/agadikar/microgateway/examples/json/resource-handler/resources/resource.json") if err != nil { return nil, fmt.Errorf("File reading error") } - //fmt.Println("Contents of file:", string(resData)) err = schema.Validate(resData) if err != nil { @@ -166,7 +165,6 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { return nil, fmt.Errorf("error marshalling microgateway definition resource") } actionData = definition - fmt.Println("%v\n", actionData) }else { // Load action data from resources resData := f.Manager.GetResource(uri) diff --git a/examples/json/resource-handler/flogo.json b/examples/json/resource-handler/fileResource/flogo.json similarity index 100% rename from examples/json/resource-handler/flogo.json rename to examples/json/resource-handler/fileResource/flogo.json diff --git a/examples/json/resource-handler/resources/resource.json b/examples/json/resource-handler/fileResource/resource.json similarity index 100% rename from examples/json/resource-handler/resources/resource.json rename to examples/json/resource-handler/fileResource/resource.json diff --git a/examples/json/resource-handler/httpResource/flogo.json b/examples/json/resource-handler/httpResource/flogo.json new file mode 100644 index 0000000..15aa27e --- /dev/null +++ b/examples/json/resource-handler/httpResource/flogo.json @@ -0,0 +1,41 @@ +{ + "name": "MyProxy", + "type": "flogo:app", + "version": "1.0.0", + "description": "This is a simple proxy.", + "properties": null, + "channels": null, + "triggers": [ + { + "name": "flogo-rest", + "id": "MyProxy", + "ref": "github.com/project-flogo/contrib/trigger/rest", + "settings": { + "port": "9096" + }, + "handlers": [ + { + "settings": { + "method": "GET", + "path": "/pets/:petId" + }, + "actions": [ + { + "id": "microgateway:Pets" + } + ] + } + ] + } + ], + "actions": [ + { + "ref": "github.com/project-flogo/microgateway", + "settings": { + "uri": "http://localhost:1234/pets" + }, + "id": "microgateway:Pets", + "metadata": null + } + ] +} diff --git a/examples/json/resource-handler/httpResource/main.go b/examples/json/resource-handler/httpResource/main.go new file mode 100644 index 0000000..03fefe4 --- /dev/null +++ b/examples/json/resource-handler/httpResource/main.go @@ -0,0 +1,69 @@ +package main + +import ( + "flag" + "fmt" + "html" + "io/ioutil" + "net/http" +) + +var ( + server = flag.Bool("server", false, "run the test server") +) + +const resource = `{ + "name": "Pets", + "steps": [{ + "service": "PetStorePets", + "input": { + "pathParams": "=$.payload.pathParams" + } + }], + "responses": [{ + "error": false, + "output": { + "code": 200, + "data": "=$.PetStorePets.outputs.data" + } + }], + "services": [{ + "name": "PetStorePets", + "description": "Get pets by ID from the petstore", + "ref": "github.com/project-flogo/contrib/activity/rest", + "settings": { + "uri": "http://petstore.swagger.io/v2/pet/:petId", + "method": "GET", + "headers": { + "Accept": "application/json" + } + } + }] +}` + +func main() { + flag.Parse() + + if *server { + http.HandleFunc("/pets", func(w http.ResponseWriter, r *http.Request) { + fmt.Printf("url: %q\n", html.EscapeString(r.URL.Path)) + defer r.Body.Close() + _, err := ioutil.ReadAll(r.Body) + if err != nil { + panic(err) + } + w.Header().Set("Content-Type", "application/json") + _, err = w.Write([]byte(resource)) + if err != nil { + panic(err) + } + }) + + err := http.ListenAndServe(":1234", nil) + if err != nil { + panic(err) + } + + return + } +} \ No newline at end of file From a9c5be62fd2381844636c75cdc3356a3b0368864 Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Thu, 7 Mar 2019 10:17:41 -0800 Subject: [PATCH 07/11] Added Readme and code clean --- action.go | 20 ++++----- .../resource-handler/fileResource/README.md | 37 +++++++++++++++++ .../resource-handler/fileResource/flogo.json | 2 +- .../resource-handler/httpResource/README.md | 41 +++++++++++++++++++ .../resource-handler/httpResource/main.go | 2 +- 5 files changed, 88 insertions(+), 14 deletions(-) create mode 100644 examples/json/resource-handler/fileResource/README.md create mode 100644 examples/json/resource-handler/httpResource/README.md diff --git a/action.go b/action.go index 9ee3676..8a40dbd 100644 --- a/action.go +++ b/action.go @@ -5,11 +5,11 @@ import ( "encoding/json" "errors" "fmt" + "io/ioutil" + "net/http" + "net/url" "os" "strings" - "net/url" - "net/http" - "io/ioutil" _ "github.com/project-flogo/contrib/function" "github.com/project-flogo/core/action" @@ -131,7 +131,7 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { } if resData := api.GetResource(uri); resData != nil { actionData = resData - }else if url.Scheme == "http"{ + } else if url.Scheme == "http" { //get resource from http res, err := http.Get(uri) if err != nil { @@ -142,15 +142,13 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { if err != nil { return nil, fmt.Errorf("Error receving HTTP resource data") } - //var definition *api.Microgateway err = json.Unmarshal(resData, &actionData) if err != nil { return nil, fmt.Errorf("error marshalling microgateway definition resource") } - //actionData = definition - }else if url.Scheme == "file"{ + } else if url.Scheme == "file" { //get resource from local file system - resData, err := ioutil.ReadFile("/Users/agadikar/microgateway/examples/json/resource-handler/resources/resource.json") + resData, err := ioutil.ReadFile(uri[7:]) if err != nil { return nil, fmt.Errorf("File reading error") } @@ -159,13 +157,11 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { if err != nil { return nil, fmt.Errorf("error validating schema: %s", err.Error()) } - var definition *api.Microgateway - err = json.Unmarshal(resData, &definition) + err = json.Unmarshal(resData, &actionData) if err != nil { return nil, fmt.Errorf("error marshalling microgateway definition resource") } - actionData = definition - }else { + } else { // Load action data from resources resData := f.Manager.GetResource(uri) if resData == nil { diff --git a/examples/json/resource-handler/fileResource/README.md b/examples/json/resource-handler/fileResource/README.md new file mode 100644 index 0000000..f4ddcea --- /dev/null +++ b/examples/json/resource-handler/fileResource/README.md @@ -0,0 +1,37 @@ +# Gateway using File Resource +This recipe is a gateway using the file resource. + +## Installation +* Install [Go](https://golang.org/) +* Install the flogo [cli](https://github.com/project-flogo/cli) + +## Setup +```bash +git clone https://github.com/project-flogo/microgateway +cd microgateway/examples/json/resource-handler/fileResource +``` + +## Testing +Create the gateway: +``` +flogo create -f flogo.json +cd MyProxy +flogo install github.com/project-flogo/contrib/activity/rest +flogo build +``` + +Start the gateway: +``` +bin/MyProxy +``` +and test below scenario. + + +### Request is successful +```bash +curl http://localhost:9096/pets/1 +``` + +You should then see something like: +```json +{"category":{"id":0,"name":"string"},"id":1,"name":"aspen","photoUrls":["string"],"status":"done","tags":[{"id":0,"name":"string"}]} \ No newline at end of file diff --git a/examples/json/resource-handler/fileResource/flogo.json b/examples/json/resource-handler/fileResource/flogo.json index ea81d53..a9a355a 100644 --- a/examples/json/resource-handler/fileResource/flogo.json +++ b/examples/json/resource-handler/fileResource/flogo.json @@ -32,7 +32,7 @@ { "ref": "github.com/project-flogo/microgateway", "settings": { - "uri": "file:///examples/json/resource-handler/resources/resource.json" + "uri": "file:///Users/agadikar/microgateway/examples/json/resource-handler/resources/resource.json" }, "id": "microgateway:Pets", "metadata": null diff --git a/examples/json/resource-handler/httpResource/README.md b/examples/json/resource-handler/httpResource/README.md new file mode 100644 index 0000000..32b806b --- /dev/null +++ b/examples/json/resource-handler/httpResource/README.md @@ -0,0 +1,41 @@ +# Gateway using HTTP Resource +This recipe is a gateway using the HTTP resource. The resource is downloaded from the requested HTTP server + +## Installation +* Install [Go](https://golang.org/) +* Install the flogo [cli](https://github.com/project-flogo/cli) + +## Setup +```bash +git clone https://github.com/project-flogo/microgateway +cd microgateway/examples/json/resource-handler/httpResource +``` + +## Testing +Create the gateway: +``` +flogo create -f flogo.json +cd MyProxy +flogo install github.com/project-flogo/contrib/activity/rest +flogo build +``` + +Start the gateway: +``` +bin/MyProxy +``` +and test below scenario. + +In another terminal start the server: +```bash +go run main.go -server +``` + +### Request is successful +```bash +curl http://localhost:9096/pets/1 +``` + +You should then see something like: +```json +{"category":{"id":0,"name":"string"},"id":1,"name":"aspen","photoUrls":["string"],"status":"done","tags":[{"id":0,"name":"string"}]} \ No newline at end of file diff --git a/examples/json/resource-handler/httpResource/main.go b/examples/json/resource-handler/httpResource/main.go index 03fefe4..8e58379 100644 --- a/examples/json/resource-handler/httpResource/main.go +++ b/examples/json/resource-handler/httpResource/main.go @@ -66,4 +66,4 @@ func main() { return } -} \ No newline at end of file +} From 0d8282647175f868801175f229f1177327b5a541 Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Thu, 7 Mar 2019 10:29:11 -0800 Subject: [PATCH 08/11] fix --- examples/json/resource-handler/fileResource/flogo.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/json/resource-handler/fileResource/flogo.json b/examples/json/resource-handler/fileResource/flogo.json index a9a355a..c8b24ee 100644 --- a/examples/json/resource-handler/fileResource/flogo.json +++ b/examples/json/resource-handler/fileResource/flogo.json @@ -32,7 +32,7 @@ { "ref": "github.com/project-flogo/microgateway", "settings": { - "uri": "file:///Users/agadikar/microgateway/examples/json/resource-handler/resources/resource.json" + "uri": "file:///Users/agadikar/microgateway/examples/json/resource-handler/fileResource/resource.json" }, "id": "microgateway:Pets", "metadata": null From d5a15a1dd897e16ba9610395577ebfd9361a15a5 Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Thu, 7 Mar 2019 15:49:41 -0800 Subject: [PATCH 09/11] Added testcases for json file --- action.go | 17 +- examples/examples_test.go | 190 +++++++++++++++++- .../resource-handler/httpResource/main.go | 14 +- 3 files changed, 213 insertions(+), 8 deletions(-) diff --git a/action.go b/action.go index 8a40dbd..c5cde77 100644 --- a/action.go +++ b/action.go @@ -46,6 +46,7 @@ func init() { } var actionMetadata = action.ToMetadata(&Settings{}, &Input{}, &Output{}) +var resourceMap = make(map[string]interface{}) // LoadResource loads the microgateway definition func (m *Manager) LoadResource(config *resource.Config) (*resource.Resource, error) { @@ -131,7 +132,9 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { } if resData := api.GetResource(uri); resData != nil { actionData = resData - } else if url.Scheme == "http" { + } else if resData := resourceMap[uri]; resData != nil{ + actionData = resData.(*api.Microgateway) + }else if url.Scheme == "http" { //get resource from http res, err := http.Get(uri) if err != nil { @@ -142,10 +145,13 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { if err != nil { return nil, fmt.Errorf("Error receving HTTP resource data") } - err = json.Unmarshal(resData, &actionData) + var definition *api.Microgateway + err = json.Unmarshal(resData, &definition) if err != nil { return nil, fmt.Errorf("error marshalling microgateway definition resource") } + resourceMap[uri] = definition + actionData = definition } else if url.Scheme == "file" { //get resource from local file system resData, err := ioutil.ReadFile(uri[7:]) @@ -157,10 +163,13 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { if err != nil { return nil, fmt.Errorf("error validating schema: %s", err.Error()) } - err = json.Unmarshal(resData, &actionData) + var definition *api.Microgateway + err = json.Unmarshal(resData, &definition) if err != nil { return nil, fmt.Errorf("error marshalling microgateway definition resource") } + resourceMap[uri] = definition + actionData = definition } else { // Load action data from resources resData := f.Manager.GetResource(uri) @@ -169,7 +178,7 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { } actionData = resData.Object().(*api.Microgateway) } - } else if p := act.settings.Pattern; p != "" { + }else if p := act.settings.Pattern; p != "" { definition, err := Load(p) if err != nil { return nil, err diff --git a/examples/examples_test.go b/examples/examples_test.go index cc39856..b3099a2 100644 --- a/examples/examples_test.go +++ b/examples/examples_test.go @@ -2,8 +2,8 @@ package examples import ( "context" - "encoding/json" - "fmt" + //"encoding/json" + //"fmt" "io/ioutil" "net/http" "path/filepath" @@ -30,6 +30,10 @@ type handler struct { Slow bool } +type resourceHandler struct{ + Slow bool +} + func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() _, err := ioutil.ReadAll(r.Body) @@ -48,6 +52,24 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } +func (h *resourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + defer r.Body.Close() + _, err := ioutil.ReadAll(r.Body) + if err != nil { + panic(err) + } + + if h.Slow { + time.Sleep(10 * time.Second) + } + + w.Header().Set("Content-Type", "application/json") + _, err = w.Write([]byte(resource)) + if err != nil { + panic(err) + } +} + const reply = `{ "id": 1, "category": { @@ -60,6 +82,36 @@ const reply = `{ "status":"available" }` +const resource = `{ + "name": "Pets", + "steps": [{ + "service": "PetStorePets", + "input": { + "pathParams": "=$.payload.pathParams" + } + }], + "responses": [{ + "error": false, + "output": { + "code": 200, + "data": "=$.PetStorePets.outputs.data" + } + }], + "services": [{ + "name": "PetStorePets", + "description": "Get pets by ID from the petstore", + "ref": "github.com/project-flogo/contrib/activity/rest", + "settings": { + "uri": "http://petstore.swagger.io/v2/pet/:petId", + "method": "GET", + "headers": { + "Accept": "application/json" + } + } + }] +}` + +/* func testBasicGatewayApplication(t *testing.T, e engine.Engine) { defer api.ClearResources() test.Drain("9096") @@ -346,7 +398,6 @@ func testAsyncGatewayExample(t *testing.T, e engine.Engine) { } body := request() - fmt.Println("body is:", body) assert.NotEqual(t, 0, len(body)) } @@ -372,3 +423,136 @@ func TestAsyncGatewayExampleJSON(t *testing.T) { assert.Nil(t, err) testAsyncGatewayExample(t, e) } + +func testResourceHandlerExampleFile(t *testing.T, e engine.Engine) { + defer api.ClearResources() + + test.Drain("9096") + err := e.Start() + assert.Nil(t, err) + defer func() { + err := e.Stop() + assert.Nil(t, err) + }() + test.Pour("9096") + + transport := &http.Transport{ + MaxIdleConns: 1, + } + defer transport.CloseIdleConnections() + client := &http.Client{ + Transport: transport, + } + request := func() string { + req, err := http.NewRequest(http.MethodGet, "http://localhost:9096/pets/4", nil) + assert.Nil(t, err) + response, err := client.Do(req) + assert.Nil(t, err) + body, err := ioutil.ReadAll(response.Body) + assert.Nil(t, err) + response.Body.Close() + return string(body) + } + + body := request() + assert.NotEqual(t, 0, len(body)) +} + +/* +func TestResourceHandlerExampleAPI_File(t *testing.T) { + if testing.Short() { + t.Skip("skipping Basic Gateway API integration test in short mode") + } + + e, err := AsyncGatewayExample() + assert.Nil(t, err) + testAsyncGatewayExample(t, e) +}*/ +/* +func TestResourceHandlerExampleJSON_File(t *testing.T) { + if testing.Short() { + t.Skip("skipping Basic Gateway JSON integration test in short mode") + } + data, err := ioutil.ReadFile(filepath.FromSlash("./json/resource-handler/fileResource/flogo.json")) + assert.Nil(t, err) + cfg, err := engine.LoadAppConfig(string(data), false) + assert.Nil(t, err) + e, err := engine.New(cfg) + assert.Nil(t, err) + testResourceHandlerExampleFile(t, e) +} +*/ + + +func testResourceHandlerExampleHTTP(t *testing.T, e engine.Engine) { + defer api.ClearResources() + + test.Drain("1234") + testHandler := resourceHandler{} + s := &http.Server{ + Addr: ":1234", + Handler: &testHandler, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + MaxHeaderBytes: 1 << 20, + } + go func() { + s.ListenAndServe() + }() + test.Pour("1234") + defer s.Shutdown(context.Background()) + + + test.Drain("9096") + err := e.Start() + assert.Nil(t, err) + defer func() { + err := e.Stop() + assert.Nil(t, err) + }() + test.Pour("9096") + + transport := &http.Transport{ + MaxIdleConns: 1, + } + defer transport.CloseIdleConnections() + client := &http.Client{ + Transport: transport, + } + request := func() string { + req, err := http.NewRequest(http.MethodGet, "http://localhost:9096/pets/4", nil) + assert.Nil(t, err) + response, err := client.Do(req) + assert.Nil(t, err) + body, err := ioutil.ReadAll(response.Body) + assert.Nil(t, err) + response.Body.Close() + return string(body) + } + + body := request() + assert.NotEqual(t, 0, len(body)) +} +/* +func TestResourceHandlerExampleAPI_File(t *testing.T) { + if testing.Short() { + t.Skip("skipping Basic Gateway API integration test in short mode") + } + + e, err := AsyncGatewayExample() + assert.Nil(t, err) + testAsyncGatewayExample(t, e) +}*/ + +func TestResourceHandlerExampleJSON_HTTP(t *testing.T) { + if testing.Short() { + t.Skip("skipping Basic Gateway JSON integration test in short mode") + } + data, err := ioutil.ReadFile(filepath.FromSlash("./json/resource-handler/httpResource/flogo.json")) + assert.Nil(t, err) + cfg, err := engine.LoadAppConfig(string(data), false) + assert.Nil(t, err) + e, err := engine.New(cfg) + assert.Nil(t, err) + testResourceHandlerExampleHTTP(t, e) +} diff --git a/examples/json/resource-handler/httpResource/main.go b/examples/json/resource-handler/httpResource/main.go index 8e58379..bcd415c 100644 --- a/examples/json/resource-handler/httpResource/main.go +++ b/examples/json/resource-handler/httpResource/main.go @@ -58,7 +58,19 @@ func main() { panic(err) } }) - + http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { + fmt.Printf("url: %q\n", html.EscapeString(r.URL.Path)) + defer r.Body.Close() + _, err := ioutil.ReadAll(r.Body) + if err != nil { + panic(err) + } + w.Header().Set("Content-Type", "application/json") + _, err = w.Write([]byte(resource)) + if err != nil { + panic(err) + } + }) err := http.ListenAndServe(":1234", nil) if err != nil { panic(err) From 82ce450419c217412ff896345edccbf1b0c2656b Mon Sep 17 00:00:00 2001 From: Akshay Gadikar Date: Mon, 11 Mar 2019 10:23:16 -0700 Subject: [PATCH 10/11] 1. Added API implementation 2. Added testcases 3. Added Readme --- action.go | 6 +- .../resource-handler/fileResource/README.md | 30 +++++++ .../api/resource-handler/fileResource/main.go | 14 ++++ .../resource-handler/httpResource/README.md | 35 ++++++++ .../api/resource-handler/httpResource/main.go | 80 +++++++++++++++++++ examples/examples.go | 72 +++++++++++++++++ examples/examples_test.go | 75 +++++++++-------- .../resource-handler/httpResource/README.md | 13 +-- .../resource-handler/httpResource/main.go | 16 +--- 9 files changed, 284 insertions(+), 57 deletions(-) create mode 100644 examples/api/resource-handler/fileResource/README.md create mode 100644 examples/api/resource-handler/fileResource/main.go create mode 100644 examples/api/resource-handler/httpResource/README.md create mode 100644 examples/api/resource-handler/httpResource/main.go diff --git a/action.go b/action.go index c5cde77..0924d15 100644 --- a/action.go +++ b/action.go @@ -132,9 +132,9 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { } if resData := api.GetResource(uri); resData != nil { actionData = resData - } else if resData := resourceMap[uri]; resData != nil{ + } else if resData := resourceMap[uri]; resData != nil { actionData = resData.(*api.Microgateway) - }else if url.Scheme == "http" { + } else if url.Scheme == "http" { //get resource from http res, err := http.Get(uri) if err != nil { @@ -178,7 +178,7 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { } actionData = resData.Object().(*api.Microgateway) } - }else if p := act.settings.Pattern; p != "" { + } else if p := act.settings.Pattern; p != "" { definition, err := Load(p) if err != nil { return nil, err diff --git a/examples/api/resource-handler/fileResource/README.md b/examples/api/resource-handler/fileResource/README.md new file mode 100644 index 0000000..a756c50 --- /dev/null +++ b/examples/api/resource-handler/fileResource/README.md @@ -0,0 +1,30 @@ +# Gateway using File Resource +This recipe is a gateway using the file resource. + +## Installation +* Install [Go](https://golang.org/) + +## Setup +```bash +git clone https://github.com/project-flogo/microgateway +cd microgateway/examples/api/resource-handler/fileResource +``` + +## Testing + +Start the gateway: +```bash +go run main.go +``` +and test below scenario. + +### Request is successful +Run the following command: +```bash +curl --request GET http://localhost:9096/endpoint +``` + +You should see: +```json +{"category":{"id":0,"name":"string"},"id":4,"name":"hc0x3yiw302","photoUrls":["string"],"status":"available","tags":[{"id":0,"name":"string"}]} +``` \ No newline at end of file diff --git a/examples/api/resource-handler/fileResource/main.go b/examples/api/resource-handler/fileResource/main.go new file mode 100644 index 0000000..b4a5666 --- /dev/null +++ b/examples/api/resource-handler/fileResource/main.go @@ -0,0 +1,14 @@ +package main + +import ( + "github.com/project-flogo/core/engine" + "github.com/project-flogo/microgateway/examples" +) + +func main() { + e, err := examples.FileResourceHandlerExample() + if err != nil { + panic(err) + } + engine.RunEngine(e) +} diff --git a/examples/api/resource-handler/httpResource/README.md b/examples/api/resource-handler/httpResource/README.md new file mode 100644 index 0000000..5601e86 --- /dev/null +++ b/examples/api/resource-handler/httpResource/README.md @@ -0,0 +1,35 @@ +# Gateway using HTTP Resource +This recipe is a gateway using the HTTP resource. The resource is downloaded from the requested HTTP server + +## Installation +* Install [Go](https://golang.org/) + +## Setup +```bash +git clone https://github.com/project-flogo/microgateway +cd microgateway/examples/api/resource-handler/httpResource +``` + +## Testing + +In terminal start the server first: +```bash +go run main.go -server +``` + +Start the gateway: +```bash +go run main.go +``` +and test below scenario. + +### Request is successful +Run the following command: +```bash +curl --request GET http://localhost:9096/endpoint +``` + +You should see: +```json +{"category":{"id":0,"name":"string"},"id":4,"name":"hc0x3yiw302","photoUrls":["string"],"status":"available","tags":[{"id":0,"name":"string"}]} +``` \ No newline at end of file diff --git a/examples/api/resource-handler/httpResource/main.go b/examples/api/resource-handler/httpResource/main.go new file mode 100644 index 0000000..8d6cd9d --- /dev/null +++ b/examples/api/resource-handler/httpResource/main.go @@ -0,0 +1,80 @@ +package main + +import ( + "flag" + "fmt" + "html" + "io/ioutil" + "net/http" + + "github.com/project-flogo/core/engine" + "github.com/project-flogo/microgateway/examples" +) + +var ( + server = flag.Bool("server", false, "run the test server") +) + +const resource = `{ + "name": "Pets", + "steps": [{ + "service": "PetStorePets", + "input": { + "pathParams": "=$.payload.pathParams" + } + }], + "responses": [{ + "error": false, + "output": { + "code": 200, + "data": "=$.PetStorePets.outputs.data" + } + }], + "services": [{ + "name": "PetStorePets", + "description": "Get pets by ID from the petstore", + "ref": "github.com/project-flogo/contrib/activity/rest", + "settings": { + "uri": "http://petstore.swagger.io/v2/pet/:petId", + "method": "GET", + "headers": { + "Accept": "application/json" + } + } + }] +}` + +func main() { + + flag.Parse() + + if *server { + http.HandleFunc("/pets", func(w http.ResponseWriter, r *http.Request) { + fmt.Printf("url: %q\n", html.EscapeString(r.URL.Path)) + defer r.Body.Close() + body, err := ioutil.ReadAll(r.Body) + if err != nil { + panic(err) + } + fmt.Println(string(body)) + w.Header().Set("Content-Type", "application/json") + _, err = w.Write([]byte(resource)) + if err != nil { + panic(err) + } + }) + + err := http.ListenAndServe(":1234", nil) + if err != nil { + panic(err) + } + + return + } + + e, err := examples.HTTPResourceHandlerExample() + if err != nil { + panic(err) + } + engine.RunEngine(e) +} diff --git a/examples/examples.go b/examples/examples.go index a775f46..4d123aa 100644 --- a/examples/examples.go +++ b/examples/examples.go @@ -287,3 +287,75 @@ func AsyncGatewayExample() (engine.Engine, error) { return api.NewEngine(app) } + +// ResourceHandlerGateway :- read resource from file system +func FileResourceHandlerExample() (engine.Engine, error) { + app := api.NewApp() + + gateway := microapi.New("Pets") + service := gateway.NewService("PetStorePets", &rest.Activity{}) + service.SetDescription("Get pets by ID from the petstore") + service.AddSetting("uri", "http://petstore.swagger.io/v2/pet/:petId") + service.AddSetting("method", "GET") + service.AddSetting("headers", map[string]string{ + "Accept": "application/json", + }) + step := gateway.NewStep(service) + step.AddInput("pathParams", "=$.payload.pathParams") + response := gateway.NewResponse(false) + response.SetCode(200) + response.SetData("=$.PetStorePets.outputs.data") + + trg := app.NewTrigger(&trigger.Trigger{}, &trigger.Settings{Port: 9096}) + handler, err := trg.NewHandler(&trigger.HandlerSettings{ + Method: "GET", + Path: "/pets/:petId", + }) + if err != nil { + return nil, err + } + + _, err = handler.NewAction(µgateway.Action{}, map[string]interface{}{ + "uri": "file:///Users/agadikar/microgateway/examples/json/resource-handler/fileResource/resource.json"}) + if err != nil { + return nil, err + } + + return api.NewEngine(app) +} + +// ResourceHandlerGateway :- getting Http resource +func HTTPResourceHandlerExample() (engine.Engine, error) { + app := api.NewApp() + + gateway := microapi.New("Pets") + service := gateway.NewService("PetStorePets", &rest.Activity{}) + service.SetDescription("Get pets by ID from the petstore") + service.AddSetting("uri", "http://petstore.swagger.io/v2/pet/:petId") + service.AddSetting("method", "GET") + service.AddSetting("headers", map[string]string{ + "Accept": "application/json", + }) + step := gateway.NewStep(service) + step.AddInput("pathParams", "=$.payload.pathParams") + response := gateway.NewResponse(false) + response.SetCode(200) + response.SetData("=$.PetStorePets.outputs.data") + + trg := app.NewTrigger(&trigger.Trigger{}, &trigger.Settings{Port: 9096}) + handler, err := trg.NewHandler(&trigger.HandlerSettings{ + Method: "GET", + Path: "/pets/:petId", + }) + if err != nil { + return nil, err + } + + _, err = handler.NewAction(µgateway.Action{}, map[string]interface{}{ + "uri": "http://localhost:1234/pets"}) + if err != nil { + return nil, err + } + + return api.NewEngine(app) +} diff --git a/examples/examples_test.go b/examples/examples_test.go index b3099a2..cefb90f 100644 --- a/examples/examples_test.go +++ b/examples/examples_test.go @@ -2,8 +2,8 @@ package examples import ( "context" - //"encoding/json" - //"fmt" + "encoding/json" + "fmt" "io/ioutil" "net/http" "path/filepath" @@ -30,7 +30,7 @@ type handler struct { Slow bool } -type resourceHandler struct{ +type resourceHandler struct { Slow bool } @@ -111,7 +111,6 @@ const resource = `{ }] }` -/* func testBasicGatewayApplication(t *testing.T, e engine.Engine) { defer api.ClearResources() test.Drain("9096") @@ -458,17 +457,16 @@ func testResourceHandlerExampleFile(t *testing.T, e engine.Engine) { assert.NotEqual(t, 0, len(body)) } -/* func TestResourceHandlerExampleAPI_File(t *testing.T) { if testing.Short() { t.Skip("skipping Basic Gateway API integration test in short mode") } - e, err := AsyncGatewayExample() + e, err := FileResourceHandlerExample() assert.Nil(t, err) - testAsyncGatewayExample(t, e) -}*/ -/* + testResourceHandlerExampleFile(t, e) +} + func TestResourceHandlerExampleJSON_File(t *testing.T) { if testing.Short() { t.Skip("skipping Basic Gateway JSON integration test in short mode") @@ -481,28 +479,9 @@ func TestResourceHandlerExampleJSON_File(t *testing.T) { assert.Nil(t, err) testResourceHandlerExampleFile(t, e) } -*/ - func testResourceHandlerExampleHTTP(t *testing.T, e engine.Engine) { defer api.ClearResources() - - test.Drain("1234") - testHandler := resourceHandler{} - s := &http.Server{ - Addr: ":1234", - Handler: &testHandler, - ReadTimeout: 10 * time.Second, - WriteTimeout: 10 * time.Second, - MaxHeaderBytes: 1 << 20, - } - go func() { - s.ListenAndServe() - }() - test.Pour("1234") - defer s.Shutdown(context.Background()) - - test.Drain("9096") err := e.Start() assert.Nil(t, err) @@ -533,16 +512,29 @@ func testResourceHandlerExampleHTTP(t *testing.T, e engine.Engine) { body := request() assert.NotEqual(t, 0, len(body)) } -/* -func TestResourceHandlerExampleAPI_File(t *testing.T) { + +func TestResourceHandlerExampleAPI_HTTP(t *testing.T) { if testing.Short() { t.Skip("skipping Basic Gateway API integration test in short mode") } - - e, err := AsyncGatewayExample() + test.Drain("1234") + testHandler := resourceHandler{} + s := &http.Server{ + Addr: ":1234", + Handler: &testHandler, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + MaxHeaderBytes: 1 << 20, + } + go func() { + s.ListenAndServe() + }() + test.Pour("1234") + defer s.Shutdown(context.Background()) + e, err := HTTPResourceHandlerExample() assert.Nil(t, err) - testAsyncGatewayExample(t, e) -}*/ + testResourceHandlerExampleHTTP(t, e) +} func TestResourceHandlerExampleJSON_HTTP(t *testing.T) { if testing.Short() { @@ -552,6 +544,21 @@ func TestResourceHandlerExampleJSON_HTTP(t *testing.T) { assert.Nil(t, err) cfg, err := engine.LoadAppConfig(string(data), false) assert.Nil(t, err) + test.Drain("1234") + testHandler := resourceHandler{} + s := &http.Server{ + Addr: ":1234", + Handler: &testHandler, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + MaxHeaderBytes: 1 << 20, + } + go func() { + s.ListenAndServe() + }() + test.Pour("1234") + defer s.Shutdown(context.Background()) + e, err := engine.New(cfg) assert.Nil(t, err) testResourceHandlerExampleHTTP(t, e) diff --git a/examples/json/resource-handler/httpResource/README.md b/examples/json/resource-handler/httpResource/README.md index 32b806b..c25a714 100644 --- a/examples/json/resource-handler/httpResource/README.md +++ b/examples/json/resource-handler/httpResource/README.md @@ -20,17 +20,17 @@ flogo install github.com/project-flogo/contrib/activity/rest flogo build ``` +In another terminal start the server first: +```bash +go run main.go -server +``` + Start the gateway: ``` bin/MyProxy ``` and test below scenario. -In another terminal start the server: -```bash -go run main.go -server -``` - ### Request is successful ```bash curl http://localhost:9096/pets/1 @@ -38,4 +38,5 @@ curl http://localhost:9096/pets/1 You should then see something like: ```json -{"category":{"id":0,"name":"string"},"id":1,"name":"aspen","photoUrls":["string"],"status":"done","tags":[{"id":0,"name":"string"}]} \ No newline at end of file +{"category":{"id":0,"name":"string"},"id":4,"name":"hc0x3yiw302","photoUrls":["string"],"status":"available","tags":[{"id":0,"name":"string"}]} +``` \ No newline at end of file diff --git a/examples/json/resource-handler/httpResource/main.go b/examples/json/resource-handler/httpResource/main.go index bcd415c..3b2aace 100644 --- a/examples/json/resource-handler/httpResource/main.go +++ b/examples/json/resource-handler/httpResource/main.go @@ -48,23 +48,11 @@ func main() { http.HandleFunc("/pets", func(w http.ResponseWriter, r *http.Request) { fmt.Printf("url: %q\n", html.EscapeString(r.URL.Path)) defer r.Body.Close() - _, err := ioutil.ReadAll(r.Body) - if err != nil { - panic(err) - } - w.Header().Set("Content-Type", "application/json") - _, err = w.Write([]byte(resource)) - if err != nil { - panic(err) - } - }) - http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { - fmt.Printf("url: %q\n", html.EscapeString(r.URL.Path)) - defer r.Body.Close() - _, err := ioutil.ReadAll(r.Body) + body, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } + fmt.Println(string(body)) w.Header().Set("Content-Type", "application/json") _, err = w.Write([]byte(resource)) if err != nil { From 9aefa1679963fbb35e9a2d3577e3530e31e2fe0c Mon Sep 17 00:00:00 2001 From: Andrew Snodgrass Date: Tue, 12 Mar 2019 13:40:42 -0600 Subject: [PATCH 11/11] Improvements --- action.go | 9 ++--- .../api/resource-handler/fileResource/main.go | 2 +- examples/examples.go | 4 +-- examples/examples_test.go | 34 ++++++++++++++++++- .../resource-handler/fileResource/flogo.json | 2 +- 5 files changed, 42 insertions(+), 9 deletions(-) diff --git a/action.go b/action.go index 0924d15..35772a4 100644 --- a/action.go +++ b/action.go @@ -9,6 +9,7 @@ import ( "net/http" "net/url" "os" + "path/filepath" "strings" _ "github.com/project-flogo/contrib/function" @@ -46,7 +47,7 @@ func init() { } var actionMetadata = action.ToMetadata(&Settings{}, &Input{}, &Output{}) -var resourceMap = make(map[string]interface{}) +var resourceMap = make(map[string]*api.Microgateway) // LoadResource loads the microgateway definition func (m *Manager) LoadResource(config *resource.Config) (*resource.Resource, error) { @@ -128,12 +129,12 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { if uri := act.settings.URI; uri != "" { url, err := url.Parse(uri) if err != nil { - panic(err) + return nil, err } if resData := api.GetResource(uri); resData != nil { actionData = resData } else if resData := resourceMap[uri]; resData != nil { - actionData = resData.(*api.Microgateway) + actionData = resData } else if url.Scheme == "http" { //get resource from http res, err := http.Get(uri) @@ -154,7 +155,7 @@ func (f *Factory) New(config *action.Config) (action.Action, error) { actionData = definition } else if url.Scheme == "file" { //get resource from local file system - resData, err := ioutil.ReadFile(uri[7:]) + resData, err := ioutil.ReadFile(filepath.FromSlash(uri[7:])) if err != nil { return nil, fmt.Errorf("File reading error") } diff --git a/examples/api/resource-handler/fileResource/main.go b/examples/api/resource-handler/fileResource/main.go index b4a5666..cc56c22 100644 --- a/examples/api/resource-handler/fileResource/main.go +++ b/examples/api/resource-handler/fileResource/main.go @@ -6,7 +6,7 @@ import ( ) func main() { - e, err := examples.FileResourceHandlerExample() + e, err := examples.FileResourceHandlerExample("file://../../../json/resource-handler/fileResource/resource.json") if err != nil { panic(err) } diff --git a/examples/examples.go b/examples/examples.go index 4d123aa..3be1be0 100644 --- a/examples/examples.go +++ b/examples/examples.go @@ -289,7 +289,7 @@ func AsyncGatewayExample() (engine.Engine, error) { } // ResourceHandlerGateway :- read resource from file system -func FileResourceHandlerExample() (engine.Engine, error) { +func FileResourceHandlerExample(uri string) (engine.Engine, error) { app := api.NewApp() gateway := microapi.New("Pets") @@ -316,7 +316,7 @@ func FileResourceHandlerExample() (engine.Engine, error) { } _, err = handler.NewAction(µgateway.Action{}, map[string]interface{}{ - "uri": "file:///Users/agadikar/microgateway/examples/json/resource-handler/fileResource/resource.json"}) + "uri": uri}) if err != nil { return nil, err } diff --git a/examples/examples_test.go b/examples/examples_test.go index cefb90f..c018378 100644 --- a/examples/examples_test.go +++ b/examples/examples_test.go @@ -462,7 +462,7 @@ func TestResourceHandlerExampleAPI_File(t *testing.T) { t.Skip("skipping Basic Gateway API integration test in short mode") } - e, err := FileResourceHandlerExample() + e, err := FileResourceHandlerExample("file://./json/resource-handler/fileResource/resource.json") assert.Nil(t, err) testResourceHandlerExampleFile(t, e) } @@ -473,6 +473,12 @@ func TestResourceHandlerExampleJSON_File(t *testing.T) { } data, err := ioutil.ReadFile(filepath.FromSlash("./json/resource-handler/fileResource/flogo.json")) assert.Nil(t, err) + flogoApp := FlogoJSON{} + err = json.Unmarshal(data, &flogoApp) + assert.Nil(t, err) + flogoApp.Actions[0].Settings["uri"] = "file://./json/resource-handler/fileResource/resource.json" + data, err = json.Marshal(&flogoApp) + assert.Nil(t, err) cfg, err := engine.LoadAppConfig(string(data), false) assert.Nil(t, err) e, err := engine.New(cfg) @@ -563,3 +569,29 @@ func TestResourceHandlerExampleJSON_HTTP(t *testing.T) { assert.Nil(t, err) testResourceHandlerExampleHTTP(t, e) } + +// FlogoJSON is the flogo JSON +type FlogoJSON struct { + Name string `json:"name"` + Type string `json:"type"` + Version string `json:"version"` + Desc string `json:"description"` + Prop interface{} `json:"properties"` + Channels interface{} `json:"channels"` + Trig interface{} `json:"triggers"` + Resources []struct { + ID string `json:"id"` + Compress bool `json:"compressed"` + Data struct { + Name string `json:"name"` + Steps []interface{} `json:"steps"` + Responses []interface{} `json:"responses"` + Services []map[string]interface{} `json:"services"` + } `json:"data"` + } `json:"resources"` + Actions []struct { + Ref string `json:"ref"` + Settings map[string]interface{} `json:"settings"` + ID string `json:"id"` + } `json:"actions"` +} diff --git a/examples/json/resource-handler/fileResource/flogo.json b/examples/json/resource-handler/fileResource/flogo.json index c8b24ee..b7b729a 100644 --- a/examples/json/resource-handler/fileResource/flogo.json +++ b/examples/json/resource-handler/fileResource/flogo.json @@ -32,7 +32,7 @@ { "ref": "github.com/project-flogo/microgateway", "settings": { - "uri": "file:///Users/agadikar/microgateway/examples/json/resource-handler/fileResource/resource.json" + "uri": "file://../resource.json" }, "id": "microgateway:Pets", "metadata": null