Skip to content

Commit

Permalink
Merge pull request #1121 from yquansah/yq-override-json
Browse files Browse the repository at this point in the history
feat: add definition for overridable json engine
  • Loading branch information
Fenny authored Jan 31, 2021
2 parents 66c457d + 5941c8c commit 267fd5e
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
11 changes: 11 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ package fiber
import (
"bufio"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
5 changes: 5 additions & 0 deletions utils/json_marshal.go
Original file line number Diff line number Diff line change
@@ -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)
26 changes: 26 additions & 0 deletions utils/json_marshal_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 267fd5e

Please sign in to comment.