Created
August 23, 2024 15:54
-
-
Save ocap-kirk/1944041b473c84ebaf1324e6535ea461 to your computer and use it in GitHub Desktop.
HTTP Request to Curl Command Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>HTTP Request to Curl Command Converter</title> | |
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> | |
</head> | |
<body> | |
<h1>HTTP Request to Curl Command Converter</h1> | |
<textarea id="input" rows="10" cols="80" placeholder="Paste your HTTP request here"></textarea><br> | |
<button id="generateCurl">Generate Curl Command</button><br> | |
<textarea id="output" rows="10" cols="80" placeholder="Curl command will appear here"></textarea> | |
<script> | |
function parseInput(input) { | |
let lines = input.split('\n'); | |
let method, path, httpVersion, headers = {}, body = []; | |
let state = 0; // 0 = request line, 1 = headers, 2 = body | |
lines.forEach(line => { | |
line = line.trim(); | |
if (state === 0) { | |
let match = line.match(/([^ ]+) +([^ ]+) +(HTTP\/.*)/); | |
if (match) { | |
method = match[1]; | |
path = match[2]; | |
httpVersion = match[3]; | |
state++; | |
} | |
} else if (state === 1) { | |
if (line.includes(":")) { | |
let [headerName, headerValue] = line.split(':').map(s => s.trim()); | |
headers[headerName.toLowerCase()] = headerValue; | |
} else if (line === '') { | |
state++; | |
} | |
} else if (state === 2) { | |
body.push(line); | |
} | |
}); | |
return { method, path, httpVersion, headers, body }; | |
} | |
function generateCurlCommand(parsedData) { | |
let { method, path, headers, body } = parsedData; | |
let curlCmd = `curl -X ${method} `; | |
let url = `https://${headers['host']}${path}`; | |
// Add headers to the curl command, ignoring Content-Length | |
Object.keys(headers).forEach(header => { | |
if (header !== "content-length") { | |
curlCmd += `-H "${header}: ${headers[header]}" `; | |
} | |
}); | |
// Add body if present | |
if (body.length > 0) { | |
let bodyData = body.join('\n').replace(/\n/g, ' ').trim(); | |
curlCmd += `--data-binary '${bodyData}' `; | |
} | |
// Add the URL to the curl command | |
curlCmd += `"${url}"`; | |
return curlCmd; | |
} | |
$('#generateCurl').click(function() { | |
let input = $('#input').val(); | |
let parsedData = parseInput(input); | |
let curlCmd = generateCurlCommand(parsedData); | |
$('#output').val(curlCmd); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment