Skip to content

Commit c91d23a

Browse files
committed
Updated unified handling-files documentation for GCS setup guide
1 parent 7b1824a commit c91d23a

File tree

1 file changed

+86
-18
lines changed
  • docs/advanced-guide/handling-file

1 file changed

+86
-18
lines changed

docs/advanced-guide/handling-file/page.md

Lines changed: 86 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@ GoFr simplifies the complexity of working with different file stores by offering
66

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

9-
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:
9+
GoFr also supports FTP/SFTP file-store. Developers can also connect and use their AWS S3 bucket or Google Cloud Storage (GCS) bucket as a file-store. The file-store can be initialized as follows:
1010

1111
### FTP file-store
12+
1213
```go
1314
package main
1415

@@ -34,6 +35,7 @@ func main() {
3435
```
3536

3637
### SFTP file-store
38+
3739
```go
3840
package main
3941

@@ -60,8 +62,7 @@ func main() {
6062
### AWS S3 Bucket as File-Store
6163

6264
To run S3 File-Store locally we can use localstack,
63-
``docker run --rm -it -p 4566:4566 -p 4510-4559:4510-4559 localstack/localstack``
64-
65+
`docker run --rm -it -p 4566:4566 -p 4510-4559:4510-4559 localstack/localstack`
6566

6667
```go
6768
package main
@@ -90,17 +91,68 @@ func main() {
9091
app.Run()
9192
}
9293
```
93-
> Note: The current implementation supports handling only one bucket at a time,
94-
> as shown in the example with `gofr-bucket-2`. Bucket switching mid-operation is not supported.
94+
95+
> Note: The current implementation supports handling only one bucket at a time,
96+
> as shown in the example with `gofr-bucket-2`. Bucket switching mid-operation is not supported.
97+
98+
### Google Cloud Storage (GCS) Bucket as File-Store
99+
100+
To run GCS File-Store locally we can use fake-gcs-server:
101+
`docker run -it --rm -p 4443:4443 -e STORAGE_EMULATOR_HOST=0.0.0.0:4443 fsouza/fake-gcs-server:latest`
102+
103+
```go
104+
package main
105+
106+
import (
107+
"gofr.dev/pkg/gofr"
108+
109+
"gofr.dev/pkg/gofr/datasource/file/gcs"
110+
)
111+
112+
func main() {
113+
app := gofr.New()
114+
115+
// Option 1: Using JSON credentials string
116+
app.AddFileStore(gcs.New(&gcs.Config{
117+
BucketName: "my-bucket",
118+
CredentialsJSON: readFile("gcs-credentials.json"),
119+
ProjectID: "my-project-id",
120+
}))
121+
122+
// Option 2: Using default credentials from env
123+
// app.AddFileStore(gcs.New(&gcs.Config{
124+
// BucketName: "my-bucket",
125+
// ProjectID: "my-project-id",
126+
// }))
127+
128+
app.Run()
129+
}
130+
131+
// Helper function to read credentials file
132+
func readFile(filename string) []byte {
133+
data, err := os.ReadFile(filename)
134+
if err != nil {
135+
log.Fatalf("Failed to read credentials file: %v", err)
136+
}
137+
return data
138+
}
139+
140+
```
141+
142+
> **Note:** When connecting to the actual GCS service, authentication can be provided via CredentialsJSON or the GOOGLE_APPLICATION_CREDENTIALS environment variable.
143+
> When using fake-gcs-server, authentication is not required.
144+
> Currently supports one bucket per file-store instance.
95145
96146
### Creating Directory
97147

98148
To create a single directory
149+
99150
```go
100151
err := ctx.File.Mkdir("my_dir",os.ModePerm)
101152
```
102153

103154
To create subdirectories as well
155+
104156
```go
105157
err := ctx.File.MkdirAll("my_dir/sub_dir", os.ModePerm)
106158
```
@@ -114,27 +166,32 @@ currentDir, err := ctx.File.Getwd()
114166
### Change current Directory
115167

116168
To switch to parent directory
169+
117170
```go
118171
currentDir, err := ctx.File.Chdir("..")
119172
```
120173

121174
To switch to another directory in same parent directory
175+
122176
```go
123177
currentDir, err := ctx.File.Chdir("../my_dir2")
124178
```
125179

126180
To switch to a subfolder of the current directory
181+
127182
```go
128183
currentDir, err := ctx.File.Chdir("sub_dir")
129184
```
185+
130186
> Note: This method attempts to change the directory, but S3's flat structure and fixed bucket
131-
> make this operation inapplicable.
187+
> make this operation inapplicable. Similarly, GCS uses a flat structure where directories are simulated through object prefixes.
132188
133189
### Read a Directory
134190

135-
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.
191+
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.
136192

137193
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.
194+
138195
```go
139196
entries, err := ctx.File.ReadDir("../testdir")
140197

@@ -143,12 +200,13 @@ for _, entry := range entries {
143200

144201
if entry.IsDir() {
145202
entryType = "Dir"
146-
}
203+
}
147204

148205
fmt.Printf("%v: %v Size: %v Last Modified Time : %v\n", entryType, entry.Name(), entry.Size(), entry.ModTime())
149206
}
150207
```
151-
> Note: In S3, directories are represented as prefixes of file keys. This method retrieves file
208+
209+
> Note: In S3 and GCS, directories are represented as prefixes of file keys/object names. This method retrieves file
152210
> entries only from the immediate level within the specified directory.
153211
154212
### Creating and Save a File with Content
@@ -163,14 +221,15 @@ _, _ = file.Write([]byte("Hello World!"))
163221
```
164222

165223
### Reading file as CSV/JSON/TEXT
224+
166225
GoFr support reading CSV/JSON/TEXT files line by line.
167226

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

171230
for reader.Next() {
172231
var b string
173-
232+
174233
// For reading CSV/TEXT files user need to pass pointer to string to SCAN.
175234
// In case of JSON user should pass structs with JSON tags as defined in encoding/json.
176235
err = reader.Scan(&b)
@@ -179,10 +238,12 @@ for reader.Next() {
179238
}
180239
```
181240

182-
183241
### Opening and Reading Content from a File
242+
184243
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.
244+
185245
> Note: In FTP, file permissions are not differentiated; both `Open` and `OpenFile` allow all file operations regardless of specified permissions.
246+
186247
```go
187248
csvFile, _ := ctx.File.Open("my_file.csv")
188249

@@ -205,6 +266,7 @@ if err != nil {
205266
### Getting Information of the file/directory
206267

207268
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)
269+
208270
```go
209271
file, _ := ctx.File.Stat("my_file.text")
210272
entryType := "File"
@@ -215,10 +277,12 @@ if entry.IsDir() {
215277

216278
fmt.Printf("%v: %v Size: %v Last Modified Time : %v\n", entryType, entry.Name(), entry.Size(), entry.ModTime())
217279
```
218-
>Note: In S3:
280+
281+
> Note: In S3 and GCS:
282+
>
219283
> - Names without a file extension are treated as directories by default.
220-
> - Names starting with "0" are interpreted as binary files, with the "0" prefix removed.
221-
>
284+
> - Names starting with "0" are interpreted as binary files, with the "0" prefix removed (S3 specific behavior).
285+
>
222286
> 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.
223287
224288
### Rename/Move a File
@@ -234,18 +298,22 @@ err := ctx.File.Rename("old_name.text", "new_name.text")
234298
### Deleting Files
235299

236300
`Remove` deletes a single file
237-
> 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.
301+
302+
> 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.
303+
238304
```go
239305
err := ctx.File.Remove("my_dir")
240306
```
241307

242308
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.
243-
> 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.
309+
310+
> Note: In S3 and GCS, 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.
311+
244312
```go
245313
err := ctx.File.RemoveAll("my_dir/my_text")
246314
```
247315

248-
> GoFr supports relative paths, allowing locations to be referenced relative to the current working directory. However, since S3 uses
249-
> a flat file structure, all methods require a full path relative to the S3 bucket.
316+
> GoFr supports relative paths, allowing locations to be referenced relative to the current working directory. However, since S3 and GCS use
317+
> a flat file structure, all methods require a full path relative to the bucket.
250318
251319
> Errors have been skipped in the example to focus on the core logic, it is recommended to handle all the errors.

0 commit comments

Comments
 (0)