github.com/lauslim12/expert-systems@v0.0.0-20221115131159-018513aad29c/internal/application/middleware.go (about)

     1  package application
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  )
     7  
     8  // Adds custom headers to the application.
     9  func customHeaders(next http.Handler) http.Handler {
    10  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    11  		w.Header().Add("X-Expert-Systems", "Miyuki")
    12  		w.Header().Add("Server", "net/http")
    13  		next.ServeHTTP(w, r)
    14  	})
    15  }
    16  
    17  // Auto redirect to HTTPS if possible.
    18  func httpsRedirect(applicationMode string) func(http.Handler) http.Handler {
    19  	return func(next http.Handler) http.Handler {
    20  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    21  			if applicationMode == "production" {
    22  				if r.Header.Get("X-Forwarded-Proto") != "https" {
    23  					sslUrl := fmt.Sprintf("https://%s%s", r.Host, r.RequestURI)
    24  					http.Redirect(w, r, sslUrl, http.StatusPermanentRedirect)
    25  					return
    26  				}
    27  			}
    28  
    29  			next.ServeHTTP(w, r)
    30  		})
    31  	}
    32  }