Questions tagged [go]

Go is a powerful programming language that embraces open-source principles. Its syntax draws some inspiration from the widely used C language, while offering unique features of its own. Unlike many other languages, Go is statically typed but includes limited dynamic typing capabilities. This innovative language incorporates automatic memory management, which simplifies the development process. Moreover, it boasts built-in concurrency primitives and supports variable-length arrays known as slices. Additionally, Go offers a vast standard library that helps developers accelerate their projects.

Iterate over the keys and values in a JSON object while simultaneously replacing any specified values in Golang

Is it possible to iterate through all the keys and values of a JSON object in Golang, identify a specific value based on a match with either the key or value, replace that value, and then create a new data structure with the updated value? I came across a ...

Compiling SSR index.html file is in progress

Currently using the Go and VueJS stack, but encountered an issue with SSR. The index.html is precompiled with GO to generate meta tags (using html/template) {{ range index . "metaTags" }} <meta {{.Key |safe }}='{{ .Name }}' {{ .Ty ...

Transform JSON attribute string into a JSON data structure

Here is a struct I am working with: type ResponseStatus struct { StatusCode int Message string Data string `json:"data"` } type Pets struct { Id int `json:"id"` Name string `json:"name"` Age int `json:"age"` ...

Decoding into identical structure with distinct JSON identifier

I have encountered a situation where I need to manipulate JSON data by performing certain transformations and then send it by marshaling. However, my requirement is to change the variable name in the final marshaled JSON. Is it possible to marshal the dat ...

Is there a way to exclude a field during json.Marshal but not during json.Unmarshal in go language?

struct Alpha { Label text `json:"label"` ExcludeDuringSerialization string `json:"excludeDuringSerialization"` } func SerializeJSON(obj interface{}){ json.Serialize(obj) } How can I exclude the ExcludeDuringSerializa ...

Looking to set up a web service that can handle incoming posts, but unsure about the best way to send a response back to jQuery

Good morning, I have a Go code that processes a JSON post request and performs certain actions. However, I am looking to send back either the result or a message to jQuery. package main import ( "fmt" "log" "net/http" "encoding/json" ...

Utilize the Golang Selenium library to establish a connection with a Selenium server and run headless Chrome

I recently started using the Go selenium package available at this link Currently, I have set up a headless chrome + selenium-server configuration within a docker container on localhost:4444 The server appears to be running smoothly as I am able to acces ...

"Unlocking the power of JSON with Go's field case

Just starting out with Go and I'm having trouble fetching and marshalling json data into a struct. The data format I'm working with is as follows: var reducedFieldData = []byte(`[ {"model":"Traverse","vin":"1gnkrhkd6ej111234"}, {"model":"TL","vin" ...

Creating HTML in Go using data from a struct

I have an HTML file named email.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shareholder</title> </head> <body> <h1> {{.PageTitle}} </h1> ...

Struggling to interpret JSON and retrieve the desired value

Just starting out in Go Lang and looking to parse a JSON structure like the one below to extract all objects in the records array. [ { "records": [ {"name":"value"},{"name":"value"} ] }, { "records": [ ...

Step-by-step guide to creating a custom web browser version using Selenium in Go

package main import ( "fmt" "time" "github.com/tebeka/selenium" "github.com/tebeka/selenium/chrome" ) func main() { // Launch Chrome browser service, err := selenium.NewChromeDriverService("./chromedriver", 4444) if err ...

Extracting a deeply nested JSON array from a document

After finding a JSON file named sample.json, I discovered that it contains an array of JSON objects with timestamps, extra data IDs, and event information. Here's a snippet: [ { "time": "2021-01-04T00:11:32.362Z", "extra_data": { "id": "123" }, ...

Use Go lang with Gin to return an empty array instead of null for JSON responses

I have a struct: type ProductConstructed struct { Name string `json:"Name"` BrandMedals []string `json:"BRAND_MEDALS"` } When I use gin to return my object: func constructProduct(c *gin.Context) { var response ProductConst ...

What is the best way to exclude fields when unmarshalling JSON in a Golang application?

In my program, I utilize a JSON file to set up the arguments and also use the flag package to configure the same arguments. Whenever an argument is parsed by both the JSON file and the flag at the same time, I prefer to use the argument parsed through the ...

Guide to organizing code for a REST API using Express.js

Recently, I have been working on developing a REST API using Sails.js. As I outlined the resources needed for my application, it struck me that many frameworks (based on Express) are proficient at handling single resources. However, in most cases, I found ...

Guide on deploying a NextJs frontend with Golang (Go) and gorilla/mux

After following a guide to serve a NextJs front-end single-page application using Golang and the native net/http package, I decided to switch to using gorilla/mux. Here is my updated main function: func main() { // Root at the `dist` folder generated ...

adding personalized data types in a configuration settings file

I've recently been experimenting with this Go-based forum software that comes with a configuration file requiring specific values as outlined in the main.go file below. Initially, I attempted using an empty string "" for the oauth credentials while testing ...

Encountering CORS Issue with Golang and Gin following a Redirect Situation

I am currently working on implementing Google OAuth2 in my Go web server using Gin. I have integrated two new endpoints - /google/sign-in and /google/callback. The former receives the request and redirects to the Google auth URL, while the latter is trigge ...

Can a non-empty response result in a 204 status code?

Utilizing the http module, I have a request from the Front-End developers team to return an empty list and status code 204 when there are no search results. Here is my attempt: AllPosts := logic.MergedSearchSearchPost(params) if len(AllPosts.Posts) == 0 { ...

Is it possible to transmit a MongoDB query to another system by converting it to JSON and later decoding it into BSON? If so, how can this be achieved in the

I have the need to transfer a MongoDB query to a different system and I would like to utilize the MongoDB Extended JSON for this purpose, especially because my queries involve date comparisons. The main issue at hand is transferring a MongoDB query genera ...

Decoding JSON data in golang

Just starting out with golang here. I'm looking to decode some JSON data as shown below: { "intro": { "title": "The Little Blue Gopher", "story": [ "Once upon a time, long long ago, there was a little blue gopher. Our little blue fr ...

Is it possible to transmit a struct Type in Golang?

As a newcomer to Golang, I seek forgiveness for my lack of knowledge and potential incorrect approach. Currently, I am working on developing a Terraform provider for an internal service. This involves unmarshalling JSON data into pre-defined Struct Types ...

Implementing Golang Template with Multiple Structs for Flexible

I currently have a structured data with a JSON field that looks like this: data := &Data{ Title string Content json.RawMessage } The template for this data is as follows: template = For {{Title}} - created at: {{CreatedAt}} / updated at: {{Updated ...

What is the process for decoding data into an embedded struct?

Is there a way to utilize .Decode() on a response body to populate a struct without needing to determine the specific type of struct beforehand? I have a versatile struct called Match, designed to store information about various games, like a match in For ...

What OAuth Flow is Suitable for a Separated Frontend and Backend Structure?

My architecture consists of a NextJS frontend and Golang backend with an authentication system using JWTs and an internal user/password database. I am now looking to add OAuth sign-in alongside the current JWT system, while still maintaining API calls with ...

Is it necessary for libraries in Golang to be non-blocking?

Is it true that non-blocking web servers like node.js, eventmachine, and tornado can become unresponsive if they encounter a blocking library? Does the same hold true for Golang? If one goroutine becomes blocked, will another automatically be allocated C ...

The issue with Go Code is that it fails to display the JSON data received from a jQuery

Problem Description The issue I am facing is that Go Code is not displaying the posted JSON value from jQuery AJAX. Main Go Code routing := chi.NewRouter() routing.Post("/authenticate", AuthenticateRouter) Go Code Snippet func AuthenticateRouter(w http. ...

"Utilizing Golang's encoding/json package to include null values during marsh

Hello, currently I am using Golang for encoding/json and encountering an issue where the JSON error is returning as null: {"user_message":"Can't find any Query with those parameters","application_context":"GroupsRepository.GetGroupsByQuery: Applicati ...

Is it better to use a single struct or multiple structs for handling nested JSON

When working with nested JSON in Go, I often find myself wondering about the most correct or idiomatic way to create the struct it's parsed into. Single struct: type myStruct struct { Fields struct { Struct0 struct { Field0 string ...

Decoding a JSON array in golang

Can you help me understand why golang unmarshalling is returning a nil result for one decoding attempt of a JSON array, but successful in another? I'm confused about what could be causing this difference. Is it a mistake in the code or is it expected behav ...

Using Go to persist JSON logs by creating and validating unique filenames repeatedly

I am relatively new to Go and I find myself regularly receiving a small (~1KB) JSON file from an API that acts as a log. My goal is to preserve each of these files for future reference. Instead of using a database, which seems unnecessary for this task, I ...

What is the best way to deliver a file in Go if the URL does not correspond to any defined pattern?

I am in the process of developing a Single Page Application using Angular 2 and Go. When it comes to routing in Angular, I have encountered an issue. For example, if I visit http://example.com/, Go serves me the index.html file as intended with this code: ...

Is Bcrypt password encryption for Golang also compatible with Node.js?

I have successfully implemented user authentication on my website using Node.js and Passport. However, I am now looking to migrate to Golang and need to figure out how to authenticate users using the passwords stored in the database. The encryption code ...

Transform the terraform resource data, which is in the form of a map containing keys of type string

I am currently developing a custom terraform provider and have encountered an issue. I'm attempting to convert a schema.TypeList field into a struct. Here is what the TypeList looks like: "template": { Type: schema.TypeLi ...

Contrast the dissimilarities between JSON and alternative errors

encoder := json.NewEncoder(writer) error := encoder.Encode(struct { RequestMethod string `json:"request_method"` QueryResults []interface{} `json:"query_results"` TimeInCache int `json:"time_in_cache"` }{RequestMethod: pro ...

Using JSON as a response in a Beego controller

Just starting out with Beego and attempting to generate a JSON response on a specific route. Below is how my controller is set up: package controllers import ( "github.com/astaxie/beego" ) type ErrorController struct { beego.Controller } type ...

Is it feasible to model general JSON arrays in a struct using Go?

Is it possible to Marshal/Unmarshal a struct in Go? type MyType struct { Items <What should be included here?> `json:"item"` } An example JSON document that needs to be handled is {"items":["value1", {"x":"y"}, "value3"]} I am new to Go ...

What possible problem could cause the error: an invalid character '-' appearing after a top-level value?

Utilizing the go-jmespath Golang library for querying a json file, my code is structured as follows: package main import ( "encoding/json" "log" "github.com/jmespath/go-jmespath" ) func main() { var jsonBlob = []byte(`[ { "o ...

Discover the most efficient method for extracting specific information from a JSON file by utilizing the existing attributes

I've been tasked with creating a basic RESTful service in Go that retrieves data for a specific book based on its ID. type Book struct { ID string `json:"id"` Isbn string `json:"isbn"` Title string `json:"title"` Author *Author ` ...

Changing a rest api POST request from JSON to form-data in Golang using the Gofiber framework

My current code successfully handles JSON in the body of a POST request, but I am now looking to switch to using form-data instead. This is my existing code: func Signin(c *fiber.Ctx) error { var data map[string]string if err := c.BodyParser(& ...

The Unmarshall function must throw an error if the JSON input structure is incorrect

I encountered an issue with struct A and B while unmarshalling JSON strings. When a JSON string meant for struct A is unmarshalled correctly, it works fine. However, if the same JSON string is mistakenly unmarshalled into struct B, it still succeeds (which ...

Guide on utilizing node-modules installed via npm in a template

I am attempting to utilize a library installed via npm in the Go template. By running 'npm install three', I have successfully installed the required three libraries, which are saved in the root folder as depicted in the provided screenshot below. https: ...

Mastering the Art of Binding Variables to Various JSON Types in GOLANG

When it comes to the naming convention of variables in a database, it is customary to use full_name. However, in Postman, the convention dictates using fullName instead. type Person struct { FullName string `json:"fullName"` } Nevertheless, ...

Guide to specifying optional JSON fields in Golang structures?

In my programming practice, I have a preference for using pointers with primitive data types in my structs. By doing so, I ensure that when I use json.Marshal to convert them, any nil fields are represented as "field": null in the resulting JSON string. Ho ...

Guide on creating a readUInt16BE function in a Node.js environment

Looking to implement the readUint16BE function in node.js, here's how it is declared: buf.readUInt16BE(offset, [noAssert]) Documentation: http://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset_noassert This function reads an unsigned 1 ...

The Go programming language's counterpart to the npm command "npm install -g

I am looking to install a compiled Golang program so that I can run it with a bash command from any location on my computer. Is there an equivalent of the npm global installation for Golang? For example, in nodejs, we use "npm install -g express" to global ...

When trying to access [Apiurl] from Vue and Golang, an error occurs due to the CORS policy blocking the XMLHttpRequest. The request header field 'authorization' is not allowed

As a newcomer to Vuejs and golang, I encountered an issue when attempting to send an Authorization token through the header while making an API call from Vue Axios. The error message that was displayed is as follows: "Access to XMLHttpRequest at 'htt ...

MD5 encryption for node applications: a guide to compatibility

I am currently in the process of converting a node service to Go. In order to do this, I require a compatible md5 hash generator (not for password storage!). However, I am experiencing different results in this scenario: When creating md5s in Node, the cr ...

Need help transferring information from your Go Web-Server to your Vue.js frontend? Having trouble with a http-post error of 404

I am currently exploring the process of transferring data between a lightweight Golang web server and a Vue.js frontend. This is the content of the server-gorillamux.go file: ... // Your original code here And this is the content of the /src/components/ ...

Manage how data is presented in a JSON format using Go's structures

Currently, I am working on a nested structure in golang and trying to manage which substructures should be displayed in JSON. For example, if I only want to show the treeid and name fields from Citrus, I attempted the following notation, but it still prin ...

Is there a way to deserialize JSON into an empty struct within a function without losing its type information?

Can someone help me with a question regarding JSON unmarshalling? I am facing an issue where the type is lost after unmarshalling the data. Here's an example of what I'm experiencing: package main import ( "encoding/json" " ...

Ensuring the data integrity of JSON values during unmarshaling in Go

Dealing with an API that usually returns JSON string values but occasionally provides numbers instead can be tricky. For example, most of the time it looks like this: { "Description": "Doorknob", "Amount": "3.25&q ...

Storing kubernetes secrets securely within GitHub Actions

We are currently implementing the use of github actions, with a focus on securely storing sensitive information like kubeconfig within github's secrets. A GitHub secret has been set up under the name KUBECONFIG1 Steps to Replicate The GitHub secret shoul ...

The property differs when being read from the input stream

This snippet of code is used to test the functionality of listing users in a web application. req := httptest.NewRequest("GET", "/v1/users", nil) resp := httptest.NewRecorder() u.app.ServeHTTP(resp, req) if resp.Code != http.StatusOK { ...

Next client unable to locate cookies in Go web server

I recently updated the authentication method for my Go web server from using Bearer tokens to utilizing cookies. During the login process, I now set a cookie for both the token and refresh token like this: a.AuthRepo.StoreInCookie(res.Token, "token&qu ...

What are some effective measures to defend against a gzip bomb attack on a service

I have a file named test.gzip which contains JSON data. {"events": [ {"uuid":"56c1718c-8eb3-11e9-8157-e4b97a2c93d3", "timestamp":"2019-06-14 14:47:31 +0000", "number":732, "user": {"full_name":"0"*1024*1024*1024}}]} The full_name field in the JSON data c ...

Having trouble extracting JSON from the HTTP response?

Currently, I'm struggling to find a solution in order to properly extract and process the JSON data from . While my code has no issues decoding the JSON data retrieved from , it always returns empty or zero values when directed towards the CoinMarketC ...

Serialization and encoding using json.NewEncoder and json.NewDecoder

I am currently delving into Backend development by constructing a very basic REST API using the gorilla mux library in Go (referring to this tutorial) Here is the code that I have developed so far: package main import ( "encoding/json" "ne ...

What is the equivalent in Go of reading from the PHP standard input stream?

Currently I am in the process of adapting a PHP script that is designed to monitor events on a Linux system through supervisor. Forgive me for possibly asking a naive question, but I am struggling to determine what the equivalent of the following code sni ...

Transform YAML into JSON with no need for a specific structure

Services: - Orders: - ID: $save ID1 SupplierOrderCode: $SupplierOrderCode - ID: $save ID2 SupplierOrderCode: 111111 I am facing a challenge while trying to convert a dynamic YAML string to JSON format. Since the source data ...

Is the NEXTAUTH_SECRET variable equivalent to the backend secret utilized for JWT token generation?

In my current project, I am developing the frontend application using NextJS and incorporating next auth for user authentication with email and password login. The backend is implemented in GoLang as a separate code base. When a user logs in, a request is ...

Guide to decoding a list of interface types from JSON in Golang

In my code, there's a package called variables which contains an interface Variable, and two structs that implement the methods in the interface - NumericalVariable and TextualVariable. Here is how they are structured... package variables type Variab ...

The data payload needed for sending a POST request in JSON format

I am in the process of constructing a body for a POST request relativeurl := "this-is-a-test-url" postBody := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"rela ...

How to decode a JSON object in Golang that contains both trait and data?

I have a dictionary data structure containing words and their meanings in the format {{"word name":"word meaning"},{"word name":"word meaning"},...}. I am attempting to convert this into a map of the words, using the interface{} type. However, I am havin ...

Learning to interpret the attributes of a struct field

One of the key features in my package is the ability for users to define the backend database column name explicitly for their fields, if they choose to do so. Normally, the package uses the field's name as the column name. However, there are cases where ...