savsgio/atreugo

Configurable JSON Marshaller

Christoph-Harms opened this issue · 2 comments

For users to be able to use other libs than encoding/json for JSON marshalling, this should be a configurable option, supposedly like so:

type Config struct {
    // ...existing stuff...

    JSONMarshaller          func(v interface{}) ([]byte, error)
}

This should default to encoding/json's Marshal() function. It would then be used like this (using json-iterator as an example replacement):

import(
    "github.com/savsgio/atreugo/v11"

    jsoniter "github.com/json-iterator/go"
)
// ...other stuff...

config := atreugo.Config{
    // ...other stuff...
    
    JSONMarshaller:      jsoniter.ConfigCompatibleWithStandardLibrary.Marshal
}

router := atreugo.New(config)

// ...other stuff

Atreugo's JSONResponse() should then use this function to marshal the JSON response.

I'm happy to implement this myself provided there's any interest in having it. 😊

Usecase:

  • You are maintaining a massive JSON API of some sort, which uses Atreugo.
  • You learn that there are alternative JSON libs for go that are much faster then encoding/json, and you want to profit from this.
  • Rather then having to go through your massive codebase, find every use of JSONResponse(), marshal the response manually and change it to ctx.Response.SetBody(marshaled), you would much prefer to just have to configure Atreugo once in your main file.

Hi @Christoph-Harms,

I think it could be a great feature, so i'd be happy to review a PR.

Thank you so much!