Force SSL Middleware for go-json-rest
Middleware to force SSL on requests to a go-json-rest
API.
Installation
go get github.com/jadengore/go-json-rest-middleware-force-ssl
Example Usage
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{})
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()))
}
Options
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. |
Middleware Options Example
api.Use(forceSSL.Middleware{
TrustXFPHeader: true,
Enable301Redirects: true,
Message: "We are unable to process your request over HTTP."
})
Per-route SSL Settings
Using rest.IfMiddleware
in go-json-rest
, it is possible to force SSL on a per-route basis.
Example Usage
forceSSLMiddleware := &forceSSL.Middleware{
TrustXFPHeader: true,
Enable301Redirects: false,
Message: "Login required for Admin portal.",
}
api := rest.NewApi()
api.Use(&rest.IfMiddleware{
Condition: func(request *rest.Request) bool {
return request.URL.Path == "/admin"
},
IfTrue: forceSSLMiddleware,
})