Bug: multipartWriter omits final boundary terminator Steps: send multipart Expected:…
- User
Bug:
multipartWriteromits final boundary terminator | Steps: send multipart | Expected: ends with --boundary-- | Actual: missing. Assistant
Bug: multipartWriter omits final boundary terminator | Steps: send multipart | Expected: ends with --boundary-- | Actual: missing.
The multipart encoding format (RFC 2046, RFC 7578) requires messages to end with a terminating boundary: --boundary--
--boundary_crud
Content-Disposition: form-data; name="field1"
value1
--boundary_crud
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain
file contents
--boundary_crud-- ← REQUIRED terminating boundary
The bug typically occurs when Close() is never called or fails silently. Here's why:
// Buggy implementation - Close() never called
func sendMultipartBuggy(url string) error {
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
// Add parts...
writer.CreateFormFile("file", "test.txt")
// BUG: writer.Close() is never called!
// Buffer now contains:
// --boundary_crud
// Content-Disposition: form-data; name="file"; filename="test.txt"
// Content-Type: text/plain
//
// (missing --boundary_crud--)
http.Post(url, writer.FormDataContentType(), &buf)
return nil
}
# Captured raw bytes (hex dump of buggy output):
00000000 2d 2d 62 6f 75 6e 64 61 72 79 5f 63 72 75 64 0d |--boundary_crud.|
00000010 0a 43 6f 6e 74 65 6e 74 2d 44 69 73 70 6f 73 69 |.Content-Disposi|
...
00000040 74 65 78 74 0d 0a 0d 0a 66 69 6c 65 20 64 61 74 |text....file dat|
00000050 61 |a|
# NO terminating --boundary_crud-- present!
func sendMultipartFixed(url string) error {
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
// Proper cleanup ensures final boundary is written
defer writer.Close() // FIX: Always close the writer
// Or use explicit close with error handling:
part, _ := writer.CreateFormFile("file", "test.txt")
part.Write([]byte("file data"))
if err := writer.Close(); err != nil {
return fmt.Errorf("failed to close multipart writer: %w", err)
}
return http.Post(url, writer.FormDataContentType(), &buf)
}
# After fix - proper termination:
00000000 2d 2d 62 6f 75 6e 64 61 72 79 5f 63 72 75 64 0d |--boundary_crud.|
...
00000050 61 0d 0a 2d 2d 62 6f 75 6e 64 61 72 79 5f 63 72 |a..--boundary_cr|
00000060 75 64 2d 2d 0d 0a |ud--..|
# └─────────────────────────────────────────┘
# Final boundary present!
| Aspect | Buggy | Fixed |
|---|---|---|
| Final boundary | --boundary_crud | --boundary_crud--\r\n |
| Close() called | Never | Always (defer or explicit) |
| Server behavior | May reject or timeout | Correctly parses all parts |