Usage | temporary-directory-go | Spatie       

 SPATIE  

temporary-directory-go
======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Temporary-directory-go](https://spatie.be/docs/temporary-directory-go/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/temporary-directory-go/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/temporary-directory-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/temporary-directory-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/temporary-directory-go/v1/usage)
- [ Testing ](https://spatie.be/docs/temporary-directory-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/temporary-directory-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/temporary-directory-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/temporary-directory-go/v1/support-us)

 Usage
=====

### Creating a temporary directory

To create a temporary directory simply call `New`:

```
dir, err := temporarydirectory.New()
if err != nil {
    return err
}
defer dir.Close()
```

All examples use `import "github.com/spatie/temporary-directory-go"` and belong inside a function returning `error`. By default, the temporary directory will be created in a randomly named directory in your system's temporary directory, usually `/tmp`. `New` replaces both PHP's constructor followed by `create()` and its static `make()` method.

### Naming your temporary directory

If you want to use a custom name for your temporary directory instead of a random name, pass `WithName`:

```
dir, err := temporarydirectory.New(temporarydirectory.WithName("my-directory"))
if err != nil {
    return err
}
defer dir.Close()
```

By default an error matching `fs.ErrExist` will be returned if a path already exists with the given name. You can override this behaviour by passing `Force` in combination with `WithName`:

```
dir, err := temporarydirectory.New(
    temporarydirectory.WithName("my-directory"),
    temporarydirectory.Force(),
)
if err != nil {
    return err
}
defer dir.Close()
```

Force deletes the existing path and its contents. A symbolic link is removed without deleting its target. Use it only for a path you own. Names are trimmed and reject PHP's reserved characters, NUL, `.` and `..`. Use `errors.Is(err, temporarydirectory.ErrInvalidName)` to recognize an invalid name. `dir.Name()` returns the configured or generated name.

### Setting a custom location for a temporary directory

You can set a custom location in which your temporary directory will be created by passing `WithLocation`:

```
dir, err := temporarydirectory.New(temporarydirectory.WithLocation("/path/to/temporary-directories"))
if err != nil {
    return err
}
defer dir.Close()
```

Missing parent directories are created. An empty location selects the system temporary directory. Relative locations are resolved to absolute paths when the directory is created, so changing the working directory later does not redirect cleanup. Options are applied in order, with the last value for each setting taking precedence. Configuration is fixed at creation rather than mutable afterward.

### Setting custom permissions for a temporary directory

By default, the temporary directory will be created with permissions `0777`, filtered by the process umask. You can customize these permissions by passing `WithPermission`:

```
dir, err := temporarydirectory.New(temporarydirectory.WithPermission(0700))
if err != nil {
    return err
}
defer dir.Close()
```

The same permissions apply to child directories and the root recreated by `Empty`. Use `0700` for private data. Windows uses inherited directory ACLs instead of Unix permission bits.

### Determining paths within the temporary directory

You can use `PathFor` to determine the full path to a file or directory in the temporary directory:

```
path, err := dir.PathFor("dumps/datadump.dat")
if err != nil {
    return err
}
if err := os.WriteFile(path, []byte("temporary data"), 0600); err != nil {
    return err
}
```

Import `os` for file operations. `Path()` returns the root without modifying the filesystem. `PathFor("abc/123/xyz")` creates nested directories. As in PHP, a child containing a dot is treated as a file path, and only its parent directories are created. The file itself is not created. Unlike PHP, dots in the root location do not affect this decision. To create a dotted directory or a file without an extension, use `os.MkdirAll` or `os.WriteFile` with `filepath.Join(dir.Path(), name)` explicitly.

Leading and trailing `/` are stripped. Paths containing parent components are rejected with `ErrInvalidPath`. Directory creation uses `os.Root` to prevent escaping through child symlinks. This does not sandbox subsequent operations on the returned string. Use trusted child names and do not let other processes replace your directory or its contents while using it.

### Emptying a temporary directory

Use `Empty` to delete all the files inside the temporary directory:

```
if err := dir.Empty(); err != nil {
    return err
}
```

The root is recreated with the configured permissions. Recursive deletion does not follow symbolic links.

### Deleting a temporary directory

Once you're done processing your temporary data you can delete the entire temporary directory using `Delete`. All files inside of it will be deleted:

```
if err := dir.Delete(); err != nil {
    return err
}
```

Deleting an absent directory succeeds. `dir.Exists()` reports whether the root exists. Use `os.Stat(dir.Path())` when you need to distinguish a missing directory from a permission error. Filesystem errors retain their standard Go error types, so `errors.Is` and `errors.As` work.

### Deleting a temporary directory when the object is destroyed

Go has no deterministic destructor. Use `defer dir.Close()` to delete the directory when your function returns, including during panic unwinding:

```
func handleTemporaryFiles() error {
    dir, err := temporarydirectory.New()
    if err != nil {
        return err
    }
    defer dir.Close()

    // Use the temporary directory.
    return nil
}
```

`Close` implements `io.Closer` and does the same work as `Delete`. Repeated calls succeed. A deferred call discards cleanup errors. Call `Close` explicitly or use a deferred function if you need to handle them. No cleanup runs after `os.Exit`, a forced termination, or a crash that prevents deferred functions from running. Without `Close` or `Delete`, the directory is left on disk.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
