Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,11 @@ docker run -d --name arangodb \
-e ARANGO_ROOT_PASSWORD=rootpassword \
--pull always \
arangodb:latest
<<<<<<< HEAD
docker run -d --name db -p 8091-8096:8091-8096 -p 11210-11211:11210-11211 couchbase
=======
docker login container-registry.oracle.com
docker pull container-registry.oracle.com/database/free:latest
docker run -d --name oracle-free -p 1521:1521 -e ORACLE_PWD=YourPasswordHere container-registry.oracle.com/database/free:latest
>>>>>>> origin
docker run -it --rm -p 4443:4443 -e STORAGE_EMULATOR_HOST=0.0.0.0:4443 fsouza/fake-gcs-server:latest
```

> [!NOTE]
Expand Down Expand Up @@ -145,4 +143,4 @@ docker run -d --name oracle-free -p 1521:1521 -e ORACLE_PWD=YourPasswordHere con
- Use trailing white space or the <br> HTML tag at the end of the line.
- Use "`" sign to add single line code and "```" to add multi-line code block.
- Use relative references to images (in `public` folder as mentioned above.)
* The [gofr.dev documentation](https://gofr.dev/docs) site is updated upon push to `/docs` path in the repo. Verify your changes are live after next GoFr version.
* The [gofr.dev documentation](https://gofr.dev/docs) site is updated upon push to `/docs` path in the repo. Verify your changes are live after next GoFr version.
110 changes: 92 additions & 18 deletions docs/advanced-guide/handling-file/page.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,15 @@ GoFr simplifies the complexity of working with different file stores by offering

By default, local file-store is initialized and user can access it from the context.

GoFr also supports FTP/SFTP file-store. Developers can also connect and use their AWS S3 bucket as a file-store. The file-store can be initialized as follows:
GoFr also supports FTP/SFTP file-store. Developers can also connect and use their cloud storage bucket as a file-store. Following cloud storage options are currently supported:

- **AWS S3**
- **Google Cloud Storage (GCS)**

The file-store can be initialized as follows:

### FTP file-store

```go
package main

Expand All @@ -34,6 +40,7 @@ func main() {
```

### SFTP file-store

```go
package main

Expand All @@ -60,8 +67,7 @@ func main() {
### AWS S3 Bucket as File-Store

To run S3 File-Store locally we can use localstack,
``docker run --rm -it -p 4566:4566 -p 4510-4559:4510-4559 localstack/localstack``

`docker run --rm -it -p 4566:4566 -p 4510-4559:4510-4559 localstack/localstack`

```go
package main
Expand Down Expand Up @@ -90,17 +96,68 @@ func main() {
app.Run()
}
```
> Note: The current implementation supports handling only one bucket at a time,
> as shown in the example with `gofr-bucket-2`. Bucket switching mid-operation is not supported.

> Note: The current implementation supports handling only one bucket at a time,
> as shown in the example with `gofr-bucket-2`. Bucket switching mid-operation is not supported.
### Google Cloud Storage (GCS) Bucket as File-Store

To run GCS File-Store locally we can use fake-gcs-server:
`docker run -it --rm -p 4443:4443 -e STORAGE_EMULATOR_HOST=0.0.0.0:4443 fsouza/fake-gcs-server:latest`

```go
package main

import (
"gofr.dev/pkg/gofr"

"gofr.dev/pkg/gofr/datasource/file/gcs"
)

func main() {
app := gofr.New()

// Option 1: Using JSON credentials string
app.AddFileStore(gcs.New(&gcs.Config{
BucketName: "my-bucket",
CredentialsJSON: readFile("gcs-credentials.json"),
ProjectID: "my-project-id",
}))

// Option 2: Using default credentials from env
// app.AddFileStore(gcs.New(&gcs.Config{
// BucketName: "my-bucket",
// ProjectID: "my-project-id",
// }))

app.Run()
}

// Helper function to read credentials file
func readFile(filename string) []byte {
data, err := os.ReadFile(filename)
if err != nil {
log.Fatalf("Failed to read credentials file: %v", err)
}
return data
}

```

> **Note:** When connecting to the actual GCS service, authentication can be provided via CredentialsJSON or the GOOGLE_APPLICATION_CREDENTIALS environment variable.
> When using fake-gcs-server, authentication is not required.
> Currently supports one bucket per file-store instance.
### Creating Directory

To create a single directory

```go
err := ctx.File.Mkdir("my_dir",os.ModePerm)
```

To create subdirectories as well

```go
err := ctx.File.MkdirAll("my_dir/sub_dir", os.ModePerm)
```
Expand All @@ -114,27 +171,32 @@ currentDir, err := ctx.File.Getwd()
### Change current Directory

To switch to parent directory

```go
currentDir, err := ctx.File.Chdir("..")
```

To switch to another directory in same parent directory

```go
currentDir, err := ctx.File.Chdir("../my_dir2")
```

To switch to a subfolder of the current directory

```go
currentDir, err := ctx.File.Chdir("sub_dir")
```

> Note: This method attempts to change the directory, but S3's flat structure and fixed bucket
> make this operation inapplicable.
> make this operation inapplicable. Similarly, GCS uses a flat structure where directories are simulated through object prefixes.
### Read a Directory

The ReadDir function reads the specified directory and returns a sorted list of its entries as FileInfo objects. Each FileInfo object provides access to its associated methods, eliminating the need for additional stat calls.
The ReadDir function reads the specified directory and returns a sorted list of its entries as FileInfo objects. Each FileInfo object provides access to its associated methods, eliminating the need for additional stat calls.

If an error occurs during the read operation, ReadDir returns the successfully read entries up to the point of the error along with the error itself. Passing "." as the directory argument returns the entries for the current directory.

```go
entries, err := ctx.File.ReadDir("../testdir")

Expand All @@ -143,12 +205,13 @@ for _, entry := range entries {

if entry.IsDir() {
entryType = "Dir"
}
}

fmt.Printf("%v: %v Size: %v Last Modified Time : %v\n", entryType, entry.Name(), entry.Size(), entry.ModTime())
}
```
> Note: In S3, directories are represented as prefixes of file keys. This method retrieves file

> Note: In S3 and GCS, directories are represented as prefixes of file keys/object names. This method retrieves file
> entries only from the immediate level within the specified directory.
### Creating and Save a File with Content
Expand All @@ -163,14 +226,15 @@ _, _ = file.Write([]byte("Hello World!"))
```

### Reading file as CSV/JSON/TEXT

GoFr support reading CSV/JSON/TEXT files line by line.

```go
reader, err := file.ReadAll()

for reader.Next() {
var b string

// For reading CSV/TEXT files user need to pass pointer to string to SCAN.
// In case of JSON user should pass structs with JSON tags as defined in encoding/json.
err = reader.Scan(&b)
Expand All @@ -179,10 +243,12 @@ for reader.Next() {
}
```


### Opening and Reading Content from a File

To open a file with default settings, use the `Open` command, which provides read and seek permissions only. For write permissions, use `OpenFile` with the appropriate file modes.

> Note: In FTP, file permissions are not differentiated; both `Open` and `OpenFile` allow all file operations regardless of specified permissions.
```go
csvFile, _ := ctx.File.Open("my_file.csv")

Expand All @@ -205,6 +271,7 @@ if err != nil {
### Getting Information of the file/directory

Stat retrieves details of a file or directory, including its name, size, last modified time, and type (such as whether it is a file or folder)

```go
file, _ := ctx.File.Stat("my_file.text")
entryType := "File"
Expand All @@ -215,10 +282,12 @@ if entry.IsDir() {

fmt.Printf("%v: %v Size: %v Last Modified Time : %v\n", entryType, entry.Name(), entry.Size(), entry.ModTime())
```
>Note: In S3:

> Note: In S3 and GCS:
>
> - Names without a file extension are treated as directories by default.
> - Names starting with "0" are interpreted as binary files, with the "0" prefix removed.
>
> - Names starting with "0" are interpreted as binary files, with the "0" prefix removed (S3 specific behavior).
>
> For directories, the method calculates the total size of all contained objects and returns the most recent modification time. For files, it directly returns the file's size and last modified time.
### Rename/Move a File
Expand All @@ -234,18 +303,23 @@ err := ctx.File.Rename("old_name.text", "new_name.text")
### Deleting Files

`Remove` deletes a single file
> Note: Currently, the S3 package supports the deletion of unversioned files from general-purpose buckets only. Directory buckets and versioned files are not supported for deletion by this method.

> Note: Currently, the S3 package supports the deletion of unversioned files from general-purpose buckets only. Directory buckets and versioned files are not supported for deletion by this method. GCS supports deletion of both files and empty directories.
```go
err := ctx.File.Remove("my_dir")
```

The `RemoveAll` command deletes all subdirectories as well. If you delete the current working directory, such as "../currentDir", the working directory will be reset to its parent directory.
> Note: In S3, RemoveAll only supports deleting directories and will return an error if a file path (as indicated by a file extension) is provided.

> Note: In S3, RemoveAll only supports deleting directories and will return an error if a file path (as indicated by a file extension) is provided for S3.
> GCS handles both files and directories.
```go
err := ctx.File.RemoveAll("my_dir/my_text")
```

> GoFr supports relative paths, allowing locations to be referenced relative to the current working directory. However, since S3 uses
> a flat file structure, all methods require a full path relative to the S3 bucket.
> GoFr supports relative paths, allowing locations to be referenced relative to the current working directory. However, since S3 and GCS use
> a flat file structure, all methods require a full path relative to the bucket.
> Errors have been skipped in the example to focus on the core logic, it is recommended to handle all the errors.
24 changes: 12 additions & 12 deletions examples/using-add-filestore/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ module gofr.dev/examples/using-add-filestore
go 1.25

require (
github.com/stretchr/testify v1.11.0
github.com/stretchr/testify v1.11.1
go.uber.org/mock v0.6.0
gofr.dev v1.43.0
gofr.dev/pkg/gofr/datasource/file/ftp v0.2.1
)

require (
cloud.google.com/go v0.120.0 // indirect
cloud.google.com/go v0.121.1 // indirect
cloud.google.com/go/auth v0.16.3 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
cloud.google.com/go/compute/metadata v0.7.0 // indirect
Expand Down Expand Up @@ -60,11 +60,11 @@ require (
github.com/prometheus/common v0.65.0 // indirect
github.com/prometheus/otlptranslator v0.0.0-20250717125610-8549f4ab4f8f // indirect
github.com/prometheus/procfs v0.17.0 // indirect
github.com/redis/go-redis/extra/rediscmd/v9 v9.11.0 // indirect
github.com/redis/go-redis/extra/redisotel/v9 v9.11.0 // indirect
github.com/redis/go-redis/v9 v9.11.0 // indirect
github.com/redis/go-redis/extra/rediscmd/v9 v9.12.1 // indirect
github.com/redis/go-redis/extra/redisotel/v9 v9.12.1 // indirect
github.com/redis/go-redis/v9 v9.12.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/segmentio/kafka-go v0.4.48 // indirect
github.com/segmentio/kafka-go v0.4.49 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
Expand All @@ -83,21 +83,21 @@ require (
go.opentelemetry.io/otel/sdk/metric v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.12.0 // indirect
google.golang.org/api v0.244.0 // indirect
google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250728155136-f173205681a0 // indirect
google.golang.org/grpc v1.74.2 // indirect
google.golang.org/protobuf v1.36.6 // indirect
google.golang.org/protobuf v1.36.7 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.66.3 // indirect
modernc.org/mathutil v1.7.1 // indirect
Expand Down
Loading
Loading