srest

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 15, 2018 License: MIT Imports: 19 Imported by: 0

README

RESTful toolkit.

License MIT Build Status Go Report Card GoDoc Coverage Status

Srest goal it's help you build sites and clear RESTful services without enslave you to complicated frameworks rules. It's a thin layer over other useful toolkits:

bmizerany/pat

gorilla/schema

Features:

  • Endpoint declaration and validation with middleware support.
  • Payload validation.
  • Templates made easy.
  • Simple.

Install:

go get gopkg.in/jimmy-go/srest.v0

Usage:

Simplest example:
// Declare a new srest without TLS configuration. View srest.Options for TLS config.
m := srest.New(nil)

// Declare an endpoint.
m.Get("/hello", func(w http.ResponseWriter, r *http.Request) {})

// Run calls http.ListenAndServe or ListenAndServeTLS
// until SIGTERM or SIGINT signal is received.
<-m.Run(9000)
With middleware:
m := srest.New(nil)
m.Get("/hello", helloHandler, Mid1, Mid2, Mid3)

// Another more legible way to pass middleware:
c := []func(http.Handler) http.Handler{
    Mid1,
    Mid2,
    Mid3,
}
m.Get("/hello/2", someHandler, c...)
m.Get("/hello/3", someHandler, c...)
<-m.Run(9000)
With REST interface:
m := srest.New(nil)
// FriendController implements srest.RESTfuler and generates endpoints for:
// GET     /v1/api/friends
// GET     /v1/api/friends/:id
// POST    /v1/api/friends
// PUT     /v1/api/friends/:id
// DELETE  /v1/api/friends/:id
m.Use("/v1/api/friends", &FriendController{}, Mid1, Mid2, Mid3)
<-m.Run(9000)
With html templates:

Load Go html templates.

// Load templates
err := srest.LoadViews("mytemplatesdir", srest.DefaultFuncMap)
// ...check errors

m := srest.New(nil)
m.Get("/", http.HandlerFunc(homeHandler))
<-m.Run(9000)

mytemplatesdir files:

├── mytemplatesdir
│   └── home.html

Using the home.html template.

func homeHandler(w http.ResponseWriter, r *http.Request) {

    // Call Render func passing variables inside v.
    v := map[string]interface{}{
        "somevar": "A",
    }
    err := srest.Render(w, "home.html", v)
    // ...check errors
}

Payload validation:

func Endpoint(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()

    var p Params
    // Bind binds url.Values to struct using gorilla schema
    err := srest.Bind(r.Form, &p)
    // ...check errors
}
type Modeler interface {
	IsValid() error
}
// Params implements srest.Modeler interface.
type Params struct{
    Name        string `schema:"name"`
    LastName    string `schema:"last_name"`
}

// IsValid implements srest.Modeler interface.
func(m *Params) IsValid() error {
    if m.Name == "" {
        return errors.New("model: name is required")
    }
    return nil
}

Take a look at the working example with all features on examples dir.

NOTES:

  • Prevents errors with endpoint declaration order.
m := srest.New(nil)
m.Get("/hello", helloHandler)
m.Get("/hello/:id/friends", helloHandler) // Won't overwrite next endpoint.
m.Get("/hello/:id", helloHandler)
  • Duplicated endpoints would panic at init time.
m := srest.New(nil)
m.Get("/hello", helloHandler)
m.Get("/hello", helloHandler) // Would panic.
m.Get("/hello/:a/name", helloHandler)
m.Get("/hello/:b/name", helloHandler) // Would panic.
<-m.Run(9000)

License:

The MIT License (MIT)

Copyright (c) 2016 Angel del Castillo

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.

Documentation

Overview

Package srest contains tools for REST services and web sites.

Copyright 2016 The SREST Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultFuncMap can be used with LoadViews for common template tasks like:
	//	cap: capitalize strings
	//	eqs: compare value of two types.
	DefaultFuncMap = deffuncmap()
)
View Source
var (

	// ErrImplementsModeler error returned when modeler interface is not implemented.
	ErrImplementsModeler = errors.New("srest: modeler interface not found")
)
View Source
var (
	// ErrTemplateNotFound error returned when template is not found.
	ErrTemplateNotFound = errors.New("srest: template not found")
)

Functions

func Bind

func Bind(vars url.Values, dst interface{}) error

Bind implements gorilla schema and runs IsValid method from data.

func Debug

func Debug(ok bool)

Debug enables template files reload on every request.

func JSON

func JSON(w http.ResponseWriter, v interface{}) error

JSON writes v to response writer.

func LoadViews

func LoadViews(dirs string, funcMap template.FuncMap) error

LoadViews parses html files on dir as templates.

func Render

func Render(w http.ResponseWriter, name string, v interface{}) error

Render writes a template to w. In order to render templates you need to call Render function passing <file.html> or <subdir>/<file.html> as name.

func Static

func Static(uri, dir string) http.Handler

Static handler for static files.

Usage: Get("/public", Static("/public", "mydir"))

Types

type ByURIDesc added in v0.2.0

type ByURIDesc []tmpHandler

ByURIDesc implements sort.Interface for []tmpHandler based on the URI field.

func (ByURIDesc) Len added in v0.2.0

func (a ByURIDesc) Len() int

func (ByURIDesc) Less added in v0.2.0

func (a ByURIDesc) Less(i, j int) bool

func (ByURIDesc) Swap added in v0.2.0

func (a ByURIDesc) Swap(i, j int)

type Modeler

type Modeler interface {
	IsValid() error
}

Modeler interface

type Options

type Options struct {
	UseTLS  bool
	TLSCert string
	TLSKey  string
}

Options type.

type RESTfuler

type RESTfuler interface {
	Create(w http.ResponseWriter, r *http.Request)
	One(w http.ResponseWriter, r *http.Request)
	List(w http.ResponseWriter, r *http.Request)
	Update(w http.ResponseWriter, r *http.Request)
	Delete(w http.ResponseWriter, r *http.Request)
}

RESTfuler interface.

type SREST

type SREST struct {
	Mux     *mux.Router
	Options *Options
	Map     map[string]bool
	// contains filtered or unexported fields
}

SREST type.

func New

func New(options *Options) *SREST

New returns a new server.

func (*SREST) Del

func (m *SREST) Del(uri string, hf http.Handler, mws ...func(http.Handler) http.Handler)

Del wrapper register a DELETE endpoint with optional middlewares.

func (*SREST) Get

func (m *SREST) Get(uri string, hf http.Handler, mws ...func(http.Handler) http.Handler)

Get wrapper register a GET endpoint with optional middlewares. It will generate endpoints for `uri` and `uri/` because some pat unexpected behaviour.

func (*SREST) Post

func (m *SREST) Post(uri string, hf http.Handler, mws ...func(http.Handler) http.Handler)

Post wrapper register a POST endpoint with optional middlewares.

func (*SREST) Put

func (m *SREST) Put(uri string, hf http.Handler, mws ...func(http.Handler) http.Handler)

Put wrapper register a PUT endpoint with optional middlewares.

func (*SREST) Run

func (m *SREST) Run(port int) chan os.Signal

Run starts the server with http.ListenAndServe or http.ListenAndServeTLS returns a channel binded it to SIGTERM and SIGINT signal.

func (*SREST) Use

func (m *SREST) Use(uri string, n RESTfuler, mws ...func(http.Handler) http.Handler)

Use receives a RESTfuler interface and generates endpoints for: One : GET path/:id List : GET path/ Create : POST path/ Update : PUT path/:id Remove : DELETE path/:id

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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