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

Overview

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"
	// }
}
Issues
Owner
Richard Knop
I'm an experienced software engineer, open source contributor. I have mostly focused on backend programming in Go & Python
Richard Knop
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

Rogério Araújo 2 Oct 21, 2021
Separate files into folders by extension

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

Abdessamad Bensaad 0 Dec 26, 2021
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

Daniël Pot 1 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

Jefferson Otoni Lima 39 Jan 5, 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

HItesh Choudhary 35 Dec 29, 2021
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

null 0 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

Vinícius Garcia 15 Jan 6, 2022
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

Brian Min 1 Nov 9, 2021
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

Sabra Bilodeau 0 Nov 28, 2021
Simple first method GRPC on GO

Simple first method GRPC on GO

Van Thinh Nguyen 4 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 //..

Bregy Malpartida 9 Mar 26, 2019
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 ;)

Abir Ghosh 1 Jan 19, 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

Elmedin Turkeš 2 Nov 9, 2021
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

alvaro garcia fernandez 0 Dec 18, 2021
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

Binalyze 55 Jan 1, 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

Nick Law 44 Jan 21, 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

Ali OYGUR 96 Dec 16, 2021
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

Cory Jacobsen 1.6k Jan 11, 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

Aliaksandr Valialkin 1.4k Jan 14, 2022
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

null 2 Jan 4, 2022
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

Gyoza Tech 35 Dec 29, 2021
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

Diego Hordi 0 Nov 24, 2021
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

Jaap Groeneveld 16 Jan 9, 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 |

 Aatman 2 Jan 5, 2022
GoLobby DotEnv is a lightweight package for loading dot env (.env) files into structs for Go projects

DotEnv GoLobby DotEnv is a lightweight package for loading dot env (.env) files into structs for Go projects Documentation Supported Versions It requi

GoLobby 8 Dec 1, 2021
A better way to marshal and unmarshal YAML in Golang

YAML marshaling and unmarshaling support for Go Introduction A wrapper around go-yaml designed to enable a better way of handling YAML when marshaling

Sam Ghods 870 Jan 18, 2022
Fast JSON encoder/decoder compatible with encoding/json for Go

Fast JSON encoder/decoder compatible with encoding/json for Go

Masaaki Goshima 1.3k Jan 15, 2022
gron transforms JSON into discrete assignments to make it easier to grep

gron Make JSON greppable! gron transforms JSON into discrete assignments to make it easier to grep for what you want and see the absolute 'path' to it

null 0 Nov 2, 2021
Gron transforms JSON into discrete assignments to make it easier to grep

gron Make JSON greppable! gron transforms JSON into discrete assignments to make it easier to grep for what you want and see the absolute 'path' to it

Stanislav 0 Nov 4, 2021