github.com/grafviktor/keep-my-secret@v0.9.10-0.20230908165355-19f35cce90e5/internal/api/web/middleware/cors.go (about)

     1  package middleware
     2  
     3  import (
     4  	"net/http"
     5  )
     6  
     7  // EnableCORS - middleware to support CORS requests. Used for development only.
     8  func (m *middleware) EnableCORS(next http.Handler) http.Handler {
     9  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    10  		// TODO: This "if" statement should be moved to router level.
    11  		if m.config.DevMode {
    12  			// That was set for my dev environment, where rest client was running in webpack-dev server
    13  			w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
    14  
    15  			// For client app, which is running inside webpack, to be removed once dev phase is complete
    16  			w.Header().Set("Access-Control-Allow-Credentials", "true")
    17  
    18  			/*
    19  			 * To expose content-disposition header which can contains filename to a client when it's downloading a file.
    20  			 * Otherwise, the client doesn't see the filename which it's downloading in the browser. This header is simply
    21  			 * not shown: content-disposition: "attachment; filename=25351.pptx"
    22  			 *
    23  			 * That's security restriction of the browser, not client. And this is related to CORS.
    24  			 */
    25  			w.Header().Set("Access-Control-Expose-Headers", "*")
    26  
    27  			if r.Method == "OPTIONS" {
    28  				w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
    29  				w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, X-CSRF-Token, Authorization")
    30  			} else {
    31  				next.ServeHTTP(w, r)
    32  			}
    33  		} else {
    34  			next.ServeHTTP(w, r)
    35  		}
    36  	})
    37  }