-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfile.go
More file actions
224 lines (203 loc) · 6 KB
/
file.go
File metadata and controls
224 lines (203 loc) · 6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package binding
import (
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"strings"
)
// File represents an uploaded file with a clean, ergonomic API.
// It wraps multipart.FileHeader and provides convenient methods for
// reading, streaming, and saving uploaded files.
//
// File is designed to be used in struct binding with the `form` tag:
//
// type UploadRequest struct {
// Avatar *File `form:"avatar"`
// Images []*File `form:"images"`
// }
//
// Security features built-in:
// - Filename is sanitized to prevent path traversal attacks
// - Save() validates destination path
//
// Example:
//
// type Request struct {
// File *File `form:"document"`
// }
//
// var req Request
// if err := binding.MultipartTo(form, &req); err != nil {
// return err
// }
//
// fmt.Printf("Received: %s (%d bytes, %s)\n", req.File.Name, req.File.Size, req.File.ContentType)
//
// if err := req.File.Save("./uploads/" + uuid.New().String() + req.File.Ext()); err != nil {
// return err
// }
type File struct {
// Name is the original filename, sanitized to prevent path traversal.
// Only the base filename is kept (no directory components).
Name string
// Size is the file size in bytes.
Size int64
// ContentType is the MIME type from the Content-Type header.
// Examples: "image/png", "application/pdf", "text/plain"
ContentType string
// header is the underlying multipart.FileHeader for internal use.
header *multipart.FileHeader
}
// NewFile creates a File from a multipart.FileHeader.
// The filename is sanitized to prevent path traversal attacks.
//
// This is the public constructor used by the binding package and
// can be used by external packages that need to create File instances.
func NewFile(fh *multipart.FileHeader) *File {
// Sanitize filename: use only the base name to prevent path traversal
name := filepath.Base(fh.Filename)
// Additional sanitization: remove any remaining path separators
// that might slip through on different OS
name = strings.ReplaceAll(name, "/", "_")
name = strings.ReplaceAll(name, "\\", "_")
// Get content type from header
contentType := fh.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/octet-stream"
}
return &File{
Name: name,
Size: fh.Size,
ContentType: contentType,
header: fh,
}
}
// Bytes reads the entire file contents into memory.
// Use Open() for large files to avoid memory pressure.
//
// Example:
//
// file, _ := getter.File("config")
// data, err := file.Bytes()
// if err != nil {
// return err
// }
// // Process data...
func (f *File) Bytes() (bytes []byte, err error) {
src, err := f.header.Open()
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
defer func() {
if cerr := src.Close(); cerr != nil && err == nil {
err = fmt.Errorf("failed to close file: %w", cerr)
}
}()
return io.ReadAll(src)
}
// Open returns a reader for streaming the file contents.
// Caller must close the returned ReadCloser when done.
//
// Use this for large files to avoid loading the entire file into memory.
//
// Example:
//
// file, _ := getter.File("video")
// reader, err := file.Open()
// if err != nil {
// return err
// }
// defer reader.Close()
//
// // Stream to destination...
// io.Copy(destination, reader)
func (f *File) Open() (io.ReadCloser, error) {
src, err := f.header.Open()
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
return src, nil
}
// Save writes the file to the destination path.
// Creates parent directories automatically if they don't exist.
//
// The destination path is cleaned to prevent path traversal,
// but you should still validate the destination is within
// your intended upload directory.
//
// Example:
//
// type Request struct {
// Document *File `form:"document"`
// }
//
// var req Request
// binding.MultipartTo(form, &req)
//
// // Save with original name
// req.Document.Save("./uploads/" + req.Document.Name)
//
// // Save with generated name (recommended)
// req.Document.Save("./uploads/" + uuid.New().String() + req.Document.Ext())
func (f *File) Save(dst string) (err error) {
// Clean the destination path
dst = filepath.Clean(dst)
// Open the uploaded file
src, err := f.header.Open()
if err != nil {
return fmt.Errorf("failed to open uploaded file: %w", err)
}
defer func() {
if cerr := src.Close(); cerr != nil && err == nil {
err = fmt.Errorf("failed to close source file: %w", cerr)
}
}()
// Create parent directories if needed
dir := filepath.Dir(dst)
if mkdirErr := os.MkdirAll(dir, 0o750); mkdirErr != nil {
return fmt.Errorf("failed to create directory: %w", mkdirErr)
}
// Create destination file
out, err := os.Create(dst)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer func() {
// CRITICAL: Close can fail when flushing buffered data to disk.
// If Close fails, the file may be incomplete even though io.Copy succeeded.
if cerr := out.Close(); cerr != nil && err == nil {
err = fmt.Errorf("failed to close destination file: %w", cerr)
}
}()
// Copy file contents
if _, copyErr := io.Copy(out, src); copyErr != nil {
return fmt.Errorf("failed to save file: %w", copyErr)
}
return nil
}
// Ext returns the file extension including the dot.
// Returns empty string if no extension is present.
//
// Examples:
//
// "image.jpg" → ".jpg"
// "doc.tar.gz" → ".gz"
// "README" → ""
func (f *File) Ext() string {
return filepath.Ext(f.Name)
}