feat(): allow scripts with extensions

This commit is contained in:
Nicolas Carlier 2020-02-01 08:47:18 +00:00
parent d793c7813d
commit 28288739f3
5 changed files with 32 additions and 11 deletions

View File

@ -60,14 +60,19 @@ You can override the default using the `WHD_SCRIPTS_DIR` environment variable or
|--> /github
|--> /build.sh
|--> /deploy.sh
|--> /ping.sh
|--> /push.js
|--> /echo.sh
|--> ...
```
Note that Webhookd is able to run any type of file in this directory as long as the file is executable.
For example, you can execute a Node.js file if you give execution rights to the file and add the appropriate `#!` header (in this case: `#!/usr/bin/env node`).
### Webhook URL
The directory structure define the webhook URL.
You can omit the script extension. If you do, webhookd will search for a `.sh` file.
If the script exists, the output the will be streamed to the HTTP response.
The streaming technology depends on the HTTP method used.
@ -97,7 +102,6 @@ $ curl -v -XPOST http://localhost:8080/foo/bar
< X-Hook-Id: 7
foo foo foo
bar bar bar
done
```
Output using `GET` (`Server-sent events`):
@ -111,8 +115,6 @@ $ curl -v -XGET http://localhost:8080/foo/bar
data: foo foo foo
data: bar bar bar
data: done
```
### Webhook parameters
@ -146,7 +148,6 @@ $ curl --data @test.json http://localhost:8080/echo?foo=bar
Query parameter: foo=bar
Header parameter: user-agent=curl/7.52.1
Script parameter: {"foo": "bar"}
done
```
### Webhook timeout configuration

View File

@ -2,7 +2,6 @@ package tools
import (
"errors"
"fmt"
"os"
"path"
"strings"
@ -10,7 +9,10 @@ import (
// ResolveScript is resolving the target script.
func ResolveScript(dir, name string) (string, error) {
script := path.Clean(path.Join(dir, fmt.Sprintf("%s.sh", name)))
if path.Ext(name) == "" {
name = name + ".sh"
}
script := path.Clean(path.Join(dir, name))
if !strings.HasPrefix(script, dir) {
return "", errors.New("Invalid script path: " + name)
}

View File

@ -22,5 +22,11 @@ func TestNotResolveScript(t *testing.T) {
func TestResolveBadScript(t *testing.T) {
_, err := tools.ResolveScript("../../scripts", "../tests/test_simple")
assert.NotNil(t, err, "")
assert.Equal(t, "Invalid script path: ../tests/test_simple", err.Error(), "")
assert.Equal(t, "Invalid script path: ../tests/test_simple.sh", err.Error(), "")
}
func TestResolveScriptWithExtension(t *testing.T) {
_, err := tools.ResolveScript("../../scripts", "node.js")
assert.NotNil(t, err, "")
assert.Equal(t, "Script not found: ../../scripts/node.js", err.Error(), "")
}

15
scripts/examples/echo.js Executable file
View File

@ -0,0 +1,15 @@
#!/usr/bin/env node
const os = require('os')
// Usage: http POST :8080/examples/echo.js msg==hello foo=bar
console.log("Echo script:")
console.log("Hostname=", os.hostname())
console.log("User-Agent=", process.env["user_agent"])
console.log("msg=", process.env["msg"])
console.log("body=", process.argv)

View File

@ -1,3 +0,0 @@
#!/usr/bin/env node
console.log("hello world!")