dannyvankooten / respond

Go package for easily replying to HTTP requests with common response types.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Respond GoDoc Build Status Go Report Card Coverage

Go package for easily responding to HTTP requests with common response types, setting the appropriate Content-Type and Status headers as needed.

  • HTML
  • Template (using html/template)
  • Text
  • JSON (using encoding/json)
  • XML (using encoding/xml)

Usage

Respond can be used with pretty much any web framework. As long as you have access to a http.ResponseWriter, you are good to go.

import "github.com/dannyvankooten/respond"
// this sets Content-Type (incl. charset) and Status header before writing the response body.
func myHandler(w http.ResponseWriter, r *http.Request) {
   respond.HTML(w, http.StatusOK, []byte("Hello world!"))
}

// if you just want to set the Content-Type and Status header, omit the last parameter
func myHandler(w http.ResponseWriter, r *http.Request) {
   respond.HTML(w, http.StatusOK)
}

// html/template.*Template
func myHandler(w http.ResponseWriter, r *http.Request) {
	tmpl := template.Must(template.New("").Parse("Hello {{.}}"))
	respond.Template(w, http.StatusOK, tmpl, "world")
}

// JSON
func myHandler(w http.ResponseWriter, r *http.Request) {
   respond.JSON(w, http.StatusOK, map[string]string{"foo": "bar"})
}

// Text
func myHandler(w http.ResponseWriter, r *http.Request) {
   respond.Text(w, http.StatusOK, []byte("Hello world!"))
}

// XML
func myHandler(w http.ResponseWriter, r *http.Request) {
   respond.XML(w, http.StatusOK, map[string]string{"foo": "bar"})
}

// XML with struct
func myHandler(w http.ResponseWriter, r *http.Request) {
   respond.XML(w, http.StatusOK, &myType{ Name: "John Doe" })
}

Respond defaults to UTF-8 as its charset. To override it, set the package global named Charset.

respond.Charset = "UTF-16"

License

MIT licensed.

About

Go package for easily replying to HTTP requests with common response types.

License:MIT License


Languages

Language:Go 100.0%