/RestN

Library for complex output normalization.

Primary LanguageGo

RestN ( rest normalization )

Purpose of this library is more control under responses.

Install it:
go get github.com/TrueGameover/RestN



IResponseNormalizer is main interface that should be implemented by your normalizer. Normalizer allows you to control how objects are converted to "raw" format.

For example:

type Test struct {
    Time time.Time,
    Another struct { GG int }
}

How "time" field would be serialized to json? Usually this behavior needs explicit conversion to string in every place. Normalizers resolve this pain.


Let's implement simple normalizer:
import "RestN/rest"

type TimeNormalizer struct {
    rest.IResponseNormalizer
}

func (n TimeNormalizer) Normalize(object interface{}, normalize rest.NormalizeMethod, options rest.Options, depth int) interface{} {
    // depth is used for control of normalization's depth
    // options - your params that passed to normalizers 
    
    if test, ok := object.(Test); ok {
            dict := map[string]interface{}{
                "Time": test.Time.Format(time.RFC3339),
                "Another": normalize(test.Another, options, depth), // if need normalize another struct deeper
            }

	    return dict
	}

    return object
}

func (n TimeNormalizer) Support(object interface{}) (ok bool) {
    _, ok = object.(rest.Locale)
    return
}

First time initialize normalizers :
normalizers.Init()

Then register it:
rest.RegisterNormalizer(TimeNormalizer{})

Create response:

r := rest.RestResponse{}
r.SetBody(Test{ Time: time.Now(), Another: {GG: 5} })
resp.SetNormalizationOption("custom_key", "custom_value") // your customization
println(r.NormalizeResponse())

It will be normalized\customized by your normalizer every time.