From b2289ba10bbb09297cf0aa89db40ef581e05ab4d Mon Sep 17 00:00:00 2001 From: Pavel Korotkov Date: Wed, 22 Jul 2020 18:05:18 +0300 Subject: [PATCH] Add a separate package to encapsulate http related stuff --- http/http.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 http/http.go diff --git a/http/http.go b/http/http.go new file mode 100644 index 00000000..9d1b3a7a --- /dev/null +++ b/http/http.go @@ -0,0 +1,58 @@ +package http + +import ( + "fmt" + "net/http" + "strconv" + + "github.com/minio/minio/legacy/crypto" +) + +type ( + HTTPResponseWriter struct { + serverName string + serverRegion string + } + + // MimeType represents various MIME type used API responses. + MimeType string + + // ContextKey is a custom type used to pass values within contexts. + ContextKey string +) + +const BearerTokenContextKey ContextKey = "bearer-token" + +const ( + // MimeType_None means no response type. + MimeType_None MimeType = "" + // MimeType_ApplicationJSON means response type is JSON. + MimeType_ApplicationJSON MimeType = "application/json" + // MimeType_ApplicationXML means response type is XML. + MimeType_ApplicationXML MimeType = "application/xml" +) + +func NewHTTPResponseWriter(appName, appVersion, region string) *HTTPResponseWriter { + return &HTTPResponseWriter{ + serverName: fmt.Sprintf("%s/%s", appName, appVersion), + serverRegion: region, + } +} + +func (rw *HTTPResponseWriter) writeResponse(w http.ResponseWriter, statusCode int, response []byte, mimeType MimeType) { + w.Header().Set("Server", rw.serverName) + if len(rw.serverRegion) > 0 { + w.Header().Set("X-Amz-Bucket-Region", rw.serverRegion) + } + w.Header().Set("Accept-Ranges", "bytes") + crypto.RemoveSensitiveHeaders(w.Header()) + if mimeType != MimeType_None { + w.Header().Set("Content-Type", string(mimeType)) + } + w.Header().Set("Content-Length", strconv.Itoa(len(response))) + w.WriteHeader(statusCode) + if response != nil { + w.Write(response) + w.(http.Flusher).Flush() + } +}