diff --git a/app.go b/app.go index fd290230..9f946b57 100644 --- a/app.go +++ b/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() diff --git a/ctx.go b/ctx.go index b0d0e22b..57b7996a 100644 --- a/ctx.go +++ b/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 } diff --git a/utils/json_executor.go b/utils/json_executor.go new file mode 100644 index 00000000..9fd7c5b7 --- /dev/null +++ b/utils/json_executor.go @@ -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) +} diff --git a/utils/json_executor_test.go b/utils/json_executor_test.go new file mode 100644 index 00000000..b0ea40a5 --- /dev/null +++ b/utils/json_executor_test.go @@ -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) +}