Skip to content

Commit

Permalink
Merge pull request martini-contrib#39 from gavv/text_renderer
Browse files Browse the repository at this point in the history
Add Text() method for writing plain text responses
  • Loading branch information
unrolled committed Jul 7, 2015
2 parents b650633 + eb65b1f commit ec18f83
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ func main() {
r.XML(200, Greeting{One: "hello", Two: "world"})
})

// This will set the Content-Type header to "text/plain; charset=UTF-8"
m.Get("/text", func(r render.Render) {
r.Text(200, "hello, world")
})

m.Run()
}

Expand Down Expand Up @@ -192,6 +197,11 @@ func main() {
r.XML(200, Greeting{One: "hello", Two: "world"})
})

// This will set the Content-Type header to "text/plain; charset=ISO-8859-1"
m.Get("/text", func(r render.Render) {
r.Text(200, "hello, world")
})

m.Run()
}

Expand Down
11 changes: 11 additions & 0 deletions render.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const (
ContentType = "Content-Type"
ContentLength = "Content-Length"
ContentBinary = "application/octet-stream"
ContentText = "text/plain"
ContentJSON = "application/json"
ContentHTML = "text/html"
ContentXHTML = "application/xhtml+xml"
Expand Down Expand Up @@ -88,6 +89,8 @@ type Render interface {
XML(status int, v interface{})
// Data writes the raw byte array to the http.ResponseWriter.
Data(status int, v []byte)
// Text writes the given status and plain text to the http.ResponseWriter.
Text(status int, v string)
// Error is a convenience function that writes an http status to the http.ResponseWriter.
Error(status int)
// Status is an alias for Error (writes an http status to the http.ResponseWriter)
Expand Down Expand Up @@ -323,6 +326,14 @@ func (r *renderer) Data(status int, v []byte) {
r.Write(v)
}

func (r *renderer) Text(status int, v string) {
if r.Header().Get(ContentType) == "" {
r.Header().Set(ContentType, ContentText+r.compiledCharset)
}
r.WriteHeader(status)
r.Write([]byte(v))
}

// Error writes the given HTTP status to the current ResponseWriter
func (r *renderer) Error(status int) {
r.WriteHeader(status)
Expand Down

0 comments on commit ec18f83

Please sign in to comment.