skue

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

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

Go to latest
Published: Jan 6, 2015 License: MIT Imports: 5 Imported by: 2

README

Skuë

logo

Skuë is a Go package intended to facilitate the creation of pragmatic REST APIs for Go servers.

What "skuë" means?

Skuë means "mouse" in Bribrí which is the language of an indigenous group of people of Costa Rica, my Country.

What is it?

Skuë is just some helper interfaces and functions working together to link separate software pieces in order to create an API REST-like server.

It does not force you to use a particular web server implementation or even a particular routing solution. And it allows you to control the different moving parts of your API separately so you can replace them in the future if you want to.

How it works?

Let's look at the following diagram describing the architecture of the API server that you'll create with Skuë and explain each part separately

The web server

For Skuë it's no important what web framework or http router do you use, as long as you follow REST style you will be OK. Let's see a basic example using martini:

func main() {
	m := martini.Classic()
	
	m.Get("/resources/:id", getResourceHandler)
	/* This will respond with a 405 Method Not Allowed
	   status code for an HTTP request with a method
	   different than GET */
	m.Any("/resources/:id", skue.NotAllowed)
	
	http.ListenAndServe(":3020", m)
}

So far so good. Nothing different of what you would expect of any other REST server.

The Skuë layer

Here is the place you start using the helper functions. The most important functions you will be using are the persistance utils:

skue.Create
skue.Read
skue.Update
skue.Delete
skue.List

Through those functions you create the API by providing valid implementations of the interfaces defined by Skuë:

Consumer
Producer
DatabasePersistor
MemoryCacher

The interface implementations are passed as parameters to the persistance functions. How this layer looks like in your server code? Let's continue with the basic example:

// GET a resource by id
func getResourceHandler(params martini.Params, w http.ResponseWriter, r *http.Request) {
	id := params["id"]
	resource := models.NewResource(id)
	skue.Read(view, resource, cache, w, r)
}

In the above code resource represents an implementation of the skue.DatabasePersistor, view represents an implementation of skue.ViewLayer and cache represents an implementation of the skue.MemoryCacher interface.

The view layer

The view layer represents the implementation of two interfaces: skue.Consumer and skue.Producer. skue.Producer is intended to be an encoder that writes a value to http writers for a particular MIME type. skue.Consumer is intended to be a decoder of HTTP requests that uses a particular MIME type to decode the intended object into a value.

type ViewLayer struct {
	Producer Producer
	Consumer Consumer
}

type Producer interface {
	MimeType() string
	Out(w http.ResponseWriter, statusCode int, value interface{})
}

type Consumer interface {
	MimeType() string
	In(r *http.Request, value interface{}) error
}

Skuë provides two already implemented view layers: XmlView and JSONView.

To continue with the basic example, let's consume and produce JSON format in our API:

import (
	"github.com/greivinlopez/skue/views"
)

var (
	view   skue.ViewLayer
)

func init() {
	view = *views.NewJSONView()
}
The memory layer

skue.MemoryCacher represents an abstraction of any memory caching system used to speed up data driven systems by caching data in RAM instead of HD. That technique is called caching.

There are two important details about this layer:

  • It is a responsability of the skue.DatabasePersistor to interact properly with the skue.MemoryCacher to ensure it is actually used.
  • The use of this layer is completely optional.

Skuë provides an implementation of the skue.MemoryCacher for Redis.

For simplicity purposes we will remove the memory layer from our API server example:

// GET a resource by id
func getResourceHandler(params martini.Params, w http.ResponseWriter, r *http.Request) {
	id := params["id"]
	resource := models.NewResource(id)
	skue.Read(view, resource, nil, w, r)
}

If the skue.DatabasePersistor its properly implemented then sending nil instead of the skue.MemoryCacher should not broke anything.

The database layer

Credits

Icons

License

Documentation

Overview

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Index

Constants

View Source
const (
	MIME_XML  = "application/xml"
	MIME_JSON = "application/json"

	HEADER_Allow                         = "Allow"
	HEADER_Accept                        = "Accept"
	HEADER_Origin                        = "Origin"
	HEADER_ContentType                   = "Content-Type"
	HEADER_LastModified                  = "Last-Modified"
	HEADER_AcceptEncoding                = "Accept-Encoding"
	HEADER_ContentEncoding               = "Content-Encoding"
	HEADER_AccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HEADER_AccessControlRequestMethod    = "Access-Control-Request-Method"
	HEADER_AccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HEADER_AccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HEADER_AccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HEADER_AccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HEADER_AccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HEADER_XRateLimitLimit               = "X-Rate-Limit-Limit"
	HEADER_XRateLimitRemaining           = "X-Rate-Limit-Remaining"
)

Variables

View Source
var ErrNotFound = errors.New("not found")

Functions

func Consume

func Consume(consumer Consumer, w http.ResponseWriter, r *http.Request, value interface{}) error

func Create

func Create(view ViewLayer, model DatabasePersistor, w http.ResponseWriter, r *http.Request)

Saves a model to the underlying storage. Internally it calls the Create method of the given model. The model is constructed from the JSON body of the given request. Writes to the http writer according to what happens with the model following the REST architectural style.

func Delete

func Delete(view ViewLayer, model DatabasePersistor, cache MemoryCacher, w http.ResponseWriter, r *http.Request)

Deletes the model in the underlying storage. Internally it calls the Read method of the given model which assumes it knows it's id. If the model is created successfully then it calls the Delete method. Writes to the http writer according to what happens with the model following the REST architectural style.

func List

func List(view ViewLayer, model DatabasePersistor, w http.ResponseWriter, r *http.Request)

Returns the list of elements associated to the givem model in the underlying storage. Writes to the http writer accordingly following the REST architectural style.

func NotAllowed

func NotAllowed(producer Producer, w http.ResponseWriter, r *http.Request)

NotAllowed handler will response with a "405 Method Not Allowed" response It is a convenience handler to route all not allowed services

func NotFound

func NotFound(producer Producer, w http.ResponseWriter, r *http.Request)

NotFound handler will respond with a "404 Not Found" response

func Produce

func Produce(producer Producer, w http.ResponseWriter, r *http.Request, status int, value interface{})

func Read

func Read(view ViewLayer, model DatabasePersistor, cache MemoryCacher, w http.ResponseWriter, r *http.Request)

Reads the model from underlying storage. Internally it calls the Read method of the given model which assumes it knows it's id. Writes to the http writer according to what happens with the model following the REST architectural style.

func ServiceResponse

func ServiceResponse(producer Producer, w http.ResponseWriter, r *http.Request, httpStatus int, message string)

ServiceResponse is a convenience function to create an http response encoded as JSON with a simple message

func Update

func Update(view ViewLayer, model DatabasePersistor, cache MemoryCacher, w http.ResponseWriter, r *http.Request)

Updates the given model in the underlying storage Internally it calls the Update method of the given model. The model is constructed from the JSON body of the given request. Writes to the http writer according to what happens with the model following the REST architectural style.

Types

type Consumer

type Consumer interface {
	MimeType() string
	In(r *http.Request, value interface{}) error
}

Consumer is intended to be a decoder of HTTP requests that uses a particular MIME type to decode the intended object into a value.

type DatabasePersistor

type DatabasePersistor interface {
	Create() (err error)
	Read(cache MemoryCacher) (err error)
	Update(cache MemoryCacher) (err error)
	Delete(cache MemoryCacher) (err error)
	List() (result interface{}, err error)
}

DatabasePersistor represents any abstraction that can follow the CRUD operations. Create, Read, Update and Delete are the four basic operations of persistent storage.

type MemoryCacher

type MemoryCacher interface {
	Set(key interface{}, value interface{}) error
	Get(key interface{}, value interface{}) error
	Delete(key interface{}) error
}

MemoryCacher represents an abstraction of any memory caching system used to speed up data driven systems by caching data in RAM instead of HD. Memory caching system examples: - Memcached: http://www.memcached.org - Redis: http://redis.io/ More info here: Caching: http://en.wikipedia.org/wiki/Cache_(computing)

type Producer

type Producer interface {
	MimeType() string
	Out(w http.ResponseWriter, statusCode int, value interface{})
}

Producer is intended to be an encoder that writes a value to http writers for a particular MIME type.

type SimpleMessage

type SimpleMessage struct {
	Status  int
	Message string
}

SimpleMessage represents an HTTP simple response with an HTTP status code and a response message

type ViewLayer

type ViewLayer struct {
	Producer Producer
	Consumer Consumer
}

ViewLayer represents a consumer and a producer to decode and encode Http requests and responses in a certain MIME type

func NewViewLayer

func NewViewLayer(producer Producer, consumer Consumer) *ViewLayer

Directories

Path Synopsis
This work uses "Redigo" package by Gary Burd: https://github.com/garyburd/redigo -------------- Redigo License -------------- Copyright 2012 Gary Burd Licensed under the Apache License, Version 2.0 (the "License"): you may not use this file except in compliance with the License.
This work uses "Redigo" package by Gary Burd: https://github.com/garyburd/redigo -------------- Redigo License -------------- Copyright 2012 Gary Burd Licensed under the Apache License, Version 2.0 (the "License"): you may not use this file except in compliance with the License.
The MIT License (MIT) Copyright (c) 2014 Greivin López Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The MIT License (MIT) Copyright (c) 2014 Greivin López Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
examples
soccer
The MIT License (MIT) Copyright (c) 2014 Greivin López Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The MIT License (MIT) Copyright (c) 2014 Greivin López Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
soccer/database
The MIT License (MIT) Copyright (c) 2014 Greivin López Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The MIT License (MIT) Copyright (c) 2014 Greivin López Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Jump to

Keyboard shortcuts

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