This template provides additional context and control over the HTTP response from your function.
This template is pre-release and is likely to change - please provide feedback via https://github.com/openfaas/faas
The template makes use of the OpenFaaS incubator project of-watchdog.
$ faas template pull https://github.com/openfaas-incubator/golang-http-template
$ faas new --lang golang-http <fn-name>
Example writing a successful message:
package function
import (
"fmt"
"net/http"
"github.com/openfaas-incubator/go-function-sdk"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
message := fmt.Sprintf("Hello world, input was: %s", string(req.Body))
return handler.Response{
Body: []byte(message),
}, err
}
Example writing a custom status code
package function
import (
"fmt"
"net/http"
"github.com/openfaas-incubator/go-function-sdk"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
return handler.Response{
Body: []byte("Your workload was accepted"),
StatusCode: http.StatusAccepted,
}, err
}
Example writing an error / failure.
package function
import (
"fmt"
"net/http"
"github.com/openfaas-incubator/go-function-sdk"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
return handler.Response{
Body: []byte("the input was invalid")
}, fmt.Errorf("invalid input")
}
The error will be logged to stderr
and the body
will be written to the client along with a HTTP 500 status code.
Example reading a header.
package function
import (
"log"
"github.com/openfaas-incubator/go-function-sdk"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
log.Println(req.Header) // Check function logs for the request headers
return handler.Response{
Body: []byte("This is the response"),
Header: map[string][]string{
"X-Served-By": []string{"My Awesome Function"},
},
}, err
}