mirror of https://github.com/gofiber/fiber.git
🚀 feat: add custom definition for a json executor
parent
3762a8520e
commit
2267f0f76f
10
app.go
10
app.go
|
@ -270,6 +270,13 @@ type Config struct {
|
|||
//
|
||||
// Default: false
|
||||
// RedirectFixedPath bool
|
||||
|
||||
// When set by an external client of Fiber it will use the provided implementation of a
|
||||
// JSONExectuor
|
||||
//
|
||||
// Allowing for flexibility in using another json library for marshalling/unmarshalling
|
||||
// Default: utils.DefaultJSONExecutor
|
||||
JSONEngineExecutor utils.JSONExecutor `json:"-"`
|
||||
}
|
||||
|
||||
// Static defines configuration options when defining static assets.
|
||||
|
@ -378,6 +385,9 @@ func New(config ...Config) *App {
|
|||
if app.config.ErrorHandler == nil {
|
||||
app.config.ErrorHandler = DefaultErrorHandler
|
||||
}
|
||||
if app.config.JSONEngineExecutor == nil {
|
||||
app.config.JSONEngineExecutor = &utils.DefaultJSONExecutor{}
|
||||
}
|
||||
|
||||
// Init app
|
||||
app.init()
|
||||
|
|
2
ctx.go
2
ctx.go
|
@ -536,7 +536,7 @@ func (c *Ctx) Is(extension string) bool {
|
|||
// and a nil slice encodes as the null JSON value.
|
||||
// This method also sets the content header to application/json.
|
||||
func (c *Ctx) JSON(data interface{}) error {
|
||||
raw, err := json.Marshal(data)
|
||||
raw, err := c.app.config.JSONEngineExecutor.Marshal(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// JSONExecutor provides the minimal API for basic JSON engine functionality
|
||||
type JSONExecutor interface {
|
||||
Marshal(interface{}) ([]byte, error)
|
||||
}
|
||||
|
||||
// DefaultJSONExecutor is a blank structure, in place to satisfy the API
|
||||
// of a JSONExecutor
|
||||
type DefaultJSONExecutor struct {
|
||||
}
|
||||
|
||||
// Marshal takes in an arbitrary interface and returns an encoding of
|
||||
// the provided interface
|
||||
func (d *DefaultJSONExecutor) Marshal(v interface{}) ([]byte, error) {
|
||||
return json.Marshal(v)
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDefaultJSONExecutor(t *testing.T) {
|
||||
type SampleStructure struct {
|
||||
ImportantString string `json:"important_string"`
|
||||
}
|
||||
|
||||
var (
|
||||
sampleStructure = &SampleStructure{
|
||||
ImportantString: "Hello World",
|
||||
}
|
||||
importantString = `{"important_string":"Hello World"}`
|
||||
)
|
||||
|
||||
jsonExecutor := DefaultJSONExecutor{}
|
||||
|
||||
raw, err := jsonExecutor.Marshal(sampleStructure)
|
||||
AssertEqual(t, err, nil)
|
||||
|
||||
AssertEqual(t, string(raw), importantString)
|
||||
}
|
Loading…
Reference in New Issue