Middleware to force SSL on requests to a go-json-rest
API.
go get github.com/jadengore/go-json-rest-middleware-force-ssl
package main
import (
"github.com/ant0ine/go-json-rest/rest"
"github.com/jadengore/go-json-rest-middleware-force-ssl"
"log"
"net/http"
)
func main() {
api := rest.NewApi()
api.Use(&forceSSL.Middleware{}) // struct with options
api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(map[string]string{"body": "Hello World!"})
}))
log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
Option | Type | Description | Defaults to |
---|---|---|---|
TrustXFPHeader | bool |
Trust X-Forwarded-Proto headers (this can allow a client to spoof whether they were using HTTPS) |
false |
Enable301Redirects | bool |
Enables 301 redirects to the HTTPS version of the request. |
false |
Message | string |
Allows a custom response message when forcing SSL without redirect. | SSL Required. |
api.Use(forceSSL.Middleware{
TrustXFPHeader: true,
Enable301Redirects: true,
Message: "We are unable to process your request over HTTP."
})
Using rest.IfMiddleware
in go-json-rest
, it is possible to force SSL on a per-route basis.
forceSSLMiddleware := &forceSSL.Middleware{
TrustXFPHeader: true,
Enable301Redirects: false,
Message: "Login required for Admin portal.",
}
api := rest.NewApi()
// Conditionally force certain routes to use forceSSLMiddleware
api.Use(&rest.IfMiddleware{
Condition: func(request *rest.Request) bool {
return request.URL.Path == "/admin"
},
IfTrue: forceSSLMiddleware,
})