Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 1 addition & 3 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
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.
1 change: 1 addition & 0 deletions go.work
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use (
./pkg/gofr/datasource/elasticsearch
./pkg/gofr/datasource/file/ftp
./pkg/gofr/datasource/file/s3
./pkg/gofr/datasource/file/gcs
./pkg/gofr/datasource/file/sftp
./pkg/gofr/datasource/kv-store/badger
./pkg/gofr/datasource/kv-store/nats
Expand Down
Loading
Loading