Skip to content

ing-bank/gohateoas

Folders and files

NameName
Last commit message
Last commit date

Latest commit

b09cf32 Β· May 7, 2024

History

28 Commits
Nov 30, 2022
Nov 18, 2022
Sep 20, 2023
Nov 18, 2022
Sep 20, 2023
Dec 23, 2022
Nov 18, 2022
Sep 20, 2023
Sep 20, 2023
Jan 16, 2023
Jan 16, 2023
May 7, 2024
Nov 18, 2022
Sep 20, 2023

Repository files navigation

🦁 Golang Hateoas

Go package GitHub GitHub go.mod Go version

Hateoas isn't always necessary for a REST API to function, but it's definitely a nice-to-have. This library provides a simple way to add hateoas links to your API responses, regardless of the wrapper object you use.

⬇️ Installation

go get github.com/ing-bank/gohateoas

πŸ“‹ Usage

package main

import (
	"fmt"
	"github.com/ing-bank/gohateoas"
	"encoding/json"
)

// APIResponse is a simple struct that will be used as a wrapper for our response.
type APIResponse struct {
	Data any `json:"data"`
}

// MarshalJSON overrides the usual json.Marshal behaviour to allow us to add links to the response
func (a APIResponse) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Data json.RawMessage `json:"data"`
	}{
		Data: gohateoas.InjectLinks(gohateoas.DefaultLinkRegistry, a.Data),
	})
}

type Cupcake struct{}

func main() {
	gohateoas.Register(Cupcake{}, gohateoas.Self("/api/v1/cupcakes/{id}", "Get this cupcake"),
		gohateoas.Post("/api/v1/cupcakes", "Create a cupcake"),
		gohateoas.Patch("/api/v1/cupcakes/{id}", "Partially update a cupcake"),
		gohateoas.Delete("/api/v1/cupcakes?id={id}", "Delete this cupcake"))

	response := APIResponse{Data: Cupcake{}}

	jsonBytes, _ := json.Marshal(response)

	fmt.Println(string(jsonBytes))
}

πŸš€ Development

  1. Clone the repository
  2. Run make t to run unit tests
  3. Run make fmt to format code

You can run make to see a list of useful commands.

πŸ”­ Future Plans

  • Add support for custom link-property name