feat(example): add force HTTPS option to force examples to show https

This commit is contained in:
2021-04-14 19:44:21 +01:00
parent 58c0fea692
commit da12cbabde

11
main.go
View File

@@ -25,13 +25,16 @@ var (
Default("").String() Default("").String()
bindFlag = kingpin.Flag("bind", "Bind address.").Short('b'). bindFlag = kingpin.Flag("bind", "Bind address.").Short('b').
Default("0.0.0.0").String() Default("0.0.0.0").String()
forceHTTPSFlag = kingpin.Flag(
"force-https", "Use https:// in example curl commands",
).Bool()
versionFlag = kingpin.Flag("version", "Print version info."). versionFlag = kingpin.Flag("version", "Print version info.").
Short('v').Bool() Short('v').Bool()
) )
func indexHandler(w http.ResponseWriter, r *http.Request) { func indexHandler(w http.ResponseWriter, r *http.Request) {
scheme := "http" scheme := "http"
if r.TLS != nil { if r.TLS != nil || *forceHTTPSFlag {
scheme = "https" scheme = "https"
} }
@@ -43,7 +46,6 @@ Example usage:
curl -X POST -F "a=Foo Bar" -F "b=FOO BAR" %s://%s/ curl -X POST -F "a=Foo Bar" -F "b=FOO BAR" %s://%s/
curl -X POST "%s://%s/?a=Foo+Bar&b=FOO+BAR"`, curl -X POST "%s://%s/?a=Foo+Bar&b=FOO+BAR"`,
name, version, scheme, r.Host, scheme, r.Host) name, version, scheme, r.Host, scheme, r.Host)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -58,7 +60,6 @@ func casecmpHandler(w http.ResponseWriter, r *http.Request) {
resp = "1" resp = "1"
} }
_, err := fmt.Fprintf(w, resp) _, err := fmt.Fprintf(w, resp)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -100,6 +101,10 @@ func startServer() {
} }
} }
if !*forceHTTPSFlag && os.Getenv("FORCE_HTTPS") != "" {
*forceHTTPSFlag = true
}
address := *bindFlag + ":" + *portFlag address := *bindFlag + ":" + *portFlag
fmt.Printf("Listening on %s\n", address) fmt.Printf("Listening on %s\n", address)
log.Fatal(http.ListenAndServe(address, nil)) log.Fatal(http.ListenAndServe(address, nil))