Transferring a JSON array from Google App Engine to Cloud Storage using GO

I am attempting to upload a JSON array to Google Cloud Storage, which is posted by an App Engine application using the code below:

saveData : function saveData() {
  var _this = this,
      save = this.shadowRoot.querySelector('#save-data'),
      subData = JSON.stringify(_this.app.userSession);

  save.url="url";
  save.body = subData;
  save.go();
}

The posted message is processed in the 'go' function with the following code. Currently, I can create a folder in the cloud storage bucket named after the user ID. However, my goal is to copy the entire JSON array (variable f in the code) into this folder. When I tried using io.Copy(wc, f), I encountered the error message below:

cannot use content (type userData) as type io.Reader in argument to io.Copy: userData does not implement io.Reader (missing Read method)

Clearly, there is something incorrect in my implementation, and as a newcomer to Go programming, I'm struggling to find a solution. Can anyone provide assistance?

package expt

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"
    "golang.org/x/net/context"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "google.golang.org/appengine"
    "google.golang.org/appengine/file"
    "google.golang.org/appengine/urlfetch"
    "google.golang.org/cloud"
    "google.golang.org/cloud/storage"
)

var bucket = "expt"

func init() {
    http.HandleFunc("/", handleStatic)
    http.HandleFunc("/save", saveJson)
}

...

// Additional code continues here

Answer №1

This piece of code appears to be quite perplexing, but it seems like you are attempting to achieve the following:

func (d *saveData) createFile(fileName string, content userData) {
    wc := storage.NewWriter(d.ctx, bucket, fileName)
    wc.ContentType = "text/plain"
    d.cleanUp = append(d.cleanUp, fileName)

    //*** new code *******
    io.Copy(wc, content)
    //********************

    if err := wc.Close(); err != nil {
        d.errorf("createFile: unable to close bucket %q, file %q: %v", bucket, fileName, err)
        return
    }
}

You cannot directly write an object to a file; it must be encoded first. It seems like you intend to use JSON. You could approach it like this:

bs, err := json.Marshal(content)
if err != nil {
  return err
}
io.Copy(wc, bytes.NewReader(bs))

However, it would be more efficient to utilize json.NewEncoder:

json.NewEncoder(wc).Encode(content)

Simplifying your createUserFolder function is also possible (no need for a buffer to concatenate strings):

func (d *saveData) createUserFolder() {
    content := testA(d.r)
    d.createFile(content.id + "/")
}

Regarding testA, I am unsure of its intended purpose, but it can be streamlined as well:

type UserData {
  ID     string `json:"id"`
  Age    string `json:"age"`
  Gender string `json:"gender"`
}

func testA(r *http.Request) UserData {
  defer r.Body.Close()
  var obj struct {
    User UserData `json:"user"`
  }
  err := json.NewDecoder(r.Body).Decode(&obj)
  if err != nil {
      log.Println("Error: %s", err)
  }
  return obj.User
}

By using uppercase field names, JSON can handle the conversion for you.

There likely is more refactoring that can be done, but these suggestions should give you a good starting point.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the `filterBy` function with a custom select list that changes dynamically

I'm currently in the process of constructing a form with an extensive selection of drop-down items utilizing vue.js. My approach involves implementing the dynamic select list as detailed in this documentation: However, I am interested in providing us ...

Obtaining data from the following entry in JSON format using the Twitter API

I am currently developing a webpage that showcases user tweets, however I want to visually represent the gap in time between each tweet by displaying empty spaces. I have been struggling with the logic of how to achieve this task and haven't made muc ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

Creating a JSON Response Using PHP API

I created a basic JSON response to test the functionality of an AJAX request on a mobile device. Using a local domain called test.local, I generated a json response. header("Content-Type:application/json; charset=utf-8"); echo json_encode(array('nam ...

Vanilla JavaScript - Conceal all remaining div elements

I have a situation where multiple divs are only visible after clicking a link. How can I ensure that when one div is clicked, all others are closed so that only the clicked one remains visible? Currently, I am using the following JavaScript: functio ...

Encountering a problematic JQuery Ajax request to a RESTful API

I am currently in the process of trying to authenticate against demo webservices that were developed by one of my colleagues. While Cross-origin resource sharing is allowed and functions perfectly when I attempt to call from the Advanced Rest Client plugin ...

Using Nodes to Populate an Array with References to Objects

How can I populate the courses of a Student in StudentSchema with courses (Object_id) from Course in CourseSchema that belong to the same major as the student? let StudentSchema = new Schema({ _id: new Schema.Types.ObjectId, emplId: { type: ...

If you refer to a function, are you personally calling the function or asking the reference to call it?

From what I understand, and please correct me if I'm mistaken, when a variable is assigned to a function in the form of a function expression, it doesn't hold the function in the same way that it holds a primitive value. The variable simply refer ...

Troubleshooting problem with list rendering in a Nativescript-vue GridLayout

As a newcomer to nativescript, I am utilizing GridLayout in an attempt to optimize layout nesting for better performance. In my template, I have an image followed by a vertical list of four items next to it. However, only the first item on the list is visi ...

The method for retrieving values and $id from a $firebaseArray using angularJS

Hey there, I'm fairly new to working with Firebase and I seem to be stuck on a problem that I can't find a solution for despite looking in many different places. Here is the structure of my Firebase database: I am trying to retrieve data from a s ...

Angular.js is experiencing difficulties when using the input value attribute in conjunction with ng-model

I've been hard at work on an app that allows users to edit items, with those changes updating in a database. To prevent empty form submissions, I automatically fill the input fields with the current item's information. form.form-update(method="p ...

Utilize PowerShell to access JSON fields by name through converting a string to JSON

How can I retrieve the value of $body.uuid? Here is my attempt: $body = @" { "uuid": "Test07", "subject": "Template07-Subject", } "@ $bodyJSON = ConvertTo-Json $body Write-Host $bodyJSON Write-Host "uuid=$($bodyJSON.uuid)" Write-Host "uuid=$($body ...

The execution of JQuery/Javascript is restricted to only the initial condition within a Visualforce page utilizing the apex:outputpanel tag

After using only JavaScript for some time, I decided to try out jQuery. However, I'm facing an issue with executing a jQuery function. It seems that only the first condition in my code (the first IF) is being executed, while the second one (the second ...

The environmental variables stored in the .env file are showing up as undefined in Next.js 13

I am having trouble accessing the environment variables stored in my .env.local file within the utils folder located in the root directory. When I try to console log them, they show as undefined. console.log({ clientId: process.env.GOOGLE_ID, clien ...

When trying to apply styles using ng-style attribute with jQuery, Angular does not seem to

Check out this plunker showcasing the issue : http://plnkr.co/edit/1ceWH9o2WNVnUUoWE6Gm Take a look at the code : var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { console.log('yeah'); ...

How can I most effectively establish defaultValues for react-hook-form in this scenario?

I am working on a static Next.js website with only frontend functionality. In the pages/feedback/[id]/edit.tsx page, I need to dynamically retrieve an id and set default values in a nested FeedbackForm component. export const FeedbackForm = ({ editing }: { ...

Embed schema information into HTML tags using JavaScript

Is there a way to insert text, specifically schema data, into an HTML div tag using JavaScript? While I know how to modify existing values within a tag like class, href, and title, I am struggling to find a method to add something entirely new. Essentiall ...

Unable to send a Json Array in the body of a Restassured request - encountering java.lang.IllegalStateException: The content is not a valid JSON Object

I'm attempting to send a list of objects as the body in a restassured request: Transaction transaction1 = new Transaction(); Transaction transaction2 = new Transaction(); List<Transaction> transactionList = new ArrayList<Transaction>(); t ...

Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code: interface TestInterface { id: number; text: string; } const testInterfaceImplementation: TestInterface = { id: 1, text: 'sample text' }; console.log(testInterface ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...