http

package module
v0.0.0-...-389047e Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2014 License: MIT Imports: 13 Imported by: 1

README

Http

Override of net/http and gorilla/pat golang library to use JSON with Request and ResponseWritter in a more easy way.

Its purpose is to create API service sending and receiving JSON data.

On each Route, we can attach interceptors (which are simple HandlerFunc) to be called before, after or when an error is returned by the handler.

See documentation of gorilla/pat here : http://www.gorillatoolkit.org/pkg/pat


Full Example


import (
	"github.com/pikanezi/http"
	"io"
	"log"
)

const (
	errorWrongObject = iota << 2
)

type Object struct {
	SomeField string `json:"someField,omitempty"`
}

func HelloWorldHandler(w http.ResponseWriter, r *http.Request) *http.Error {
	object := &Object{"Hello World"}
	w.WriteJSON(object)
	return nil
}

func AdminHandler(w http.ResponseWriter, r *http.Request) *http.Error {
	w.WriteJSON("Hello Admin!")
	return nil
}

func CheckAdminInterceptor(w http.ResponseWriter, r *http.Request) *http.Error {
	// Check if user is an Admin
	return nil
}


func AddObjectHandler(w http.ResponseWriter, r *http.Request) *http.Error {
	object := &Object{}
	if err := r.GetJSONObject(&object); err != nil {
		return http.NewError(err, 500)
	}
	// handle object
	return nil
}

// GetFileReader works only for single file reader.
func GetFileHandler(w http.ResponseWriter, r *http.Request) *http.Error {
	reader, err := r.GetFileReader("file")
	// Handle file Reader
	return nil
}

func MultiFileHandler(w http.ResponseWriter, r *http.Request) *http.Error {
	if err := r.ForEachFile("files", func (index int, reader io.Reader) {
		// Do something with each file Reader
	}); err != nil {
		return http.NewError(err, 500)
	}
	return nil
}

func main() {
	r := http.NewRouter()
    
	// Set the custom headers to be set before the Handler handle the request.
	// It is useful for handling the CORS.
	r.SetCustomHeader(http.Header{
		"Access-Control-Allow-Origin":      domainCORS,
		"Access-Control-Allow-Methods":     "POST, GET, OPTIONS, PUT, DELETE",
		"Access-Control-Allow-Headers":     "Content-Type, Authorization, Accept, x-api-key",
		"Access-Control-Allow-Max-Age":     "604800",
		"Access-Control-Allow-Credentials": "true",
	})
	
	r.Get("/hello/world", HelloWorldHandler).Before(CheckAdminInterceptor)
	r.Post("/object", AddObjectHandler)
    r.Post("/file", GetFileHandler)
    r.Post("/files", MultiFileHandler)
    
	log.Fatal(http.ListenAndServe(":8080", r)
}

License

The MIT License (MIT)

Copyright (c) 2014 Vincent Nëel

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 http overrides net/http and gorilla/pat golang library to use JSON with Request and ResponseWriter in a more easy way.

Its purpose is to create web server sending and receiving JSON data in few lines.

Full Example

	import (
    	"github.com/pikanezi/http"
    	"log"
	)

	type Object struct {
    	SomeField string `json:"someField,omitempty"`
	}

	func HelloWorldHandler(w http.ResponseWriter, r *http.Request) *http.Error {
    	object := &Object{"Hello World"}
    	if err := w.WriteJSON(object); err != nil {
        	return &http.Error{Error: err.Error()
    	}
	}

	func main() {

    	// NewRouter takes the domain to authorize it cross-domains requests
    	r := http.NewRouter()

    	r.Get("/hello/world", HelloWorldHandler)

    	log.Fatal(http.ListenAndServe(":8080", r)
	}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handle

func Handle(route string, handler http.Handler)

Handle registers the handler for the given pattern in the golang http DefaultServeMux. This should be avoided, use ListenAndServe instead.

func ListenAndServe

func ListenAndServe(addr string, handler http.Handler) error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Handler is typically the Router itself.

func Redirect

func Redirect(w ResponseWriter, r *Request, urlStr string, code int)

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

func SetDebug

func SetDebug(debug bool)

SetDebug set the debug at true so it prints some debug.

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

Types

type Error

type Error struct {
	Error      string `json:"error,omitempty"`
	HTTPCode   int    `json:"httpCode,omitempty"`
	StatusCode int    `json:"statusCode,omitempty"`
}

Error is a type that must be used when returning from the Handlers.

func NewError

func NewError(err error, httpCode int) *Error

NewError returns a new Error.

func NewErrorAPI

func NewErrorAPI(err error, statusCode, httpCode int) *Error

NewErrorAPI returns a new Error with a statusCode.

type HandlerFunc

type HandlerFunc func(ResponseWriter, *Request) *Error

HandlerFunc must returns an Error that will be handled by the Router itself. See implementation of the ServeHTTP method of the Router.

type Header map[string]string

Header represents custom header to be set to the response before .

func (Header) Add

func (h Header) Add(key, value string)

Add add a key-value pair to the header.

type Request

type Request struct {
	*http.Request
}

Request represents an HTTP request received by a server or to be sent by a client.

func CreateRequest

func CreateRequest(r *http.Request) *Request

CreateRequest a new Request from a classic Request.

func NewRequest

func NewRequest(method, url string, body io.Reader) (*Request, error)

NewRequest returns a new Request given a method, URL, and optional body.

func (*Request) ForEachFileHeader

func (req *Request) ForEachFileHeader(key string, f func(int, *multipart.FileHeader) error) error

ForEachFileHeader calls the function f with every multipart.FileHeader contained in the provided form key. Opening and closing the file is the responsibility of the user.

func (*Request) ForEachFileReader

func (req *Request) ForEachFileReader(key string, f func(int, io.Reader) error) error

ForEachFileReader calls the function f with every io.Reader contained in the provided form key. After every call to f, the file is close.

func (*Request) GetAndReturnJSONObject

func (req *Request) GetAndReturnJSONObject(object interface{}) (interface{}, error)

GetAndReturnJSONObject returns the JSON object from the body.

func (*Request) GetFileReader

func (req *Request) GetFileReader(key string) (io.Reader, error)

GetFileReader get the multiform body and returns it as a Reader.

func (*Request) GetJSONObject

func (req *Request) GetJSONObject(object interface{}) error

GetJSONObject just call json.Unmarshal to the body and put it in the object.

func (*Request) GetXMLObject

func (req *Request) GetXMLObject(object interface{}) error

GetXMLObject jus call xml.Unmarshal to the body and put it in the object.

func (*Request) URLParam

func (req *Request) URLParam(key string) string

URLParam returns an URL param. It is the same as calling request.Url.Query().Get(":key").

type Response

type Response struct {
	*http.Response
}

Response represents the response from an HTTP request.

func Get

func Get(url string) (*Response, error)

Get issues a GET request to the given URL and returns the Response.

func PostForm

func PostForm(url string, data url.Values) (*Response, error)

PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.

func PostJSON

func PostJSON(url string, object interface{}) (*Response, error)

PostJSON issues a POST request of type "application/json" (the object will be marshaled as JSON) to the given URL.

func (*Response) GetAndReturnJSONObject

func (resp *Response) GetAndReturnJSONObject(object interface{}) (interface{}, error)

GetAndReturnJSONObject returns an the JSON object from the body.

func (*Response) GetJSONObject

func (resp *Response) GetJSONObject(object interface{}) error

GetJSONObject just call json.Unmarshal to the body and put it in the object.

func (*Response) GetXMLObject

func (resp *Response) GetXMLObject(object interface{}) error

GetXMLObject jus call xml.Unmarshal to the body and put it in the object.

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter
	http.Hijacker
}

A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.

func CreateResponseWriter

func CreateResponseWriter(r http.ResponseWriter) ResponseWriter

CreateResponseWriter create a new ResponseWriter from a classic ResponseWriter.

func (ResponseWriter) WriteError

func (rw ResponseWriter) WriteError(customErr *Error) error

WriteError send an error using http.Error.

func (ResponseWriter) WriteJSON

func (rw ResponseWriter) WriteJSON(object interface{}) error

WriteJSON marshal the Object and write it.

func (ResponseWriter) WriteSingleStringJSON

func (rw ResponseWriter) WriteSingleStringJSON(key, value string)

WriteSingleStringJSON marshal a single key / value JSON and write it.

type RouteHandler

type RouteHandler struct {
	Route *mux.Route
	// contains filtered or unexported fields
}

RouteHandler contains the main Handler and the given mux.Route. When an interceptor has been given, it fires them. If an Error occurs in a Before interceptor, it stops any further interceptor and writes the Error to the client. If an Error occurs in the Handler, it fires the OnError interceptors and the After interceptors. Any Error occurring in a OnError or After interceptor is ignored.

func (*RouteHandler) After

func (h *RouteHandler) After(handlers ...HandlerFunc) *RouteHandler

After add interceptors that must be run after the Request has been handled.

func (*RouteHandler) Before

func (h *RouteHandler) Before(handlers ...HandlerFunc) *RouteHandler

Before add interceptors that must be run before the Request has been handled.

func (*RouteHandler) OnError

func (h *RouteHandler) OnError(handlers ...HandlerFunc) *RouteHandler

OnError add interceptors that must be run when an Error occurs.

type Router

type Router struct {
	*pat.Router
	// contains filtered or unexported fields
}

Router embeds pat.Router. Router is a request router that implements a pat-like API. pat docs: http://godoc.org/github.com/bmizerany/pat

func NewRouter

func NewRouter() *Router

NewRouter returns a new router with the given domain.

Example
router := NewRouter()

router.Get("/", func(w ResponseWriter, r *Request) *Error {
	w.WriteJSON("Hello!")
	return nil
})

router.Get("/admin", func(w ResponseWriter, r *Request) *Error {
	// do stuff
	return nil
}).Before(func(w ResponseWriter, r *Request) *Error {
	// check if user is an admin
	return nil
})

router.Post("/upload", func(w ResponseWriter, r *Request) *Error {
	if err := r.ForEachFile("file", func(index int, reader io.Reader) error {
		// Do something with the reader
		return nil
	}); err != nil {
		return NewError(err, 400)
	}
	return nil
})
ListenAndServe(":8080", router)

func (*Router) CustomHeader

func (router *Router) CustomHeader() Header

CustomHeader returns the customHeaders of the router.

func (*Router) Delete

func (router *Router) Delete(route string, h HandlerFunc) *RouteHandler

Delete registers a pattern with a handler for DELETE requests.

func (*Router) Get

func (router *Router) Get(route string, h HandlerFunc) *RouteHandler

Get registers a pattern with a handler for GET requests.

func (*Router) Post

func (router *Router) Post(route string, h HandlerFunc) *RouteHandler

Post registers a pattern with a handler for POST requests.

func (*Router) Put

func (router *Router) Put(route string, h HandlerFunc) *RouteHandler

Put registers a pattern with a handler for PUT requests.

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the handler registered in the matched route. It performs any hooks and add the domain registered in the Router to be allowed for cross-domain requests.

func (*Router) SetCustomHeader

func (router *Router) SetCustomHeader(customHeader Header)

SetCustomHeader set the customHeader of the router.

Jump to

Keyboard shortcuts

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