//remove the io.writer argument requirement at top
func uploadFile(bucket, object string) error {
//...snip...
//remove the following at the bottom of the function
fmt.Fprintf(w, "Blob %v uploaded.\n", object)
//shoutout to Derek Perkins on the Go (Gophers) Slack
bucket := "mybucketname" object := "myobjectname" upploadFile(bucket, object)
not enough arguments in call to uploadFile have (string, string) want (io.Writer, string, string)
// Upload an object with storage.Writer. wc := o.NewWriter(ctx) if _, err = io.Copy(wc, f); err != nil { return fmt.Errorf("io.Copy: %v", err) } if err := wc.Close(); err != nil { return fmt.Errorf("Writer.Close: %v", err) } fmt.Fprintf(w, "Blob %v uploaded.\n", object) return nil
Full copy paste ready modified edition and example driver syntax to use for other Go noobs like myself:
func uploadFile(bucket, object string) error {
// bucket := "bucket-name"
// object := "object-name"
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return fmt.Errorf("storage.NewClient: %v", err)
}
defer client.Close()
// Open local file.
f, err := os.Open("./output.txt")
if err != nil {
return fmt.Errorf("os.Open: %v", err)
}
defer f.Close()
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
o := client.Bucket(bucket).Object(object)
// Optional: set a generation-match precondition to avoid potential race
// conditions and data corruptions. The request to upload is aborted if the
// object's generation number does not match your precondition.
// For an object that does not yet exist, set the DoesNotExist precondition.
o = o.If(storage.Conditions{DoesNotExist: true})
// If the live object already exists in your bucket, set instead a
// generation-match precondition using the live object's generation number.
// attrs, err := o.Attrs(ctx)
// if err != nil {
// return fmt.Errorf("object.Attrs: %v", err)
// }
// o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})
// Upload an object with storage.Writer.
wc := o.NewWriter(ctx)
if _, err = io.Copy(wc, f); err != nil {
return fmt.Errorf("io.Copy: %v", err)
}
if err := wc.Close(); err != nil {
return fmt.Errorf("Writer.Close: %v", err)
}
return nil
}
func main() {
//test gcp storage client
uploadFile("bucketname", "objectname")
}