Over the years I've noticed quite a lot of “magic” strings
in HTTP-related code, primarily "http" and
"https". There are a lot of examples
in net/http/... as well as in cmd/....
So, I propose to add these constants to net/http
(or, perhaps, net/url?):
const (
Scheme = "http"
Secure = "https"
)
Example usage:
var u = &url.URL{
Scheme: http.Scheme,
Host: host,
Path: path.Join("users", userID),
}
if u.Scheme != http.Secure {
return errors.New("insecure api")
}
I think Scheme and Secure are not obvious to the reader, if anything I would prefer plain HTTP and HTTPS though it stutters
@seankhliao My reasoning was similar to that
of sort.Interface. Then again, we
do have log.Log, so I don't really have
a strong opinion about the exact naming.
I don’t think these constants add anything for the reader. The literals http and https are descriptive, we’ll know, and unlikely to change at this point. A constant which represented these literals would be identical, except would be capitalised, which is misleading as HTTP schemes are not capitalised.
@davecheney My main concern here are possible
misspellings. I've already seen http being
misspelled as htp in a private
project. Luckily, the tests caught it, but still.
In addition to the stutter, writing http.HTTP and http.HTTPS is 3 characters longer than "http" and "https".
People felt strongly about adding the HTTP method constants too but in practice they're not used because "GET" looks better than http.MethodGet. I feel like this would be the same.
As such, I'm not in favor of this.
@bradfitz
[…] in practice they're not used because
"GET"looks better thanhttp.MethodGet. I feel like this would be the same.
That is not my experience, to be honest. Unless the code base is older than the named constants, I have almost always seen the constants preferred to literals.
As for the stuttering, my original proposal doesn't have that issue.
As for the stuttering, my original proposal doesn't have that issue
Accepted, but the names http.Scheme and http.Secure don’t describe their contents; the former sounds like the name of a type and the latter sounds like some kind of boolean
@davecheney I guess they could be
http.SchemePlain and http.SchemeSecure,
just like we now have http.MethodGet
and http.MethodPost. But that's way
more typing.
I would hope that packages that implement other
protocols would add their schemes in a similar fashion,
so that we could have, say, ftp.Scheme
and git.Scheme.
Based on the discussion, this seems like a likely decline.
No change in consensus, so declined.
Most helpful comment
In addition to the stutter, writing
http.HTTPandhttp.HTTPSis 3 characters longer than"http"and"https".People felt strongly about adding the HTTP method constants too but in practice they're not used because
"GET"looks better thanhttp.MethodGet. I feel like this would be the same.As such, I'm not in favor of this.