Skip to content

Commit

Permalink
fix up readme advanced example with updated API
Browse files Browse the repository at this point in the history
  • Loading branch information
rdallman committed Oct 25, 2018
1 parent 80587e8 commit eccde19
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ will take 2 minutes!
# Advanced example

TODO going to move to [examples](examples/) too :)
TODO make these `_example.go` instead of in markdown ;)

```go
package main
Expand All @@ -41,21 +42,32 @@ func main() {
fdk.Handle(fdk.HandlerFunc(myHandler))
}

// TODO make http.Handler example

func myHandler(ctx context.Context, in io.Reader, out io.Writer) {
fnctx := fdk.Context(ctx)
fnctx, ok := fdk.GetContext(ctx).(fdk.HTTPContext)
if !ok {
// optionally, this may be a good idea
fdk.WriteStatus(out, 400)
fdk.SetHeader(out, "Content-Type", "application/json")
io.WriteString(out, `{"error":"function not invoked via http trigger"}`)
return
}

contentType := fnctx.Header.Get("Content-Type")
contentType := fnctx.Header().Get("Content-Type")
if contentType != "application/json" {
// can assert content type for your api this way
fdk.WriteStatus(out, 400)
fdk.SetHeader(out, "Content-Type", "application/json")
io.WriteString(out, `{"error":"invalid content type"}`)
return
}

if fnctx.Method != "PUT" {
if fnctx.RequestMethod() != "PUT" {
// can assert certain request methods for certain endpoints
fdk.WriteStatus(out, 404)
fdk.SetHeader(out, "Content-Type", "application/json")
io.WriteString(out, `{"error":"route not found"}`)
io.WriteString(out, `{"error":"route not found, method not supported"}`)
return
}

Expand All @@ -64,20 +76,23 @@ func myHandler(ctx context.Context, in io.Reader, out io.Writer) {
}
json.NewDecoder(in).Decode(&person)

// you can write your own headers & status, if you'd like to
fdk.WriteStatus(out, 201)
fdk.SetHeader(out, "Content-Type", "application/json")
// this is where you might insert person into a database or do something else

all := struct {
Name string `json:"name"`
URL string `json:"url"`
Header http.Header `json:"header"`
Config map[string]string `json:"config"`
}{
Name: person.Name,
Header: fnctx.Header,
Config: fnctx.Config,
Name: person.Name,
URL: fnctx.RequestURL(),
Header: fnctx.Header(),
Config: fnctx.Config(),
}

// you can write your own headers & status, if you'd like to
fdk.SetHeader(out, "Content-Type", "application/json")
fdk.WriteStatus(out, 201)
json.NewEncoder(out).Encode(&all)
}
```

0 comments on commit eccde19

Please sign in to comment.