Skip to content

Commit

Permalink
feat: Add Go helper functions for HttpResponse (#2622)
Browse files Browse the repository at this point in the history
`builtin/external_module.go` will have a couple of helper functions
added:
```
// A helper for successful HttpResponse
//
func HttpSuccess[E any, B any](code int, body B) HttpResponse[B, E] {
  return HttpResponse[B, E]{Status: code, Body: ftl.Some(body)}
}

// A helper for HttpResponse with error
//
func HttpError[B any, E any](code int, e E) HttpResponse[B, E] {
  return HttpResponse[B, E]{Status: code, Error: ftl.Some(e)}
}
```

Fixes: #1632
  • Loading branch information
tomdaffurn authored Sep 6, 2024
1 parent 4f4ca4e commit a48978d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,7 @@ type QueryParamRequest struct {

//ftl:ingress http GET /queryparams
func Query(ctx context.Context, req builtin.HttpRequest[ftl.Unit, ftl.Unit, QueryParamRequest]) (builtin.HttpResponse[string, string], error) {
return builtin.HttpResponse[string, string]{
Body: ftl.Some(req.Query.Foo.Default("No value")),
}, nil
return builtin.HttpSuccess[string](200, req.Query.Foo.Default("No value")), nil
}

//ftl:ingress http GET /html
Expand Down Expand Up @@ -138,7 +136,7 @@ func Int(ctx context.Context, req builtin.HttpRequest[int, ftl.Unit, ftl.Unit])

//ftl:ingress http POST /float
func Float(ctx context.Context, req builtin.HttpRequest[float64, ftl.Unit, ftl.Unit]) (builtin.HttpResponse[float64, string], error) {
return builtin.HttpResponse[float64, string]{Body: ftl.Some(req.Body)}, nil
return builtin.HttpSuccess[string](200, req.Body), nil
}

//ftl:ingress http POST /bool
Expand All @@ -148,10 +146,7 @@ func Bool(ctx context.Context, req builtin.HttpRequest[bool, ftl.Unit, ftl.Unit]

//ftl:ingress http GET /error
func Error(ctx context.Context, req builtin.HttpRequest[ftl.Unit, ftl.Unit, ftl.Unit]) (builtin.HttpResponse[ftl.Unit, string], error) {
return builtin.HttpResponse[ftl.Unit, string]{
Status: 500,
Error: ftl.Some("Error from FTL"),
}, nil
return builtin.HttpError[ftl.Unit](500, "Error from FTL"), nil
}

//ftl:ingress http POST /array/string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,17 @@ func init() {
)
}
{{- end}}
{{- if eq .Module.Name "builtin"}}

// A helper for successful HttpResponse
//
func HttpSuccess[E any, B any](code int, body B) HttpResponse[B, E] {
return HttpResponse[B, E]{Status: code, Body: ftl.Some(body)}
}

// A helper for HttpResponse with error
//
func HttpError[B any, E any](code int, e E) HttpResponse[B, E] {
return HttpResponse[B, E]{Status: code, Error: ftl.Some(e)}
}
{{- end}}

0 comments on commit a48978d

Please sign in to comment.