The user wants a file upload service built in Go.
Key requirements:
- Streaming: Handle large files without loading everything into memory.
- AV Scanning: Scan uploaded files for viruses (integration concept).
- MIME Validation: Verify the actual content type, not just the extension.
- Lifecycle: Manage file expiration/archival (concepts).
- Signed URLs: Generate secure, time-limited links for downloading.
Architecture/Stack:
- Language: Go (Golang) is the standard for backend services like this due to performance and concurrency.
- Storage: S3 (or compatible like MinIO) is the industry standard for object storage.
- HTTP Framework:
net/http is fine, or gin/echo. I'll stick to net/http or a lightweight wrapper to keep it standard, but standard library is usually sufficient for a demo.
- Database: Postgres (to store metadata, status, expiration).
- Virus Scanning: ClamAV is the standard open-source choice.
Step-by-Step Implementation Plan:
-
Project Structure:
main.go: Entry point.
handlers: Upload, Download.
storage: S3/MinIO interface.
scanner: ClamAV interface.
utils: MIME detection, Signed URL generation.
-
Streaming Uploads:
- Use
io.Copy or io.TeeReader.
- Don't use
r.FormFile if we want strict control, use r.MultipartReader to stream parts directly to storage without buffering the whole file in RAM.
-
MIME Validation:
- Use
http.DetectContentType. Since we are streaming, we need to peek the first 512 bytes.
- Constraint: We need to check MIME before committing to storage ideally, or at least during.
- Approach: Use a
io.MultiReader to read the first 512 bytes for detection, then pass the rest to the uploader.
-
Storage Interface (MinIO/S3):
- Use
minio/minio-go driver.
- Use
PutObject which takes an io.Reader.
-
AV Scanning:
- This is tricky with streaming. ClamAV usually scans files on disk or a stream.
- Approach A: Upload to S3, then trigger a scan (async).
- Approach B: Scan while uploading (sync).
- Decision: For a robust service, usually you upload to a "quarantine" bucket, scan, then move to "clean" bucket. However, the prompt implies a "service". I will implement an interface for the scanner and mock the implementation or provide a simple TCP implementation for ClamAV.
-
Lifecycle:
- This is usually handled via DB flags (
expires_at) and a background worker (cron) that deletes old files.
- I'll define the DB schema and a placeholder for the cleanup job.
-
Signed URLs:
- S3 has built-in presigned URLs.
- If we want application-level signed URLs (to hide the bucket or add logic), we need HMAC signing.
- Decision: Let's use S3 Presigned URLs as they are the standard solution for "offloading traffic from the app server".
Refining the Code Structure (Mental Draft):
-
Dependencies: minio, jackc/pgx (or standard db), maybe h2non/filetype for better MIME detection? net/http built-in is okay.
-
The "Streaming" Challenge:
- Standard
multipart/form-data parsing reads the whole file into temp files if not handled carefully.
- We need
r.MultipartReader().
- We read the header, find the file part.
- We read 512 bytes -> Detect MIME.
- We reconstruct the reader (bytes read + remaining stream) -> Pass to S3 PutObject.
-
The AV Challenge:
- ClamAV requires a session.
INSTREAM command.
- To stream both to S3 and ClamAV simultaneously?
io.TeeReader works, but network latency mismatch makes it hard.
- Simpler approach for this code: Write to a temporary buffer/file (if small) or just upload to S3, then download to scan?
- Better approach for this specific prompt: I will implement the "Quarantine" pattern.
- Upload stream to S3 (Quarantine bucket).
- Return "Uploaded/Pending Scan".
- Background worker scans.
- Signed URLs only work if scan passes.
Wait, the user might want a synchronous response. "Build a file upload service".
Let's stick to a synchronous-ish flow for the demo:
- Receive stream.
- Pipe to S3.
- Trigger scan (mocked or simple ClamAV ping).
- Return ID.
Actually, let's do S3 Presigned URLs for Upload (client uploads directly to S3) + Notification?
No, the prompt asks to "Build a file upload service". Usually, this means the server handles the file.
I will implement the Server-side Streaming Proxy.
Revised AV Strategy: Real-time streaming to ClamAV while uploading to S3 is complex (backpressure).
Compromise: I will show the Synchronous Validation approach using a buffer for MIME, and then an Async Scan approach concept, but implement the S3 upload directly.
Let's focus on the Streaming + MIME part heavily, as that's the "Go" way.
Code Components:
FileService struct holding S3 client, DB, Scanner.
UploadHandler:
- Parse multipart.
- Read 512 bytes (Peek).
- Validate MIME.
- Create
io.MultiReader (Peeked bytes + remaining body).
- Stream to S3
PutObject.
- Save Metadata to DB.
- Return ID.
DownloadHandler (Signed URL):
- Check DB if file is clean/exists.
- Generate S3 Presigned URL (GET).
Let's write the code.
- Imports: Standard lib +
github.com/minio/minio-go/v7.
- Mocking: I won't include a running ClamAV instance, but I will create the Interface and a Mock implementation so the user sees where to plug it in.
Refining the Lifecycle:
I'll add an ExpiresAt column. I'll show a snippet for a cleanup routine.
Refining Signed URLs:
I will use MinIO's PresignedGetObject. It's the most efficient way (offloads bandwidth).
Handling "Streaming" correctly:
To truly stream and not buffer in memory:
reader, err := r.MultipartReader()
Loop through parts.
If file part:
buffer := make([]byte, 512)
n, _ := part.Read(buffer)
mime := http.DetectContentType(buffer)
fullReader := io.MultiReader(bytes.NewReader(buffer), part)
s3Client.PutObject(ctx, bucket, key, fullReader, size, ...)
Dependencies:
I need to define a go.mod context mentally.
github.com/minio/minio-go/v7
github.com/google/uuid
Self-Correction during thought process:
The user might want application-level signed URLs (HMAC) rather than S3 Presigned, to track download counts. I will stick to S3 Presigned for simplicity and performance but mention the alternative.
Final Output Structure:
- Concepts: Brief explanation of the architecture.
- Project Setup: Folder structure.
- Core Implementation:
- Storage Interface (MinIO/S3).
- Scanner Interface (ClamAV).
- The Service Logic (Streaming, MIME, DB).
- Handlers: HTTP entry points.
- Running instructions.
Let's prepare the Go code. I will use MinIO as the S3 backend because it's easy to run locally via Docker.
Key details to nail:
- MIME Detection: Needs the first 512 bytes.
- Streaming:
io.Pipe or io.MultiReader. MultiReader is safer here.
- Lifecycle:
time.Now().Add(...) in DB.
- Signed URLs:
presignedURL, err := s3Client.PresignedGetObject(...).
Let's assemble.
The "AV Scanning" part in detail:
Scanning a stream during upload to S3 is hard because if the AV fails at 90%, S3 already has the partial file (unless you use multipart and abort, or write to a temp bucket).
I will implement the "Scan after upload" pattern (Move from Staging to Production), as it's the only production-safe way to handle AV without buffering the whole file in RAM.
- Upload to
staging-bucket.
- Trigger Scan (async).
- If clean, move to
final-bucket (or set metadata "clean=true").
- Signed URLs only allow access if "clean=true".
Actually, for simplicity in a single code block, I'll simulate the scan synchronously or mark it "pending" and explain the async step.
I will write a synchronous "Scanner" interface implementation that just reads the stream (using a TeeReader) to simulate scanning while uploading to a temp location, then promoting it.
No, simpler: Upload -> S3. The "Lifecycle" section handles the cleanup/scan.
I will focus on the Streaming Upload and Signed Download.
Let's stick to the prompt's request for "AV Scanning":
I'll include a ClamAV client wrapper. The strategy:
Use io.TeeReader.
One reader goes to S3 (fast).
One reader goes to ClamAV (slow).
If ClamAV fails, we mark the DB entry as "Infected" (and eventually delete).
Problem: io.TeeReader blocks the S3 upload if ClamAV is slow.
Better Strategy: The industry standard is Object Lock or Bucket Replication + Lambda/Scan.
Since I need to provide code:
I will define a Scanner interface.
I will implement a ClamAVScanner.
I will show how to hook it. To make the code runnable without a ClamAV container, I'll provide a NoOpScanner by default but include the code for the real one.
Final Plan:
- Models:
FileMetadata (ID, Name, MIME, Status, ExpiredAt).
- S3 Wrapper: MinIO wrapper for Put (streaming) and Presign.
- Scanner: Interface.
- Handler:
Upload: MultipartReader -> Peek 512b (MIME) -> MultiReader -> S3.Put.
Download: S3.Presign.
Let's write it.
Note on MIME detection: http.DetectContentType is robust enough for basic checks.
Note on Lifecycle: I'll add a LifecycleManager struct.
Let's generate the response. I will provide a complete, single-package runnable example (assuming local MinIO/Postgres dependencies) but structure it cleanly.
Wait, I can simulate the dependencies to make it more "copy-paste" friendly?
No, it's better to require MinIO. It's standard.
Structure:
main.go -> Setup dependencies, start server.
upload.go -> Logic.
scan.go -> Logic.
presign.go -> Logic.
I will combine them into logical blocks in the response.
Safety checks:
- Path traversal in filenames?
filepath.Base.
- File size limit?
http.MaxBytesHandler.
Let's go.
One specific detail: Streaming + MIME.
Since http.DetectContentType needs 512 bytes, and multipart is a stream, once I read 512 bytes, I must prepend them back to the reader I pass to S3.
io.MultiReader is the specific tool for this.
Signed URLs:
S3 presigned URLs are generated by the server using credentials, valid for X seconds, executed by the client directly against S3.
AV Scanning implementation detail:
I will assume a "Scan on Upload" approach where we pipe the data.
Actually, piping data to S3 and ClamAV simultaneously is the most "streaming" way to do it.
I'll use io.Pipe? No, io.TeeReader.
Reader (Network) -> TeeReader -> Writer A (S3) & Reader B (ClamAV).
Actually, TeeReader writes to a Writer. S3 PutObject takes a Reader.
So:
Network Reader -> TeeReader -> (Logic) -> S3 Writer? No, S3 client usually takes a Reader.
If S3 takes a Reader, we can't use TeeReader easily unless we upload via a Pipe.
pr, pw := io.Pipe()
go func() { io.Copy(pw, requestBody) }()
s3.PutObject(pr)
av.Scan(pr) -- No, can't read twice.
Correct "Dual" Streaming Approach:
- Create a
io.PipeWriter for S3.
- Read from Request.
- Write to PipeWriter (S3 uploads in background).
- Feed data to AV Scanner.
Actually, the standard way is Upload to S3 -> S3 Event -> Scan.
I will implement the S3 Presigned POST policy?
No, that's client-side.
The user asked to "Build a file upload service" (server receives).
Okay, I will stick to:
- Server receives stream.
- Peeks 512b for MIME.
- Uploads to S3 (Staging).
- Returns Success.
- (Optional/Bonus) Explain the Async scan loop.
I'll refine the prompt requirement: "AV Scanning".
I will implement a synchronous scan simulation using a small buffer or just explain where it fits. If I try to implement real ClamAV streaming in the example, it becomes non-runnable without the specific ClamAV socket.
I will provide the Interface and a Mock implementation, and comment on how to do the real ClamAV INSTREAM.
Okay, ready.
Summary of the Code:
- MinioSetup: Setup S3 client.
- DB: In-memory map for metadata (to keep it runnable without Postgres).
- Scanner: Interface + Mock.
- Upload Handler:
r.MultipartReader
- Read part.
bytes.NewReader + http.DetectContentType.
io.MultiReader (head + body).
s3.PutObject (streaming).
scanner.Scan(reader)? No, can't read twice.
- Solution: Upload to S3 first. Then, if AV is required, the service downloads (streams) from S3 to the AV scanner. This prevents buffering in RAM.
Let's proceed.
This solution implements a production-ready file upload service in Go. It avoids loading entire files into memory (RAM), making it suitable for handling massive files (GBs/TBs) even