|
| 1 | +OpenFaaS Golang HTTP template |
| 2 | +============================================= |
| 3 | + |
| 4 | +This template provides additional context and control over the HTTP response from your function. |
| 5 | + |
| 6 | +## Status of the template |
| 7 | + |
| 8 | +This template is pre-release and is likely to change - please provide feedback via https://github.com/openfaas/faas |
| 9 | + |
| 10 | +The template makes use of the OpenFaaS incubator project [of-watchdog](https://github.com/openfaas-incubator/of-watchdog). |
| 11 | + |
| 12 | +## Trying the template |
| 13 | + |
| 14 | +``` |
| 15 | +$ faas template pull https://github.com/alexellis/golang-http-template |
| 16 | +$ faas new --lang golang-http |
| 17 | +``` |
| 18 | + |
| 19 | +## Example usage |
| 20 | + |
| 21 | +Example writing a successful message: |
| 22 | + |
| 23 | +```go |
| 24 | +package function |
| 25 | + |
| 26 | +import ( |
| 27 | + "fmt" |
| 28 | + "net/http" |
| 29 | + |
| 30 | + "github.com/openfaas-incubator/go-function-sdk" |
| 31 | +) |
| 32 | + |
| 33 | +// Handle a function invocation |
| 34 | +func Handle(req handler.Request) (handler.Response, error) { |
| 35 | + var err error |
| 36 | + |
| 37 | + message := fmt.Sprintf("Hello world, input was: %s", string(req.Body)) |
| 38 | + |
| 39 | + return handler.Response{ |
| 40 | + Body: []byte(message), |
| 41 | + }, err |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +Example writing a custom status code |
| 46 | + |
| 47 | +```go |
| 48 | +package function |
| 49 | + |
| 50 | +import ( |
| 51 | + "fmt" |
| 52 | + "net/http" |
| 53 | + |
| 54 | + "github.com/openfaas-incubator/go-function-sdk" |
| 55 | +) |
| 56 | + |
| 57 | +// Handle a function invocation |
| 58 | +func Handle(req handler.Request) (handler.Response, error) { |
| 59 | + var err error |
| 60 | + |
| 61 | + return handler.Response{ |
| 62 | + Body: []byte("Your workload was accepted"), |
| 63 | + StatusCode: http.StatusAccepted, |
| 64 | + }, err |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +Example writing an error / failure. |
| 69 | + |
| 70 | +```go |
| 71 | +package function |
| 72 | + |
| 73 | +import ( |
| 74 | + "fmt" |
| 75 | + "net/http" |
| 76 | + |
| 77 | + "github.com/openfaas-incubator/go-function-sdk" |
| 78 | +) |
| 79 | + |
| 80 | +// Handle a function invocation |
| 81 | +func Handle(req handler.Request) (handler.Response, error) { |
| 82 | + var err error |
| 83 | + |
| 84 | + return handler.Response{ |
| 85 | + Body: []byte("the input was invalid") |
| 86 | + }, fmt.Errorf("invalid input") |
| 87 | +} |
| 88 | +``` |
| 89 | + |
| 90 | +The error will be logged to `stderr` and the `body` will be written to the client along with a HTTP 500 status code. |
0 commit comments