Skip to content

Commit 97c32c1

Browse files
stefanprodanalexellis
authored andcommitted
Add middleware template example
Signed-off-by: Stefan Prodan <[email protected]>
1 parent c93c0a2 commit 97c32c1

File tree

1 file changed

+69
-4
lines changed

1 file changed

+69
-4
lines changed

README.md

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
1-
OpenFaaS Golang HTTP template
1+
OpenFaaS Golang HTTP templates
22
=============================================
33

4+
## golang-http
5+
46
This template provides additional context and control over the HTTP response from your function.
57

6-
## Status of the template
8+
### Status of the template
79

810
This template is pre-release and is likely to change - please provide feedback via https://github.com/openfaas/faas
911

1012
The template makes use of the OpenFaaS incubator project [of-watchdog](https://github.com/openfaas-incubator/of-watchdog).
1113

12-
## Trying the template
14+
### Trying the template
1315

1416
```
1517
$ faas template pull https://github.com/openfaas-incubator/golang-http-template
1618
$ faas new --lang golang-http <fn-name>
1719
```
1820

19-
## Example usage
21+
### Example usage
2022

2123
Example writing a successful message:
2224

@@ -114,3 +116,66 @@ func Handle(req handler.Request) (handler.Response, error) {
114116
}, err
115117
}
116118
```
119+
120+
## go-middleware
121+
122+
This template uses the http.HandlerFunc as entry point.
123+
124+
### Status of the template
125+
126+
The template makes use of the OpenFaaS incubator project [of-watchdog](https://github.com/openfaas-incubator/of-watchdog).
127+
128+
### Trying the template
129+
130+
```
131+
$ faas template pull https://github.com/openfaas-incubator/golang-http-template
132+
$ faas new --lang golang-middleware <fn-name>
133+
```
134+
135+
### Example usage
136+
137+
Example writing a json response:
138+
139+
```go
140+
package function
141+
142+
import (
143+
"encoding/json"
144+
"fmt"
145+
"io/ioutil"
146+
"net/http"
147+
"os"
148+
)
149+
150+
func Handle(w http.ResponseWriter, r *http.Request) {
151+
// read request payload
152+
reqBody, err := ioutil.ReadAll(r.Body)
153+
if err != nil {
154+
http.Error(w, err.Error(), http.StatusInternalServerError)
155+
return
156+
}
157+
158+
// log to stdout
159+
fmt.Printf("request body: %s", string(reqBody))
160+
161+
response := struct {
162+
Payload string `json:"payload"`
163+
Headers map[string][]string `json:"headers"`
164+
Environment []string `json:"environment"`
165+
}{
166+
Payload: string(reqBody),
167+
Headers: r.Header,
168+
Environment: os.Environ(),
169+
}
170+
171+
resBody, err := json.Marshal(response)
172+
if err != nil {
173+
http.Error(w, err.Error(), http.StatusInternalServerError)
174+
return
175+
}
176+
177+
// write result
178+
w.WriteHeader(http.StatusOK)
179+
w.Write(resBody)
180+
}
181+
```

0 commit comments

Comments
 (0)