rip

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2023 License: BSD-3-Clause Imports: 11 Imported by: 1

README

RIP ⚰ Go Reference Go Report Card

REST in peace

Why?

Creating RESTful API in Go is in a way simple and fun in the first time, but also repetitive and error prone the more resources you handle.
Copy pasting nearly the same code for each resource you want to GET or POST to except for the request and response types is not that cool, and interface{} neither.
Let's get the best of both worlds with GENERICS 🎆 everybody screams 😱

How?

The idea would be to use the classic net/http package with handlers created from Go types.

http.HandleFunc(rip.HandleEntity[User]("/users", NewUserProvider())

// in Go 1.21, you can skip the type specification
http.HandleFunc(rip.HandleEntity("/users", NewUserProvider())

given that UserProvider implements the rip.EntityProvider interface

// simplified version
type EntityProvider[Ent Entity] interface {
	Create(ctx context.Context, ent Ent) (Ent, error)
	Get(ctx context.Context, id Entity) (Ent, error)
	Update(ctx context.Context, ent Ent) error
	Delete(ctx context.Context, id Entity) error
	ListAll(ctx context.Context) ([]Ent, error)
}

and your resource implements the Entity interface

type Entity interface {
	IDString() string
	IDFromString(s string) error
}

Right now, it can talk several encoding in reading and writing: JSON, XML, YAML, msgpack, HTML and HTML form. Based on Accept and Content-Type headers, you can be asymmetrical in encoding: send JSON and read XML.

HTML/HTML Forms allows you to edit your resources directly from your web browser. It's very basic for now.

⚠️: Disclaimer, the API is not stable yet, use or contribute at your own risks

* Final code may differ from actual shown footage

Play with it

go run github.com/dolanor/rip/examples/srv-example@latest
// open your browser to http://localhost:8888/users/ and start editing users

Features

  • support for multiple encoding automatically selected with Accept and Content-Type headers, or resource extension /entities/1.json
    • JSON
    • YAML
    • XML
    • msgpack
    • HTML (read version)
    • HTML forms (write version)
  • middlewares
  • automatic generation of HTML forms for live editing of resources

TODO

  • middleware support
  • I'd like to have more composability in the resource provider (some are read-only, some can't list, some are write only…), haven't figured out the right way to design that, yet.
  • it should work for nested resources
  • improve the error API
  • support for hypermedia discoverability
  • support for multiple data representation

Documentation

Overview

Example
package main

import (
	"context"
	"net/http"
	"time"
)

func main() {
	up := newUserProvider()
	http.HandleFunc(HandleEntities("/users/", up))

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}

type user struct {
	Name         string    `json:"name" xml:"name"`
	EmailAddress string    `json:"email_address" xml:"email_address"`
	BirthDate    time.Time `json:"birth_date" xml:"birth_date"`
}

func (u user) IDString() string {
	return u.Name
}

func (u *user) IDFromString(s string) error {
	u.Name = s

	return nil
}

type UserProvider struct {
	mem map[string]user
}

func newUserProvider() *UserProvider {
	return &UserProvider{
		mem: map[string]user{},
	}
}

func (up *UserProvider) Create(ctx context.Context, u *user) (*user, error) {
	up.mem[u.Name] = *u
	return u, nil
}

func (up UserProvider) Get(ctx context.Context, entity Entity) (*user, error) {
	u, ok := up.mem[entity.IDString()]
	if !ok {
		return &user{}, ErrNotFound
	}
	return &u, nil
}

func (up *UserProvider) Delete(ctx context.Context, entity Entity) error {
	_, ok := up.mem[entity.IDString()]
	if !ok {
		return ErrNotFound
	}

	delete(up.mem, entity.IDString())
	return nil
}

func (up *UserProvider) Update(ctx context.Context, u *user) error {
	_, ok := up.mem[u.Name]
	if !ok {
		return ErrNotFound
	}
	up.mem[u.Name] = *u

	return nil
}

func (up *UserProvider) ListAll(ctx context.Context) ([]*user, error) {
	var users []*user
	for _, u := range up.mem {
		// we copy to avoid referring the same pointer that would get updated
		u := u
		users = append(users, &u)
	}

	return users, nil
}

Index

Examples

Constants

View Source
const NewEntityID = "rip-new-entity-id"

Variables

View Source
var (
	ErrNotFound = ripError{
		Code:    ErrorCodeNotFound,
		Status:  http.StatusNotFound,
		Message: "entity not found",
	}
)

Functions

func Handle

func Handle[
	Input, Output any,
](
	method string, f InputOutputFunc[Input, Output],
) http.HandlerFunc

Handle is a generic HTTP handler that maps an HTTP method to a RequestResponseFunc f.

func HandleEntities added in v0.1.4

func HandleEntities[
	Ent Entity,
	EP EntityProvider[Ent],
](
	urlPath string,
	ep EP,
	middlewares ...Middleware,
) (path string, handler http.HandlerFunc)

HandleEntities associates an urlPath with an entity provider, and handles all HTTP requests in a RESTful way:

POST   /entities/    : creates the entity
GET    /entities/:id : get the entity
PUT    /entities/:id : updates the entity (needs to pass the full entity data)
DELETE /entities/:id : deletes the entity
GET    /entities/    : lists the entities

Types

type Entity added in v0.1.4

type Entity interface {
	// IDString returns an ID in form of a string.
	IDString() string

	// IDFromString serialize an ID from s.
	IDFromString(s string) error
}

Entity is a resource that can be identified by an string. It comes from the concept of entity in Domain Driven Design.

type EntityCreater added in v0.1.4

type EntityCreater[Ent Entity] interface {
	Create(ctx context.Context, ent Ent) (Ent, error)
}

EntityCreater creates a entity that can be identified.

type EntityDeleter added in v0.1.4

type EntityDeleter[Ent Entity] interface {
	Delete(ctx context.Context, id Entity) error
}

EntityDeleter deletes a entity with its id.

type EntityGetter added in v0.1.4

type EntityGetter[Ent Entity] interface {
	Get(ctx context.Context, id Entity) (Ent, error)
}

EntityGetter gets a entity with its id.

type EntityLister added in v0.1.4

type EntityLister[Ent any] interface {
	ListAll(ctx context.Context) ([]Ent, error)
}

EntityLister lists a group of entities.

type EntityProvider added in v0.1.4

type EntityProvider[Ent Entity] interface {
	EntityCreater[Ent]
	EntityGetter[Ent]
	EntityUpdater[Ent]
	EntityDeleter[Ent]
	EntityLister[Ent]
}

EntityProvider provides identifiable entities.

type EntityUpdater added in v0.1.4

type EntityUpdater[Ent Entity] interface {
	Update(ctx context.Context, ent Ent) error
}

EntityUpdater updates an identifiable entity.

type ErrorCode

type ErrorCode int

ErrorCode maps errors from the ResourceProvider implementation to HTTP status code.

const (
	// ErrorCodeNotFound happens when a resource with an id is not found.
	ErrorCodeNotFound ErrorCode = http.StatusNotFound

	// ErrorCodeBadQArg happens when a user gives a wrongly formatted header `; q=X.Y` argument.
	ErrorCodeBadQArg ErrorCode = 499
)

type InputOutputFunc added in v0.1.4

type InputOutputFunc[
	Input, Output any,
] func(ctx context.Context, input Input) (output Output, err error)

InputOutputFunc is a function that takes a ctx and an input, and it can return an output or an err.

type Middleware added in v0.1.4

type Middleware func(http.HandlerFunc) http.HandlerFunc

Middleware is an HTTP Middleware that you can add to your handler to handle specific actions like logging, authentication, authorization, metrics, ….

Directories

Path Synopsis
xml
examples
srv-example command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL