Created
March 1, 2022 17:26
-
-
Save rseroter/e70916bbc1291a959502f39ba016346c to your computer and use it in GitHub Desktop.
Go service that reads Google Cloud Storage objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package goportable | |
import ( | |
"encoding/json" //encoding the response | |
"log" //writing logs | |
"net/http" | |
"strings" //flattening an array | |
"cloud.google.com/go/storage" //talking to cloud storage | |
"github.com/GoogleCloudPlatform/functions-framework-go/functions" //go middleware | |
"google.golang.org/api/iterator" //looping through objects | |
) | |
func init() { | |
functions.HTTP("ReadFiles", readFiles) | |
} | |
// readFiles is an HTTP Cloud Function with a request parameter. | |
func readFiles(w http.ResponseWriter, r *http.Request) { | |
log.Printf("called the API!") | |
//grab querystring param, if empty, set to default value | |
bucketname := r.URL.Query().Get("bucketname") | |
if bucketname == "" { | |
bucketname = "seroter-app-files" | |
} | |
//grab context | |
ctx := r.Context() | |
//instantiate storage client | |
client, err := storage.NewClient(ctx) | |
if err != nil { | |
log.Printf("error happened!") | |
} | |
defer client.Close() | |
//reference a specific bucket | |
bkt := client.Bucket(bucketname) | |
//query for all files in the selected bucket | |
query := &storage.Query{Prefix: ""} | |
var names []string | |
it := bkt.Objects(ctx, query) | |
for { | |
attrs, err := it.Next() | |
if err == iterator.Done { | |
break | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
names = append(names, attrs.Name) | |
} | |
//log the names of retrieved files | |
log.Printf("Files returned: %s", names) | |
//create a response map that'll convert to a flat JSON payload | |
response := make(map[string]string) | |
response["files"] = strings.Join(names, " , ") | |
jsonResponse, _ := json.Marshal(response) | |
w.Write(jsonResponse) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment