Skip to content
This repository has been archived by the owner on Sep 30, 2022. It is now read-only.
/ respond Public archive

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

License

Notifications You must be signed in to change notification settings

dannyvankooten/respond

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages