Skip to content

Request Unpacking

Kosala Tennakoon edited this page Jan 7, 2020 · 3 revisions

Package /app/request

An unpacker is used to intercept the request and get the JSON payload. In addition to that unpackers are used to do basic structure validations.

All unpackers should implement the UnpackerInterface.

package request

// UnpackerInterface is the interface implemented by all unpacker data structures.
type UnpackerInterface interface {

	// RequiredFormat string representation of the required format of the relevant request body.
	RequiredFormat() string
}

By implementing this interface all unpackers will implement a RequiredFormat function that will return the expected data structure by that unpacker.

Following is an example.

package unpackers

// SampleUnpacker contains the unpacking structure for the address sent in request payload.
type SampleUnpacker struct {
	Name     string `json:"name" validate:"required"`
	Password string `json:"password" validate:"required"`
}

// NewSampleUnpacker creates a new instance of the unpacker.
func NewSampleUnpacker() *SampleUnpacker {

	return &SampleUnpacker{}
}

// RequiredFormat returns the applicable JSON format for the address data structure.
func (u *SampleUnpacker) RequiredFormat() string {

	return `{
		"name": "<string>",
		"password": "<string>"
	}`
}

The unpacker will be used as follows.

// unpack request
sampleUnpacker := unpackers.NewSampleUnpacker()
err := request.Unpack(r, sampleUnpacker)
if err != nil {
    // handle error
}

Clone this wiki locally