Skip to content

Instantly share code, notes, and snippets.

@garrydzeng
Created February 21, 2022 19:00
Show Gist options
  • Save garrydzeng/c57c6871db70deb85c92a1c4e625d07f to your computer and use it in GitHub Desktop.
Save garrydzeng/c57c6871db70deb85c92a1c4e625d07f to your computer and use it in GitHub Desktop.
A field parameter used to negotiate content schema (example: )

起因

内容协商 (Content Negotiation) 是 HTTP 协议重要的组成部分,它允许客户端与服务端协商内容的媒体类型 (MIME) 等信息,但不能拿来协商内容结构。日常开发当中,这个其实是刚需的功能:或许你还能记得客户端需要什么字段的时候,服务端就对应地修改返回的数据。反反复复的日子😂。为了解决这个问题,计划在 Accept 请求头当中 schema 参数用于协商数据结构

示例

POST /sessions
Accept: application/json; charset=utf-8; schema={id,user{name,id}}

这个例子里,客户端协商数据结构为 {id,user{name,id}} ,因此服务端自动地响应需要的自动为 JSON 格式

{
  "id": "954026db5ec3406ea4da45dc5459a15a",
  "user": {
    "name": "Administrator",
    "id": 1
  }
}

客户端会知道完整的数据结构 (及其类型),但是它可以自己决定用哪些字段而不需要服务端干预。若遇到没有权限或不存在的字段时可以认为协商失败了,返回 406 Not Acceptable 状态码

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment