MCPcopy
hub / github.com/gofiber/fiber / Save

Method Save

client/response.go:144–190  ·  view source on GitHub ↗

Save writes the response body to a file or io.Writer. If a string path is provided, it creates directories if needed, then writes to a file. If an io.Writer is provided, it writes directly to it. When streaming is enabled, the body is read directly from the stream.

(v any)

Source from the content-addressed store, hash-verified

142// If an io.Writer is provided, it writes directly to it.
143// When streaming is enabled, the body is read directly from the stream.
144func (r *Response) Save(v any) error {
145 switch p := v.(type) {
146 case string:
147 file := filepath.Clean(p)
148 dir := filepath.Dir(file)
149
150 // Create directory if it doesn't exist
151 if _, err := os.Stat(dir); err != nil {
152 if !errors.Is(err, fs.ErrNotExist) {
153 return fmt.Errorf("failed to check directory: %w", err)
154 }
155
156 if err = os.MkdirAll(dir, 0o750); err != nil {
157 return fmt.Errorf("failed to create directory: %w", err)
158 }
159 }
160
161 // Create and write to file
162 outFile, err := os.Create(file)
163 if err != nil {
164 return fmt.Errorf("failed to create file: %w", err)
165 }
166 defer func() { _ = outFile.Close() }() //nolint:errcheck // not needed
167
168 // Use BodyStream() which handles both streaming and non-streaming cases
169 if _, err = io.Copy(outFile, r.BodyStream()); err != nil {
170 return fmt.Errorf("failed to write response body to file: %w", err)
171 }
172
173 return nil
174
175 case io.Writer:
176 // Use BodyStream() which handles both streaming and non-streaming cases
177 if _, err := io.Copy(p, r.BodyStream()); err != nil {
178 return fmt.Errorf("failed to write response body to writer: %w", err)
179 }
180 // Close the writer if it implements io.WriteCloser
181 if pc, ok := p.(io.WriteCloser); ok {
182 _ = pc.Close() //nolint:errcheck // not needed
183 }
184
185 return nil
186
187 default:
188 return ErrNotSupportSaveMethod
189 }
190}
191
192// Reset clears the Response object, making it ready for reuse.
193func (r *Response) Reset() {

Callers 2

Test_Response_SaveFunction · 0.45

Calls 4

BodyStreamMethod · 0.95
IsMethod · 0.65
ErrorfMethod · 0.65
CloseMethod · 0.65

Tested by 2

Test_Response_SaveFunction · 0.36