HTTP headers 背后的命名约定

Naming convention behind HTTP headers

我正在构建一个 API,我需要在消息通过我的系统时对其进行跟踪。为此,我打算使用 X-Correlation-Id HTTP header,但我遇到了问题。

首先,X- 前缀已​​弃用,不鼓励使用它。那会让我 Correlation-Id.

其次,我打算使用连字符,但在我阅读时 https://www.rfc-editor.org/rfc/rfc7230 I realize that hyphen isn't named anywhere explicitly. section-3.2.6 提及排除的字符 - 这些字符不能用于 http header 定界符?

第三,由于 HTTP header 是 case-insensitive,我是否应该以小写形式定义所有预期的 header?我问是因为我做的研究越多,我发现的变化就越多。有些 API 大写了 header,有些则没有。有些使用连字符,有些使用下划线。

这些东西有明确的指导方针吗?我告诉我的老板,对 HTTP headers 使用驼峰式大小写并不是最佳选择,但我找不到任何相关指南。

  1. 只要是私有的,字段名就无所谓了。如有疑问,请使用“应用程序名称”而不是“X”。

  2. 字段名称使用“令牌”ABNF,其中包含“-”。

  3. 由于它们不区分大小写,因此您如何“定义”它们并不重要。如有疑问,请使用与 HTTP 规范相同的约定。 CamelCase 尤其没有帮助,因为 HTTP/2(和 3)将所有内容都小写。

RFC 2822 定义 Headers

的生产规则

A field name MUST be composed of printable US-ASCII characters (i.e., characters that have values between 33 and 126, inclusive), except colon.

您将在描述 optional fields

的部分找到 ABNF 表示
optional-field  =       field-name ":" unstructured CRLF

field-name      =       1*ftext

ftext           =       %d33-57 /               ; Any character except
                        %d59-126                ;  controls, SP, and
                                                ;  ":".

特别是在 HTTP 中,您需要注意 Appendix B (note that HYPHEN-MINUS 中定义的生产规则是允许的 tchar)

field-name = token

header-field = field-name ":" OWS field-value OWS

tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
    "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA

token = 1*tchar

如果您查看 IANA Message Headers Registry, you'll find quite a few headers that include hyphens in the spelling. Careful examination will show a number of standard HTTP headers that include hyphens (Accept-Language, Content-Type,等等)。

Third, since the HTTP headers are case-insensitive, should I define all of my expected headers in lower case?

对于您的说明,我会推荐与 IANA 注册表中的条目一致的拼写约定;在您的实施中,您将使用不区分大小写的指定拼写匹配。