From 6ad39dad61ae0fccb83103edfbd4cc0469c0d6e1 Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Wed, 9 Dec 2015 13:47:11 +0200 Subject: [PATCH] Added SendFile to Response --- http.go | 25 +++++++++++++++++++++++++ server.go | 17 +---------------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/http.go b/http.go index b6be4cb..fa4b7c7 100644 --- a/http.go +++ b/http.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "mime/multipart" + "os" "sync" ) @@ -98,6 +99,30 @@ func (req *Request) SetConnectionClose() { req.Header.SetConnectionClose() } +// SendFile registers file on the given path to be used as response body +// when Write is called. +// +// Note that SendFile doesn't set Content-Type, so set it yourself +// with Header.SetContentType. +func (resp *Response) SendFile(path string) error { + f, err := os.Open(path) + if err != nil { + return err + } + statInfo, err := f.Stat() + if err != nil { + f.Close() + return err + } + size64 := statInfo.Size() + size := int(size64) + if int64(size) != size64 { + size = -1 + } + resp.SetBodyStream(f, size) + return nil +} + // SetBodyStream sets response body stream and, optionally body size. // // If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes diff --git a/server.go b/server.go index 2185a77..2552a80 100644 --- a/server.go +++ b/server.go @@ -659,22 +659,7 @@ func (ctx *RequestCtx) ResetBody() { // so set it yourself with SetContentType() before returning // from RequestHandler. func (ctx *RequestCtx) SendFile(path string) error { - f, err := os.Open(path) - if err != nil { - return err - } - statInfo, err := f.Stat() - if err != nil { - f.Close() - return err - } - size64 := statInfo.Size() - size := int(size64) - if int64(size) != size64 { - size = -1 - } - ctx.SetBodyStream(f, size) - return nil + return ctx.Response.SendFile(path) } // Write writes p into response body.