Go Language Collective

The official Q&A channel for Google's Go Programming Language.
The official Q&A channel for Google's Go Programming Language.

Questions

Browse questions with relevant Go Language tags

57,070 questions

0votes
0answers
4views

Go - errors.As() not recognising type

I am using a helper function to decode JSON. It returns a custom error type that is populated with the reason why it could not parse the JSON and the HTTP code I should return. package dto type ...
user avatar
  • 1,923
0votes
0answers
9views

K8s operator listen to secret change

We have created few month ago controller which run great using kubebuilder, Few weeks ago we added a “listener” to a secret which when the secret is changing (secret properties) The reconcile is ...
user avatar
  • 311
-2votes
1answer
11views

Is there a 'protected' analog in golang for accessing an embded structs private methods?

In Java/C++ you can use the 'protected' to make private methods/attributes of base classes accessible from inherited classes. I noticed in Go there doesn't seem to be anything similar. If that's the ...
user avatar
0votes
1answer
7views

using ldflags for giving binary file a version not working in golang

The main.go as follows: package main func main() { println("hello world") } The Makefile as follows: flags=-X main.version=1.5.0 build: go build -ldflags "$(flags)" -o ...
user avatar
-1votes
0answers
18views

create a channel without make function (GO)

The following code works okay func main() { c := make(chan string) go subRountine(c) fmt.Println(<-c) } func subRountine(c chan string) { c <- "hello" } Is there any ...
user avatar
-1votes
0answers
11views

golang - get package from replaced module

I would like to use the latest version of a package in a new function. I can use "replace" to replace the package github.com/stellar/go/ @v2 with github.com/stellar/go/v2; but what i need to ...
user avatar
  • 1,559
0votes
0answers
6views

How do i make go dns lookup force usage of nscd if available?

Is there any way i can force a go binary to perform dns lookup's and get response from the nscd cache on the same host if it is available? I assume it can be forced if i use a custom resolver, but i'd ...
user avatar
-1votes
1answer
12views

errors.Is(err, target error) returns false when the two errors have the same string

This shouldn't fail because the two errors have the same string, but it still fails: if !errors.Is(err, testspec.expectErr) { t.Errorf("Error mismatch, want %v, get %v", testspec....
user avatar
  • 5,176
0votes
0answers
19views

Is safe store jwt payload in global variable for every request in golang?

I build app with JWT authentication in go, I declare global variable to store payload information for every coming request, so the program just need to decode the jwt once on middleware when it pass ...
user avatar
  • 13
0votes
0answers
16views

How to insert package.txt into scripts object of package.json file?

My package.txt contains:- "scripts": { "lint": "eslint --fix .", "lint-check": "eslint .", } I am creating a react app using npx create-...
user avatar
1vote
1answer
24views

Testing In Golang, how to test cache that expires in 30 seconds

I have an interface called localcache: package localcache type Cache interface { Set(k string, v interface{}) error Get(k string) (interface{}, error) } and another file containing its ...
user avatar
  • 39
0votes
0answers
12views

In glog, Why there is no stdout but only stderr in the parameters setting

By default, all log statements write to files in a temporary directory. This package provides several flags that modify this behavior. As a result, flag.Parse must be called before any logging is done....
user avatar
0votes
1answer
24views

Golang returning a default array of structs

When I curl an api I get back a response like this: [{"Hits":25,"Name":"HIT"},{"Hits":87,"Name":"MISS"},{"Hits":15,"Name"...
user avatar
  • 1,239
0votes
2answers
36views

Is there a way to map an array of objects in golang?

Coming from Nodejs, I could do something like: // given an array `list` of objects with a field `fruit`: fruits = list.map(el => el.fruit) # which will return an array of fruit strings Any way ...
user avatar
  • 19.3k
0votes
2answers
42views

How do you write a generic Go function that allows pointers to multiple primitive types?

I'm trying to use Go generics to write a function to cut down some of the boilerplate if/else blocks in our code. I came up with something that works for a single type parameter as follows: func ...
user avatar
  • 13k
1vote
0answers
15views

GOINSECURE to enable http downlaods on packages from Github

I'm developing a CLI app at work in order to automate a couple tedious tasks, to do this I need to install a couple packages like gotp. I noticed that installing this new package into my project this ...
user avatar
  • 973
1vote
1answer
20views

How to change stdio of a given process (i.e. not current process)?

Here is a way to change stdio of a given process by external tools such as gdb: https://www.baeldung.com/linux/redirect-output-of-running-process My question is, how can I do this programatically? I ...
user avatar
  • 1,074
0votes
2answers
23views

Golang - many in use connections

#golang #oracle Im trying to understand how the Max connection works. Basically I have this db configuration: params.MinSessions = 5 params.MaxSessions = 6 params.SessionTimeout = 0 params.WaitTimeout ...
user avatar
2votes
0answers
11views

Artifactory not sourcing go module major versions correctly

I am releasing a major version update to a go module but Artifactory will not pull the version when incremented by go module requirements. There post here and here, say to create a v2/ directory and ...
user avatar
  • 467
-1votes
1answer
22views

Golang panic: interface conversion: interface {} is nil, not string

I have tried to create CA configuration file, certificate and private key, I am using cfssl command in go and try to simulate same command from cfssl gencert -initca ca-csr.json | cfssljson -bare ca ...
user avatar
0votes
1answer
31views

Refactor main.go to another packages

Good, first of all, I am learning Go and I am a deaf person and English is not my main language. I'm having a hard time understanding the videos, even though they are subtitled, I don't understand ...
user avatar
0votes
0answers
32views

How do I process the answer to a question?

My handler callback: func (b *Bot) HandleView(bot *tgbotapi.BotAPI, update tgbotapi.Update) error { zap.L().Debug("handler", zap.Reflect("HandleView", update)) smileSearch ...
user avatar
1vote
1answer
64views

In Go 1.18 strings.Title() is deprecated. What to use now? And how?

As suggested here names of people should be capitalized like John William Smith. I'm writing a small software in Golang which gets last and first name from user's form inputs. Until Go 1.18 I was ...
user avatar
  • 1,325
0votes
2answers
37views

Need to pass empty slice in [] this format and not as ""

I have a api with one attribute of body as type Reg struct{ Env []string json:"env" } while calling the api I need to pass value of "env" as optional parameter. i.e. in ...
user avatar
0votes
0answers
25views

unexpected status code when using httputils.ReverseProxy

I need to proxy requests to another service. Before doing this, a pre-flight request needs to be performed to get a token and some cookies. When I do it manually, with http.Client, it works as ...
user avatar
  • 8,180
-1votes
1answer
27views

Go build process seems to erroneously infer the wrong version of Go:

I have built a simple library to run a pool of workers in Go and a file (to test it) which uses said library, (see code hereunder). When I use the local version of the library (stored in $GOROOT/src/.....
user avatar
0votes
1answer
21views

Golang: Get the pointer to a struct using reflection

I'm trying to write code that recursively traverses a struct and keeps track of pointers to all its fields to do basic analysis (size, number of references, etc). However, I'm running into an issue ...
user avatar
  • 179
0votes
1answer
25views

How can I compile this golang type paramater code?

go version: 1.18 func main() { colly.NewCollector().OnXML( "//*[contains(@class,\"prdList\")]//li/div/div[@class=\"prdImg\"]/a", func(element *colly....
user avatar
0votes
0answers
31views

Running a custom command with Kubernetes go client

I am new to both Golang and Kubernetes, but I am trying to see if there is a way to run a custom command using the go-client library. The specific command I am trying to run is: kubectl exec -it ...
user avatar
0votes
1answer
43views

recursively iterate struct array in Go

I need to iterate over all the answer options from a json file: {"questions": [ {"id": 1, "question": "What is your marital status?", "answer&...
user avatar
-1votes
2answers
41views

Ho to remove a value of a key in a map?

I have a a map which has a key and multiple values for that key. What i want to do is delete a single value from values. Example: map1 := make(map[string][]string) str1 := []string{"Jon", &...
user avatar
  • 11
0votes
0answers
22views

go mod vendor does not pull packages to vendor folder

Im coming back to golang after a couple of years and I've forgotten how go modules are supposed to work... This is my main file - sync.go package main import ( "database/sql" "...
user avatar
  • 1,449
1vote
0answers
16views

Inject headers into httptest.Recorder so echo context can see them in Golang

I have some tests that inject headers into Echo like this: func test() { request := httptest.NewRequest(http.MethodGet, "/", http.NoBody) recorder := httptest.NewRecorder() ...
user avatar
  • 3,985
2votes
1answer
29views

How to obtain MongoDB version using Golang library?

I am using Go's MongodDB driver (https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.8.0/mongo#section-documentation) and want to obtain the version of the mongoDB server deployed. For instance, if it ...
user avatar
-1votes
1answer
33views

Can an interface method accept/return a struct while allowing the use of structs with the same shape to satisfy it?

I would like to create a library that exports a function that defines its own dependencies without consuming types from an external package (excluding std lib). The issue is, if my dependency is an ...
user avatar
  • 4,879
0votes
1answer
14views

Docker image build failed: go mod download: reading https://api.bitbucket.org/2.0/repositories/***/***?fields=scm: 404 Not Found

Building of Docker image started to fail just now. It was working yesterday. This is the error coming: Step 14/31 : RUN go mod download ---> Running in 9dcd36a5e81b go mod download: reading https:/...
user avatar
0votes
1answer
21views

Golang post request to NodeJS API gets stuck on formidable

For some reason, my post requests made in go with below code gets stuck on my express api using express-formidable. I tried removing the use of formidable in the api app.use(formidable()) and it ...
user avatar
  • 981
0votes
1answer
17views

kafka commit during rebalancing

The scenario: Kafka version 2.4.1. Kafka partitions are processing messages actively. CPU usage is less, memory usage is mediocre and no throttling is observed. Golang Applications deployed on k8s ...
user avatar
1vote
0answers
49views

Does golang's generic help reduce redundant codes using interfaces to implement interfaces?

The following code is used to implement the String() and Json interfaces for many types. Notice that, in fact, as long as you implement a LabelSet() interface, you can implement the String() and Json ...
user avatar
0votes
1answer
48views

Get environment variables from pseudo-terminal

I have a program that uses https://github.com/creack/pty to create pseudo terminals. Given a command, it creates a file object where you can read and write and it will work as stdin and stdout. I use ...
user avatar
0votes
0answers
16views

GO - Golang AES128 ECB Decryption

I find the snippet of the code from https://stackoverflow.com/questions/24072026/golang-aes-ecb-encryption/71614065?noredirect=1#comment126568172_71614065in golang to decrypts AES-128 data in ECB (...
user avatar
1vote
1answer
24views

AES 256 CTR Encryption in Golang Decrypt in Node JS with CryptoJS and the Key is String (not WordArray)

I have to send data by using golang to existing (legacy) service with nodejs encryption that will decrypt data using AES CTR mode with Crypto JS libray. I have made some code as follow (the key ...
user avatar
  • 63
-2votes
1answer
26views

Golang - Type decimal.Decimal convert

Trying to convert type decimal.Decimal to string func main() { a := strconv.Itoa(Price) // Price of type decimal.Decimal fmt.Printf("%q\n", a) } Problem: cannot use (variable of ...
user avatar
0votes
0answers
16views

Run Gazelle in dry-run or warn mode

Context Is there a way to have gazelle run in dry-run mode? I'd like to create a CI job that runs gazelle with dry-run and fails if gazelle finds any changes. Something like this $ bazel run //:...
user avatar
  • 621
-2votes
2answers
51views

How can I use dynamic key for struct in Go lang?

I have this struct for get data from Json string. type msg struct { Msg1 string `json:"msg1"` Msg2 string `json:"msg2"` Msg3 string `json:"...
user avatar
  • 299
1vote
1answer
26views

Unable to find reason for go deadlock

Unable to find a reason as to why this code deadlocks. The aim here is make the worker go routines do some work only after they are signaled. If the signalStream channel is removed from the code, it ...
user avatar
  • 48
-1votes
2answers
24views

GoLang: Working with map in Anynomous structs

I am trying to understand how to use maps in anonymous structs. My code is as below places := struct { Country map[string][]string }{ make(map[string][]string)["india"] := []...
user avatar
  • 4,747
0votes
1answer
20views

How to schedule cron sending message to ActiveMQ broker using Golang?

I am using Golang. I want to send message (scheduled with cron) to ActiveMQ Broker like this document (AMQ_SCHEDULED_CRON) When looking up this document. I did not find anything mentioning about ...
user avatar
  • 707
-2votes
1answer
30views

How to Import https://github.com/go-test/deep into Your Golang Test

I'm new to Golang. My go version: 1.17.8 Trying write tests to compare strcuts. Found this lib can show you which fields exactly equivalent. So thought of using it over reflect.DeepEqual Here's my ...
user avatar
0votes
2answers
41views

How to calculate between days?

i'm new in golang. Can u teach me how to calculate between two days. This is my code, i want to calculate betweet Time and Created At type ActivityHistoryData struct { AgentId uint ...
user avatar
  • 1


15 30 50 per page
1
2 3 4 5
1142