Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added function in openapi3.operation #370

Merged
merged 20 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"io/fs"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -326,3 +328,55 @@ func body[B any](c netHttpContext[B]) (B, error) {

return body, err
}

type netHttpContextWithParams[T any] struct {
netHttpContext[T]
}

func (c netHttpContextWithParams[T]) Params() (T, error) {
var t T
typeOfT := reflect.TypeOf(t)
valueOfT := reflect.New(typeOfT).Elem()

for i := 0; i < typeOfT.NumField(); i++ {
field := typeOfT.Field(i)
fieldValue := valueOfT.Field(i)

if headerKey, ok := field.Tag.Lookup("header"); ok {
if headerValue := c.Request().Header.Get(headerKey); headerValue != "" {
fieldValue.SetString(headerValue)
}
}

if queryKey, ok := field.Tag.Lookup("query"); ok {
if queryValue := c.Request().URL.Query().Get(queryKey); queryValue != "" {
if fieldValue.Kind() == reflect.Ptr {
if fieldValue.Type().Elem().Kind() == reflect.Int {
intVal, err := strconv.Atoi(queryValue)
if err != nil {
return t, err
}
fieldValue.Set(reflect.ValueOf(&intVal))
} else {
fieldValue.Set(reflect.ValueOf(&queryValue))
}
} else {
fieldValue.SetString(queryValue)
}
}
}

if cookieKey, ok := field.Tag.Lookup("cookie"); ok {
if cookie, err := c.Request().Cookie(cookieKey); err == nil {
fieldValue.SetString(cookie.Value)
}
}
}

return valueOfT.Interface().(T), nil
}





TheRanomial marked this conversation as resolved.
Show resolved Hide resolved
97 changes: 0 additions & 97 deletions documentation/docs/guides/controllers.md
TheRanomial marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,97 +0,0 @@
# Controllers

Controllers are the main way to interact with the application. They are responsible for handling the requests and responses.

## Controller types

### Returning JSON

```go
func (c fuego.ContextNoBody) (MyResponse, error)
```

Used when the request does not have a body. The response will be automatically serialized to JSON.

```go
func (c fuego.ContextWithBody[MyInput]) (MyResponse, error)
```

Used when the request has a body.
Fuego will automatically parse the body and validate it using the input struct.

### Returning HTML

```go
func (c fuego.ContextNoBody) (fuego.HTML, error)
```

Some special interface return types are used by Fuego to return special responses.

- `fuego.HTML` is used to return HTML responses from `html/template`.
- `fuego.Templ` is used to return HTML responses from `a-h/templ`.
- `fuego.Gomponent` is used to return HTML responses from `maragudk/gomponent`.

### Example of a JSON controller

```go
type MyInput struct {
Name string `json:"name"`
}

type MyResponse struct {
Message string `json:"message"`
}

func MyController(c fuego.ContextWithBody[MyInput]) (MyResponse, error) {
body, err := c.Body()
if err != nil {
return MyResponse{}, err
}

return MyResponse{
Message: "Hello " + body.Name,
}, nil
}
```

## Headers

You can always go further in the request and response by using the underlying net/http request and response, by using `c.Request` and `c.Response`.

### Get request header

```go
func MyController(c fuego.ContextNoBody) (MyResponse, error) {
value := c.Header("X-My-Header")
return MyResponse{}, nil
}
```

### Set response header

```go
func MyController(c fuego.ContextNoBody) (MyResponse, error) {
c.SetHeader("X-My-Header", "value")
return MyResponse{}, nil
}
```

## Cookies

### Get request cookie

```go
func MyController(c fuego.ContextNoBody) (MyResponse, error) {
value := c.Cookie("my-cookie")
return MyResponse{}, nil
}
```

### Set response cookie

```go
func MyController(c fuego.ContextNoBody) (MyResponse, error) {
c.SetCookie("my-cookie", "value")
return MyResponse{}, nil
}
```
44 changes: 40 additions & 4 deletions openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,18 +185,54 @@
// Request Body
if route.Operation.RequestBody == nil {
bodyTag := SchemaTagFromType(openapi, *new(B))

if bodyTag.Name != "unknown-interface" {
requestBody := newRequestBody[B](bodyTag, route.RequestContentTypes)

// add request body to operation
route.Operation.RequestBody = &openapi3.RequestBodyRef{
Value: requestBody,
}
}
}

// Response - globals
TheRanomial marked this conversation as resolved.
Show resolved Hide resolved
typeOfT := reflect.TypeOf(*new(T))
TheRanomial marked this conversation as resolved.
Show resolved Hide resolved
if typeOfT != nil {
for i := 0; i < typeOfT.NumField(); i++ {
field := typeOfT.Field(i)

if headerKey, ok := field.Tag.Lookup("header"); ok {
param := &openapi3.Parameter{
Name: headerKey,
In: "header",
Schema: openapi3.NewStringSchema().NewRef(),
}
if err := route.Operation.RegisterParameters(param); err != nil {

Check failure on line 207 in openapi.go

View workflow job for this annotation

GitHub Actions / govulncheck

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 207 in openapi.go

View workflow job for this annotation

GitHub Actions / tests

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 207 in openapi.go

View workflow job for this annotation

GitHub Actions / golangci-lint

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 207 in openapi.go

View workflow job for this annotation

GitHub Actions / golangci-lint

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 207 in openapi.go

View workflow job for this annotation

GitHub Actions / golangci-lint

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)
return nil, fmt.Errorf("failed to register header parameter: %w", err)
}
}

if queryKey, ok := field.Tag.Lookup("query"); ok {
param := &openapi3.Parameter{
Name: queryKey,
In: "query",
Schema: openapi3.NewStringSchema().NewRef(),
}
if err := route.Operation.RegisterParameters(param); err != nil {

Check failure on line 218 in openapi.go

View workflow job for this annotation

GitHub Actions / govulncheck

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 218 in openapi.go

View workflow job for this annotation

GitHub Actions / tests

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 218 in openapi.go

View workflow job for this annotation

GitHub Actions / golangci-lint

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 218 in openapi.go

View workflow job for this annotation

GitHub Actions / golangci-lint

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 218 in openapi.go

View workflow job for this annotation

GitHub Actions / golangci-lint

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)
return nil, fmt.Errorf("failed to register query parameter: %w", err)
}
}

if cookieKey, ok := field.Tag.Lookup("cookie"); ok {
param := &openapi3.Parameter{
Name: cookieKey,
In: "cookie",
Schema: openapi3.NewStringSchema().NewRef(),
}
if err := route.Operation.RegisterParameters(param); err != nil {

Check failure on line 229 in openapi.go

View workflow job for this annotation

GitHub Actions / govulncheck

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 229 in openapi.go

View workflow job for this annotation

GitHub Actions / tests

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)

Check failure on line 229 in openapi.go

View workflow job for this annotation

GitHub Actions / golangci-lint

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters) (typecheck)

Check failure on line 229 in openapi.go

View workflow job for this annotation

GitHub Actions / golangci-lint

route.Operation.RegisterParameters undefined (type *openapi3.Operation has no field or method RegisterParameters)) (typecheck)
return nil, fmt.Errorf("failed to register cookie parameter: %w", err)
}
}
}
}

for _, openAPIGlobalResponse := range openapi.globalOpenAPIResponses {
addResponseIfNotSet(
openapi,
Expand Down
Loading