goresource

package module
v0.0.0-...-af653b8 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2018 License: MIT Imports: 7 Imported by: 1

README

goresource Build Status codecov coveralls

goresource provides a micro framework for easy implementation of RESTful APIs with golang.

Overview

goresource comes with a few basic structs and interfaces.

  • An Entity is an interface for any type that needs to be persisted and operated on.
  • A Resource is a struct corresponding each entity that can do http request handling.
  • A ResourceManager ties together a Resource and an Entity.
Example

Let's say we have a Book type.

type Book {
  ID   string `json:"id"`
  ISBN string `json:"isbn"`
  Name string `json:"name"`
}

To implement a RESTful API for the Book type, first we satisfy the Entity interface for Book.

func (b Book) HasId() bool {
  if b.ID != "" {
      return true
    }
    return false
}

func (b Book) GetId() string {
  return b.ID
}

Next we write a ResourceManager for Book.

type BookManager struct {
  goresource.DefaultManager
}

func NewBookManager(name string, store store.Store) *BookManager {
  return &BookManager{goresource.NewDefaultManager(name, store)}
}

BookManager should satify the ResourceManager interface

func (manager *BookManager) New() goresource.Entity {
  return &Book{}
}

func (manager *BookManager) ParseJSON(data io.ReadCloser) (goresource.Entity, error) {
  book, ok := manager.New().(*Book)
    if !ok {
      return nil, fmt.Errorf("error creating new book.")
  }
    decoder := json.NewDecoder(data)
    err := decoder.Decode(book)
    if err != nil {
      return nil, err
    }
    return book, nil
}

Finally we create a new Resource with the BookManager

router := mux.NewRouter().PathPrefix("/api").Subrouter()
store, _ := store.NewMongoStore("localhost:27017", "booksdb")
defer store.Close()

manager := NewBookManager("books", store)
bookResource := goresource.NewResource(manager, router)

The router can them be used to serve the REST API endpoints.

http.Handle("/", router)
http.ListenAndServe(":8080", nil)

See the example directory for the full example code.

Installation

go get github.com/rockstardevs/goresource

Test

tests are written using ginkgo.

go get github.com/onsi/ginkgo/ginkgo github.com/onsi/gomega

To run all tests recursively

ginkgo -r

Updating Mocks

mockgen -package mocks -destination mocks/store.go goresource/store Store
mockgen -package mocks -destination mocks/manager.go goresource ResourceManager

TODO/What could be better

  • Implement PATCH and OPTIONS
  • Remove hard dependency on mux.Router and accept any Router.
  • Implement addition stores, currently only MongoDB is implemented.

Contributing

Pull requests are welcome. Please ensure to include tests.

Documentation

Overview

Package goresource provides a micro REST framework.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DefaultManager

type DefaultManager struct {
	// Name is used a prefix for routes as well as the database collection name.
	Name  string
	Store store.Store
}

DefaultManager is a default implementation for ResourceManager. It implements defaults for all methods except New and ParseJSON.

func NewDefaultManager

func NewDefaultManager(name string, store store.Store) DefaultManager

NewDefaultManager initializes and returns a DefaultManager.

func (DefaultManager) CreateEntity

func (manager DefaultManager) CreateEntity(e Entity, _ url.Values) (interface{}, error)

CreateEntity persists the given entity.

func (DefaultManager) DeleteEntity

func (manager DefaultManager) DeleteEntity(id string, _ url.Values) error

DeleteEntity removes a single entity with the given id.

func (DefaultManager) GetEntity

func (manager DefaultManager) GetEntity(id string, _ url.Values) (interface{}, error)

GetEntity fetches a single resource entity with the given id.

func (DefaultManager) GetName

func (manager DefaultManager) GetName() string

GetName returns the name for this DefaultManager.

func (DefaultManager) ListEntities

func (manager DefaultManager) ListEntities(query url.Values) (interface{}, error)

ListEntities fetches all resource entities.

func (DefaultManager) UpdateEntity

func (manager DefaultManager) UpdateEntity(id string, e Entity, _ url.Values) (interface{}, error)

UpdateEntity persists changes to the given entity with the given id.

type Entity

type Entity interface {
	HasId() bool
	GetId() string
}

Entity is an interface implemented by entities we store in the database.

type Resource

type Resource struct {
	// contains filtered or unexported fields
}

Resource provides an abstraction to be able to store and retrieve entities via a RESTful api. It is responsible for request handling and writing responses. The acutal persistence and any entity specific operations are delegated to the corresponding ResourceManager. This decouples request handing and persistence from specific entity types.

func NewResource

func NewResource(m ResourceManager, router *mux.Router) *Resource

NewResource instantiates a Resource and binds routes to the given mux router, to serve the api end points specific to this resource.

func (Resource) Delete

func (r Resource) Delete(rw http.ResponseWriter, req *http.Request)

Delete is the delegate http handler for delete requests for this resource.

func (Resource) Get

func (r Resource) Get(rw http.ResponseWriter, req *http.Request)

Get is the delegate http handler for get requests for this resource.

func (Resource) Head

func (r Resource) Head(rw http.ResponseWriter, req *http.Request)

Head is the delegate http handler for head requests for this resource.

func (Resource) Patch

func (r Resource) Patch(rw http.ResponseWriter, req *http.Request)

Patch is the delegate http handler for patch requests for this resource.

func (Resource) PostOrPut

func (r Resource) PostOrPut(rw http.ResponseWriter, req *http.Request)

PostOrPut is the common code between put and post requests. TODO: This is partially incorrect according to the spec. PUT without an id in the uri is invalid and should return a BadRequest error. Fix this to comply to with the spec.

func (Resource) ServeHTTP

func (r Resource) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP is the main http handler that handles all api request for this resource. It delegates based on HTTP Method to other methods of this resource.

func (Resource) UnsupportedMethod

func (r Resource) UnsupportedMethod(rw http.ResponseWriter, req *http.Request)

UnsupportedMethod is the delegate http handler for unknown requests types. This is the catch-all when request method is not known.

type ResourceManager

type ResourceManager interface {
	GetName() string
	New() Entity
	GetEntity(id string, query url.Values) (interface{}, error)
	CreateEntity(entity Entity, query url.Values) (interface{}, error)
	ListEntities(query url.Values) (interface{}, error)
	UpdateEntity(id string, entity Entity, query url.Values) (interface{}, error)
	DeleteEntity(id string, query url.Values) error
	ParseJSON(io.ReadCloser) (Entity, error)
}

ResourceManager is an interface implemented by managers for entities.

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
package store implements a database store for goresource.
package store implements a database store for goresource.
Package util provides utility functions for goresource.
Package util provides utility functions for goresource.

Jump to

Keyboard shortcuts

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