Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

main - custom json serializers #88

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions body.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package requests

import (
"bytes"
"encoding/json"
"io"
"net/url"
"os"
Expand Down Expand Up @@ -47,7 +46,7 @@ func BodyBytes(b []byte) BodyGetter {
// BodyJSON is a BodyGetter that marshals a JSON object.
func BodyJSON(v any) BodyGetter {
return func() (io.ReadCloser, error) {
b, err := json.Marshal(v)
b, err := jsonMarshal(v)
if err != nil {
return nil, err
}
Expand Down
3 changes: 1 addition & 2 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package requests
import (
"bufio"
"bytes"
"encoding/json"
"io"
"net/http"
"os"
Expand Down Expand Up @@ -46,7 +45,7 @@ func ToJSON(v any) ResponseHandler {
if err != nil {
return err
}
if err = json.Unmarshal(data, v); err != nil {
if err = jsonUnmarshal(data, v); err != nil {
return err
}
return nil
Expand Down
28 changes: 28 additions & 0 deletions json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package requests

import (
"encoding/json"
)

type jsonMarshaller = func(v any) ([]byte, error)
type jsonUnmarshaller = func(data []byte, v any) error

var (
jsonMarshal = json.Marshal
jsonUnmarshal = json.Unmarshal
)

func SetJSONUnmarshaller(j jsonUnmarshaller) {
jsonUnmarshal = j
}

func SetJSONMarshaller(j jsonMarshaller) {
jsonMarshal = j
}

// SetJSONSerializers is a function to set global json.Marshal/json.Unmarshal function
// For faster serialization/deserialization you can use functions from, for instance, https://github.com/goccy/go-json
func SetJSONSerializers(marshaller jsonMarshaller, unmarshaller jsonUnmarshaller) {
jsonMarshal = marshaller
jsonUnmarshal = unmarshaller
}