A simple Go package to make custom structs marshal into HAL compatible JSON responses.

jsonhal

A simple Go package to make custom structs marshal into HAL compatible JSON responses.

Travis Status for RichardKnop/jsonhal godoc for RichardKnop/jsonhal codecov for RichardKnop/jsonhal


Just add jsonhal.Hal as anonymous field to your structs and use SetLink to set hyperlinks and optionally SetEmbedded to set embedded resources.

Example:

package main

import (
	"encoding/json"
	"log"

	"github.com/RichardKnop/jsonhal"
)

// HelloWorld ...
type HelloWorld struct {
	jsonhal.Hal
	ID   uint   `json:"id"`
	Name string `json:"name"`
}

// Foobar ...
type Foobar struct {
	jsonhal.Hal
	ID   uint   `json:"id"`
	Name string `json:"name"`
}

func main() {
	var (
		helloWorld   *HelloWorld
		jsonResponse []byte
		err          error
	)

	helloWorld = &HelloWorld{ID: 1, Name: "Hello World"}
	helloWorld.SetLink("self", "/v1/hello/world/1", "")

	jsonResponse, err = json.Marshal(helloWorld)
	if err != nil {
		log.Fatal(err)
	}
	log.Print(string(jsonResponse))
	// {
	// 	"_links": {
	// 		"self": {
	// 			"href": "/v1/hello/world/1"
	// 		}
	// 	},
	// 	"id": 1,
	// 	"name": "Hello World"
	// }

	helloWorld = &HelloWorld{ID: 1, Name: "Hello World"}
	helloWorld.SetLink(
		"self", // name
		"/v1/hello/world?offset=2&limit=2", // href
		"", // title
	)
	helloWorld.SetLink(
		"next", // name
		"/v1/hello/world?offset=4&limit=2", // href
		"", // title
	)
	helloWorld.SetLink(
		"previous",                         // name
		"/v1/hello/world?offset=0&limit=2", // href
		"", // title
	)
	jsonResponse, err = json.Marshal(helloWorld)
	if err != nil {
		log.Fatal(err)
	}
	log.Print(string(jsonResponse))
	// {
	// 	"_links": {
	// 		"next": {
	// 			"href": "/v1/hello/world?offset=4\u0026limit=2"
	// 		},
	// 		"previous": {
	// 			"href": "/v1/hello/world?offset=0\u0026limit=2"
	// 		},
	// 		"self": {
	// 			"href": "/v1/hello/world?offset=2\u0026limit=2"
	// 		}
	// 	},
	// 	"id": 1,
	// 	"name": "Hello World"
	// }

	helloWorld = &HelloWorld{ID: 1, Name: "Hello World"}
	helloWorld.SetLink("self", "/v1/hello/world/1", "")

	// Add embedded resources
	foobars := []*Foobar{
		&Foobar{
			Hal: jsonhal.Hal{
				Links: map[string]*jsonhal.Link{
					"self": &jsonhal.Link{Href: "/v1/foo/bar/1"},
				},
			},
			ID:   1,
			Name: "Foo bar 1",
		},
		&Foobar{
			Hal: jsonhal.Hal{
				Links: map[string]*jsonhal.Link{
					"self": &jsonhal.Link{Href: "/v1/foo/bar/2"},
				},
			},
			ID:   2,
			Name: "Foo bar 2",
		},
	}
	helloWorld.SetEmbedded("foobars", Embedded(foobars))

	jsonResponse, err = json.Marshal(helloWorld)
	if err != nil {
		log.Fatal(err)
	}
	log.Print(string(jsonResponse))
	// {
	// 	"_links": {
	// 		"self": {
	// 			"href": "/v1/hello/world/1"
	// 		}
	// 	},
	// 	"_embedded": {
	// 		"foobars": [
	// 			{
	// 				"_links": {
	// 					"self": {
	// 						"href": "/v1/foo/bar/1"
	// 					}
	// 				},
	// 				"id": 1,
	// 				"name": "Foo bar 1"
	// 			},
	// 			{
	// 				"_links": {
	// 					"self": {
	// 						"href": "/v1/foo/bar/2"
	// 					}
	// 				},
	// 				"id": 2,
	// 				"name": "Foo bar 2"
	// 			}
	// 		]
	// 	},
	// 	"id": 1,
	// 	"name": "Hello World"
	// }
}
Owner
Richard Knop
I'm an experienced software engineer, open source contributor. I have mostly focused on backend programming in Go & Python
Richard Knop
Similar Resources

Simple boilerplate code to get started with building and deploying a serverless CRUD API

Simple boilerplate code to get started with building and deploying a serverless CRUD API with Go, MongoDB and Netlify

Jan 20, 2022

Simple first method GRPC on GO

Simple first method GRPC on GO

Dec 10, 2021

Simple script for farm free books from PackPub.com

Bookgot BookGot is a simple boot for farm free books from PACKTPUB.COM #Install go get -u github.com/bregydoc/Bookgot Usage First import BookGot //..

Mar 26, 2019

`go-redash-query` is a simple library to get structed data from `redash query` sources

go-redash-query go-redash-query is a simple library to get structed data from redash query sources Example Source table id name email 1 Dannyhann rhrn

May 22, 2022

JPRQ Customizer is a customizer that helps to use the JPRQ server code and make it compatible with your own server with custom subdomain and domain

JPRQ Customizer is a customizer that helps to use the JPRQ server code and make it compatible with your own server with custom subdomain and domain

JPRQ Customizer is a customizer that helps to use the JPRQ server code and make it compatible with your own server with custom subdomain and domain.You can upload the generated directory to your web server and expose user localhost to public internet. You can use this to make your local machine a command center for your ethical hacking purpose ;)

Jan 19, 2022

atomic time package with json Marshal / Unmarshal support

ATime Atomic Time package for Go, optimized for performance yet simple to use. Usage // one line create dt := atime.New() // allocates *AtomicTime dt

Feb 6, 2022

Allows parsing CSV files into custom structs and implements required fields that can't be empty

Welcome to Go Custom CSV Parser 👋 Allows parsing CSV files into custom structs and implements required fields that can't be empty 🏠 Homepage Install

Nov 9, 2021

A fast, easy-of-use and dependency free custom mapping from .csv data into Golang structs

csvparser This package provides a fast and easy-of-use custom mapping from .csv data into Golang structs. Index Pre-requisites Installation Examples C

Nov 14, 2022

Fast JSON parser and validator for Go. No custom structs, no code generation, no reflection

fastjson - fast JSON parser and validator for Go Features Fast. As usual, up to 15x faster than the standard encoding/json. See benchmarks. Parses arb

Jan 5, 2023

Easy JSON parser for Go. No custom structs, no code generation, no reflection

Easy JSON parser for Go. No custom structs, no code generation, no reflection

Dec 28, 2022

A Go package for handling common HTTP JSON responses.

go-respond A Go package for handling common HTTP JSON responses. Installation go get github.com/nicklaw5/go-respond Usage The goal of go-respond is to

Sep 26, 2022

Go package that handles HTML, JSON, XML and etc. responses

gores http response utility library for Go this package is very small and lightweight, useful for RESTful APIs. installation go get github.com/alioygu

Oct 31, 2022

Go package for easily rendering JSON, XML, binary data, and HTML templates responses.

Render Render is a package that provides functionality for easily rendering JSON, XML, text, binary data, and HTML templates. This package is based on

Jan 8, 2023

httpreq is an http request library written with Golang to make requests and handle responses easily.

httpreq is an http request library written with Golang to make requests and handle responses easily. Install go get github.com/binalyze/http

Feb 10, 2022

Marshal data into commands struct!

Marshal data into commands struct!

Commandarrgh in a nuthsell Commandarrgh is an interface that helps you marshaling data into a command arguments structure. Maybe you have been trying

Dec 18, 2021

Parametrized JSON logging library in Golang which lets you obfuscate sensitive data and marshal any kind of content.

Parametrized JSON logging library in Golang which lets you obfuscate sensitive data and marshal any kind of content.

Noodlog Summary Noodlog is a Golang JSON parametrized and highly configurable logging library. It allows you to: print go structs as JSON messages; pr

Oct 27, 2022

Go package that adds marshal and unmarshal features to nullable sql types.

#Nullable Very simple Go module to handle nullable fields. Basically, it adds to sql package types the JSON marshal and unmarshal features. It has 100

Jan 20, 2022

K8s-go-structs - All k8s API Go structs

k8s-api go types Why? Its nice to have it all in a single package. . |-- pkg |

Jul 17, 2022

Quick and easy expression matching for JSON schemas used in requests and responses

schema schema makes it easier to check if map/array structures match a certain schema. Great for testing JSON API's or validating the format of incomi

Dec 24, 2022
Comments
  • Added map structure.Decoder to get support for son fields of type timeTime

    Added map structure.Decoder to get support for son fields of type timeTime

    I've used your fork instead of the original one because I liked the idea of DecodeEmbedded. But unfortunately it failed in the very first use of that function because map structure isn't able to handle time.Time fields out of the box.

    For me it was much easier to add the functionality here instead of filling the gap in map structure. I'll appreciate it if you will merge it into your fork.

    kind regards

    Reinhard

  • Do not reuse decoder, otherwise previous result is overwritten

    Do not reuse decoder, otherwise previous result is overwritten

    When using DecodeEmbedded twice with different result arguments, the second call uses the first result because the cached decoder contains a pointer to the result

A practical journey into the Golang Programming Language

OneTutorial - A practical journey into the Golang Programming Language This little project will help you touch many topics around Golang, in a small a

Oct 21, 2021
Separate files into folders by extension

Sffae Sffae (stands for Separate files into folders by extension) is a tiny gola

Dec 26, 2021
Digging into the ins and outs of Golang boxing.

Golang boxing This repository is used to dig into the ins and outs of Golang boxing. Prerequisites The examples in this repository require Golang 1.18

Dec 16, 2022
Simple Notifier/Listener utility package to pass around messages in-memory

Simple Observer (go) A small simple library to use for sending around messages in-memory. It uses a notifier/listener style messaging. Installation go

Dec 7, 2021
Simples exemplo de CRUD para armazenar em memoria os dados vindo do JSON.

API Growth Este repositório foi criado para colocarmos projetos em diversas linguagens com intúito totalmente didático para colaborar com a comunidade

Dec 14, 2022
A complete guide to undersatnd golang programming language, web requests, JSON and creating web APIs with mongodb

Golang series A complete guide to undersatnd golang programming language, web requests, JSON and creating web APIs with mongodb LearnCodeonline.in 01

Jan 1, 2023
My ML - A machine learning package based on golang

my_ML a machine learning package based on golang 这是一个基于golang的机器学习库和一些机器学习的数据集,可

Feb 15, 2022
An open source programming language that makes it easy to build simple
An open source programming language that makes it easy to build simple

The Go Programming Language Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. Gopher ima

Oct 15, 2021
This is an example of a keep-it-simple directory layout for Go projects that was created using DDD principles, please copy and share if you like it.

DDD Go Template This project was created to illustrate a great architectural structure I developed together with @fabiorodrigues in the period I was w

Dec 5, 2022
Repository for COMP 429 Programming Assignment# 1 - A simple chat application, by Sabra Bilodeau.

Chatty COMP 429 Programming Assignment 1 A Chat Application for Remote Message Exchange by Sabra Bilodeau Getting Started with Chatty Building the Pro

Nov 28, 2021