NewFile returns a new temporary file with the data copied from the Reader. It must be closed when done. This deletes this file. This file will be automatically closed on context cancellation. Usage of this function requires eng approval - ask before using.
(ctx context.Context, reader io.Reader)
| 43 | // |
| 44 | // Usage of this function requires eng approval - ask before using. |
| 45 | func NewFile(ctx context.Context, reader io.Reader) (File, error) { |
| 46 | id, err := uuidutil.New() |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | file, err := os.CreateTemp("", id.String()) |
| 51 | if err != nil { |
| 52 | return nil, err |
| 53 | } |
| 54 | path := file.Name() |
| 55 | // just in case |
| 56 | absPath, err := filepath.Abs(filepath.Clean(path)) |
| 57 | if err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | closer := func() error { return os.Remove(absPath) } |
| 61 | go func() { |
| 62 | <-ctx.Done() |
| 63 | _ = closer() |
| 64 | }() |
| 65 | _, err = io.Copy(file, reader) |
| 66 | err = errors.Join(err, file.Close()) |
| 67 | if err != nil { |
| 68 | err = errors.Join(err, closer()) |
| 69 | return nil, err |
| 70 | } |
| 71 | return newFile(closerFunc(closer), absPath), nil |
| 72 | } |
| 73 | |
| 74 | // NewDir returns a new temporary directory. |
| 75 | // |