Skip to content

Commit ec18f83

Browse files
committed
Merge pull request #39 from gavv/text_renderer
Add Text() method for writing plain text responses
2 parents b650633 + eb65b1f commit ec18f83

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,11 @@ func main() {
148148
r.XML(200, Greeting{One: "hello", Two: "world"})
149149
})
150150

151+
// This will set the Content-Type header to "text/plain; charset=UTF-8"
152+
m.Get("/text", func(r render.Render) {
153+
r.Text(200, "hello, world")
154+
})
155+
151156
m.Run()
152157
}
153158

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

200+
// This will set the Content-Type header to "text/plain; charset=ISO-8859-1"
201+
m.Get("/text", func(r render.Render) {
202+
r.Text(200, "hello, world")
203+
})
204+
195205
m.Run()
196206
}
197207

render.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ const (
5757
ContentType = "Content-Type"
5858
ContentLength = "Content-Length"
5959
ContentBinary = "application/octet-stream"
60+
ContentText = "text/plain"
6061
ContentJSON = "application/json"
6162
ContentHTML = "text/html"
6263
ContentXHTML = "application/xhtml+xml"
@@ -88,6 +89,8 @@ type Render interface {
8889
XML(status int, v interface{})
8990
// Data writes the raw byte array to the http.ResponseWriter.
9091
Data(status int, v []byte)
92+
// Text writes the given status and plain text to the http.ResponseWriter.
93+
Text(status int, v string)
9194
// Error is a convenience function that writes an http status to the http.ResponseWriter.
9295
Error(status int)
9396
// Status is an alias for Error (writes an http status to the http.ResponseWriter)
@@ -323,6 +326,14 @@ func (r *renderer) Data(status int, v []byte) {
323326
r.Write(v)
324327
}
325328

329+
func (r *renderer) Text(status int, v string) {
330+
if r.Header().Get(ContentType) == "" {
331+
r.Header().Set(ContentType, ContentText+r.compiledCharset)
332+
}
333+
r.WriteHeader(status)
334+
r.Write([]byte(v))
335+
}
336+
326337
// Error writes the given HTTP status to the current ResponseWriter
327338
func (r *renderer) Error(status int) {
328339
r.WriteHeader(status)

0 commit comments

Comments
 (0)