Skip to content

Custom Serializer/Deserializer

Choose a tag to compare

@fulldump fulldump released this 28 Mar 10:37
· 3 commits to master since this release

Use custom serializer and deserializer functions :D

b := NewBox()

b.Serializer = func(ctx context.Context, w io.Writer, v interface{}) error {
	// Your custom code here:
	resp := GetBoxContext(ctx).Response
	resp.Header().Set("Content-Type", "application/json+customwrap")
	resp.WriteHeader(http.StatusFound)

	json.NewEncoder(w).Encode(map[string]interface{}{
		"wrap": v,
	})

	return nil
}

b.Deserializer = func(ctx context.Context, r io.Reader, v interface{}) error {
	// Your custom code here:
	payload, err := io.ReadAll(r)
	if err != nil {
		return err
	}

	if len(payload) > 15 {
		return ErrPayloadTooLong
	}

	return json.Unmarshal(payload, v)
}