diff --git a/app.go b/app.go index 387a475bd4..63106a7b0e 100644 --- a/app.go +++ b/app.go @@ -12,6 +12,7 @@ package fiber import ( "bufio" "crypto/tls" + "encoding/json" "errors" "fmt" "net" @@ -272,6 +273,13 @@ type Config struct { // // Default: false // RedirectFixedPath bool + + // When set by an external client of Fiber it will use the provided implementation of a + // JSONMarshal + // + // Allowing for flexibility in using another json library for encoding + // Default: json.Marshal + JSONEncoder utils.JSONMarshal `json:"-"` } // Static defines configuration options when defining static assets. @@ -385,6 +393,9 @@ func New(config ...Config) *App { if app.config.ErrorHandler == nil { app.config.ErrorHandler = DefaultErrorHandler } + if app.config.JSONEncoder == nil { + app.config.JSONEncoder = json.Marshal + } // Init app app.init() diff --git a/ctx.go b/ctx.go index b0d0e22b9a..acb1492aa7 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.JSONEncoder(data) if err != nil { return err } diff --git a/utils/json_marshal.go b/utils/json_marshal.go new file mode 100644 index 0000000000..692b49a4b7 --- /dev/null +++ b/utils/json_marshal.go @@ -0,0 +1,5 @@ +package utils + +// JSONMarshal is the standard definition of representing a Go structure in +// json format +type JSONMarshal func(interface{}) ([]byte, error) diff --git a/utils/json_marshal_test.go b/utils/json_marshal_test.go new file mode 100644 index 0000000000..08501d9621 --- /dev/null +++ b/utils/json_marshal_test.go @@ -0,0 +1,26 @@ +package utils + +import ( + "encoding/json" + "testing" +) + +func TestDefaultJSONEncoder(t *testing.T) { + type SampleStructure struct { + ImportantString string `json:"important_string"` + } + + var ( + sampleStructure = &SampleStructure{ + ImportantString: "Hello World", + } + importantString = `{"important_string":"Hello World"}` + + jsonEncoder JSONMarshal = json.Marshal + ) + + raw, err := jsonEncoder(sampleStructure) + AssertEqual(t, err, nil) + + AssertEqual(t, string(raw), importantString) +}