Skip to content

Commit

Permalink
Merge pull request #41 from project-flogo/#40-httpsupport
Browse files Browse the repository at this point in the history
#40 httpsupport
  • Loading branch information
pointlander committed Mar 12, 2019
2 parents fe88b77 + 9aefa16 commit eb1db87
Show file tree
Hide file tree
Showing 14 changed files with 761 additions and 2 deletions.
48 changes: 47 additions & 1 deletion action.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"

_ "github.com/project-flogo/contrib/function"
Expand Down Expand Up @@ -43,6 +47,7 @@ func init() {
}

var actionMetadata = action.ToMetadata(&Settings{}, &Input{}, &Output{})
var resourceMap = make(map[string]*api.Microgateway)

// LoadResource loads the microgateway definition
func (m *Manager) LoadResource(config *resource.Config) (*resource.Resource, error) {
Expand All @@ -58,7 +63,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
}

Expand Down Expand Up @@ -123,8 +127,50 @@ 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 {
return nil, err
}
if resData := api.GetResource(uri); resData != nil {
actionData = resData
} else if resData := resourceMap[uri]; resData != nil {
actionData = resData
} else if url.Scheme == "http" {
//get resource from http
res, err := http.Get(uri)
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")
}
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(filepath.FromSlash(uri[7:]))
if err != nil {
return nil, fmt.Errorf("File reading error")
}

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")
}
resourceMap[uri] = definition
actionData = definition
} else {
// Load action data from resources
resData := f.Manager.GetResource(uri)
Expand Down
1 change: 1 addition & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func GetResource(name string) *Microgateway {
resourcesMutex.RLock()
defer resourcesMutex.RUnlock()
return resources[name]

}

// ClearResources clears the resources for testing
Expand Down
30 changes: 30 additions & 0 deletions examples/api/resource-handler/fileResource/README.md
Original file line number Diff line number Diff line change
@@ -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"}]}
```
14 changes: 14 additions & 0 deletions examples/api/resource-handler/fileResource/main.go
Original file line number Diff line number Diff line change
@@ -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("file://../../../json/resource-handler/fileResource/resource.json")
if err != nil {
panic(err)
}
engine.RunEngine(e)
}
35 changes: 35 additions & 0 deletions examples/api/resource-handler/httpResource/README.md
Original file line number Diff line number Diff line change
@@ -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"}]}
```
80 changes: 80 additions & 0 deletions examples/api/resource-handler/httpResource/main.go
Original file line number Diff line number Diff line change
@@ -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)
}
72 changes: 72 additions & 0 deletions examples/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,75 @@ func AsyncGatewayExample() (engine.Engine, error) {

return api.NewEngine(app)
}

// ResourceHandlerGateway :- read resource from file system
func FileResourceHandlerExample(uri string) (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(&microgateway.Action{}, map[string]interface{}{
"uri": uri})
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(&microgateway.Action{}, map[string]interface{}{
"uri": "http://localhost:1234/pets"})
if err != nil {
return nil, err
}

return api.NewEngine(app)
}
Loading

0 comments on commit eb1db87

Please sign in to comment.