Skip to content

Commit 7c100f2

Browse files
feat: guess content-type for external bodies
1 parent bd9e3e7 commit 7c100f2

File tree

4 files changed

+25
-7
lines changed

4 files changed

+25
-7
lines changed

lua/rest-nvim/autocmds.lua

+4-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,10 @@ function autocmds.setup()
7373
req.headers["content-type"] = { "application/json" }
7474
elseif req.body.__TYPE == "xml" then
7575
req.headers["content-type"] = { "application/xml" }
76-
-- TODO: auto-set content-type header for external body
76+
elseif req.body.__TYPE == "external" then
77+
local mimetypes = require("mimetypes")
78+
local body_mimetype = mimetypes.guess(req.body.data.path)
79+
req.headers["content-type"] = { body_mimetype }
7780
end
7881
end
7982
end

spec/examples/examples_spec.lua

+17
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,20 @@ describe("pre-request script", function()
103103
assert.same("https://jsonplaceholder.typicode.com/posts/", req2.url)
104104
end)
105105
end)
106+
107+
describe("builtin request hooks", function ()
108+
describe("set_content_type", function ()
109+
it("with external body", function ()
110+
local source = open("spec/examples/post_with_external_body.http")
111+
local _, tree = utils.ts_parse_source(source)
112+
local req_node = assert(tree:root():child(0))
113+
local req = assert(parser.parse(req_node, source))
114+
_G.rest_request = req
115+
vim.api.nvim_exec_autocmds("User", {
116+
pattern = { "RestRequest", "RestRequestPre" },
117+
})
118+
_G.rest_request = nil
119+
assert.same({ "application/json" }, req.headers["content-type"])
120+
end)
121+
end)
122+
end)
+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
// The request body is read from a file
1+
### The request body is read from a file
22
POST https://example.com:8080/api/html/post
3-
Content-Type: application/json
3+
# rest.nvim can guess the Content-Type from file path
44

55
< ./input.json

spec/parser/http_parser_spec.lua

+2-4
Original file line numberDiff line numberDiff line change
@@ -190,12 +190,10 @@ key5 = value5
190190
assert.same({
191191
method = "POST",
192192
url = "https://example.com:8080/api/html/post",
193-
headers = {
194-
["content-type"] = { "application/json" },
195-
},
193+
headers = {},
196194
cookies = {},
197195
handlers = {},
198-
name = "post_with_external_body#1",
196+
name = "The request body is read from a file",
199197
body = {
200198
__TYPE = "external",
201199
data = {

0 commit comments

Comments
 (0)