satellite: adding proper headers to api responses (#3489)

This commit is contained in:
Nikolai Siedov 2019-11-12 15:05:35 +02:00 committed by GitHub
parent b2d2377d2e
commit 70c7ee842e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 27 deletions

View File

@ -68,6 +68,7 @@ func (a *Auth) Token(w http.ResponseWriter, r *http.Request) {
return return
} }
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(token) err = json.NewEncoder(w).Encode(token)
if err != nil { if err != nil {
a.log.Error("token handler could not encode token response", zap.Error(ErrAuthAPI.Wrap(err))) a.log.Error("token handler could not encode token response", zap.Error(ErrAuthAPI.Wrap(err)))
@ -139,9 +140,10 @@ func (a *Auth) Register(w http.ResponseWriter, r *http.Request) {
}, },
) )
err = json.NewEncoder(w).Encode(&user.ID) w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(user.ID)
if err != nil { if err != nil {
a.log.Error("registration handler could not encode error", zap.Error(ErrAuthAPI.Wrap(err))) a.log.Error("registration handler could not encode userID", zap.Error(ErrAuthAPI.Wrap(err)))
return return
} }
} }
@ -194,6 +196,7 @@ func (a *Auth) GetAccount(w http.ResponseWriter, r *http.Request) {
user.ID = auth.User.ID user.ID = auth.User.ID
user.PartnerID = auth.User.PartnerID user.PartnerID = auth.User.PartnerID
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(&user) err = json.NewEncoder(w).Encode(&user)
if err != nil { if err != nil {
a.log.Error("could not encode user info", zap.Error(ErrAuthAPI.Wrap(err))) a.log.Error("could not encode user info", zap.Error(ErrAuthAPI.Wrap(err)))

View File

@ -72,7 +72,8 @@ func (p *Payments) AccountBalance(w http.ResponseWriter, r *http.Request) {
return return
} }
err = json.NewEncoder(w).Encode(balance) w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(&balance)
if err != nil { if err != nil {
p.log.Error("failed to write json balance response", zap.Error(ErrPaymentsAPI.Wrap(err))) p.log.Error("failed to write json balance response", zap.Error(ErrPaymentsAPI.Wrap(err)))
} }
@ -121,6 +122,7 @@ func (p *Payments) ListCreditCards(w http.ResponseWriter, r *http.Request) {
return return
} }
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(cards) err = json.NewEncoder(w).Encode(cards)
if err != nil { if err != nil {
p.log.Error("failed to write json list cards response", zap.Error(ErrPaymentsAPI.Wrap(err))) p.log.Error("failed to write json list cards response", zap.Error(ErrPaymentsAPI.Wrap(err)))
@ -194,6 +196,7 @@ func (p *Payments) BillingHistory(w http.ResponseWriter, r *http.Request) {
return return
} }
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(billingHistory) err = json.NewEncoder(w).Encode(billingHistory)
if err != nil { if err != nil {
p.log.Error("failed to write json billing history response", zap.Error(ErrPaymentsAPI.Wrap(err))) p.log.Error("failed to write json billing history response", zap.Error(ErrPaymentsAPI.Wrap(err)))

View File

@ -11,6 +11,7 @@ import (
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"os"
"path" "path"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -150,7 +151,7 @@ func NewServer(logger *zap.Logger, config Config, service *console.Service, mail
router.HandleFunc("/password-recovery/", server.passwordRecoveryHandler) router.HandleFunc("/password-recovery/", server.passwordRecoveryHandler)
router.HandleFunc("/cancel-password-recovery/", server.cancelPasswordRecoveryHandler) router.HandleFunc("/cancel-password-recovery/", server.cancelPasswordRecoveryHandler)
router.HandleFunc("/usage-report/", server.bucketUsageReportHandler) router.HandleFunc("/usage-report/", server.bucketUsageReportHandler)
router.PathPrefix("/static/").Handler(server.gzipHandler(http.StripPrefix("/static", fs))) router.PathPrefix("/static/").Handler(server.gzipMiddleware(http.StripPrefix("/static", fs)))
router.PathPrefix("/").Handler(http.HandlerFunc(server.appHandler)) router.PathPrefix("/").Handler(http.HandlerFunc(server.appHandler))
} }
@ -520,37 +521,28 @@ func (server *Server) seoHandler(w http.ResponseWriter, req *http.Request) {
} }
} }
// gzipHandler is used to gzip static content to minify resources if browser support such decoding // gzipMiddleware is used to gzip static content to minify resources if browser support such decoding.
func (server *Server) gzipHandler(fn http.Handler) http.Handler { func (server *Server) gzipMiddleware(fn http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
isGzipSupported := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") w.Header().Set("Cache-Control", "public, max-age=31536000")
extension := filepath.Ext(r.RequestURI)
// we have gzipped only fonts, js and css bundles
formats := map[string]bool{
".js": true,
".ttf": true,
".css": true,
}
isNeededFormatToGzip := formats[extension]
// because we have some static content outside of console frontend app.
// for example: 404 page, account activation, password reset, etc.
// TODO: find better solution, its a temporary fix
isFromStaticDir := strings.Contains(r.URL.Path, "/static/dist/")
w.Header().Set(contentType, mime.TypeByExtension(extension))
w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Content-Type-Options", "nosniff")
// in case if old browser doesn't support gzip decoding or if file extension is not recommended to gzip isGzipSupported := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
// just return original file if !isGzipSupported {
if !isGzipSupported || !isNeededFormatToGzip || !isFromStaticDir {
fn.ServeHTTP(w, r) fn.ServeHTTP(w, r)
return return
} }
info, err := os.Stat(server.config.StaticDir + strings.TrimPrefix(r.URL.Path, "/static") + ".gz")
if err != nil {
fn.ServeHTTP(w, r)
return
}
extension := filepath.Ext(info.Name()[:len(info.Name())-3])
w.Header().Set(contentType, mime.TypeByExtension(extension))
w.Header().Set("Content-Encoding", "gzip") w.Header().Set("Content-Encoding", "gzip")
// updating request URL
newRequest := new(http.Request) newRequest := new(http.Request)
*newRequest = *r *newRequest = *r
newRequest.URL = new(url.URL) newRequest.URL = new(url.URL)
@ -561,7 +553,7 @@ func (server *Server) gzipHandler(fn http.Handler) http.Handler {
}) })
} }
// satelliteNameHandler retrieve satellites name. // satelliteNameHandler retrieves satellite name.
func (server *Server) satelliteNameHandler(w http.ResponseWriter, r *http.Request) { func (server *Server) satelliteNameHandler(w http.ResponseWriter, r *http.Request) {
var response struct { var response struct {
SatelliteName string `json:"satelliteName"` SatelliteName string `json:"satelliteName"`