Skip to content

Commit

Permalink
Improved serialization guide
Browse files Browse the repository at this point in the history
  • Loading branch information
EwenQuim committed Jul 8, 2024
1 parent 7126685 commit e1f039e
Showing 1 changed file with 16 additions and 28 deletions.
44 changes: 16 additions & 28 deletions documentation/docs/guides/serialization.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,10 @@ To serialize data, just return the data you want to serialize from your controll
- Plain text `Accept: text/plain`

```go
package main

import (
"github.com/go-fuego/fuego"
)

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

func main() {
s := fuego.NewServer()

fuego.Get(s, "/", helloWorld)

s.Run()
}

func helloWorld(c fuego.ContextNoBody) (MyReturnType, error) {
return MyReturnType{Message: "Hello, World!"}, nil
}
Expand All @@ -56,24 +42,10 @@ func helloWorld(c fuego.ContextNoBody) (MyReturnType, error) {
To deserialize data, use the `fuego.ContextWithBody` type in your controller.

```go
package main

import (
"github.com/go-fuego/fuego"
)

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

func main() {
s := fuego.NewServer()

fuego.Post(s, "/", echo)

s.Run()
}

func echo(c fuego.ContextWithBody[ReceivedType]) (string, error) {
// Deserialize the HTTP Request body into ReceivedType,
// whether it's application/json, application/xml, application/x-www-form-urlencoded, etc.
Expand Down Expand Up @@ -103,6 +75,22 @@ fuego.Put(s, "/blob", func(c *fuego.ContextWithBody[[]byte]) (any, error) {
})
```

## Custom response - Bypass return type

If you want to bypass the automatic serialization, you can directly write to the response writer.

```go
func helloWorld(c fuego.ContextNoBody) (any, error) {
w := c.Response()
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Hello, World!")) // Write directly to the response writer.
_ = json.NewEncoder(w).Encode(MyReturnType{Message: "Hello, World!"}) // You can also use json.NewEncoder(w).Encode to serialize data directly into JSON
fuego.SendJSON(w, MyReturnType{Message: "Hello, World!"}) // Or use fuego.SendJSON to serialize data directly into JSON

return nil, nil // If you return nil, nil fuego will not try to serialize a response
}
```

## Custom serialization

But you can also use the `Serialize` and `Deserialize` functions to manually serialize and deserialize data.
Expand Down

0 comments on commit e1f039e

Please sign in to comment.