retencoder

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

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

Go to latest
Published: Mar 9, 2014 License: MIT Imports: 8 Imported by: 0

README

retencoder

Allows you to return values from your handlers and have it encoded based on the Accept header. Supports JSON, XML, and fmt.Stringer.

I made this to answer a question on the martini googlegroups.

Usage
m.Map(retencoder.ReturnHandler())
Example
package main

import (
	"encoding/xml"
	"log"
	"net/http"

	"github.com/codegangsta/martini"
	"github.com/kdar/martini-retencoder"
)

type Some struct {
	XMLName  xml.Name `json:"-" xml:"response"`
	Login    string   `json:"login" xml:"login"`
	Password string   `json:"password" xml:"password"`
}

func (s *Some) String() string {
	return "Login: " + s.Login + ", Password: " + s.Password
}

func main() {
	m := martini.New()
	route := martini.NewRouter()

	m.Map(retencoder.ReturnHandler())

	route.Get("/test", func() (int, interface{}) {
		result := &Some{Login: "awesome", Password: "hidden"}
		return http.StatusOK, result
	})

	m.Action(route.Handle)

	log.Println("Waiting for connections...")

	if err := http.ListenAndServe(":8000", m); err != nil {
		log.Fatal(err)
	}
}

Results
curl http://localhost:8000/test -H "Accept: application/json"
{"login":"awesome","password":"hidden"}

curl http://localhost:8000/test -H "Accept: application/text"
Login: awesome, Password: hidden

curl http://localhost:8000/test -H "Accept: application/xml"
<response><login>awesome</login><password>hidden</password></response>

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReturnHandler

func ReturnHandler() martini.ReturnHandler

ReturnHandler is a service that is called when a route handler returns something. The ReturnHandler is responsible for writing to the ResponseWriter based on the values that are passed into this function.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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