在Go中构建URL(包括服务器方案)

I am creating a REST API in Go, and I want to build URLs to other resources in my replies.

Based on the http.Response I can get the Host and URL.

However, how would I go about getting the transport scheme used by the server? http or https?

I attemped to check if server.TLSConfig is nil and then assuming it is using http since it says this in the documentation for http.Server:

TLSConfig    *tls.Config   // optional TLS config, used by ListenAndServeTLS

But it turns out this exists even when I do not run the server with ListenAndServeTLS.


Or is this way of building my URLs the wrong way of doing things? Is there some other normal way of doing this?

My preferred solution when running http and https is just to run a simple listener on :80 that redirects all traffic to https. Then any real traffic can be assumed to be https.

Alternately I believe you can access a request's URL at req.URL.Scheme to see the protocol.

Or do you mean for the entire application? If you accept configuration to switch between http and https, then can't you look at that and see which they chose? I guess I'm missing some context maybe.

It is also common practice for apps to take a baseURL via flag or config to generate external urls with.