🚀 feat: add custom definition for a json executor

pull/1121/head
Yoofi Quansah 2021-01-19 19:42:51 -08:00
parent 3762a8520e
commit 2267f0f76f
4 changed files with 57 additions and 1 deletions

10
app.go
View File

@ -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
View File

@ -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
}

21
utils/json_executor.go Normal file
View File

@ -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)
}

View File

@ -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)
}