Questions tagged [go]

18841 questions
1

votes
3

answer
321

Views

golang multiple assignment evaluation

I'm confused on the concept of multiple assignment. Given the following code: func fibonacci() func() int { current, next := 0, 1 return func() int { current, next = next, current+next return current } } How is the assignment evaluated, given the fact that both variables appear on both the left and...
Jeroen Jacobs
1

votes
1

answer
574

Views

How to check if all fields of a *struct are nil?

I'm not quite sure how to address this question, please feel free to edit. With the first code block below, I am able to check if a all fields of a struct are nil. In reality however, the values injected in the struct, are received as args.Review (see second code block below). In the second code blo...
Asten Mies
1

votes
1

answer
1.3k

Views

access golang struct field with variable

For reference: example here I am trying to access a struct field using a variable key, to explain in PHP you can do the below. $arr = ['test' => 'foo']; $key = 'test'; $result = $arr[$key]; Or in Javascript you can do the below const obj = {'test': 'foo'} const key = 'test' const result = obj[key] I...
Sam White
1

votes
1

answer
857

Views

Passing a function with parameters to time.AfterFunc

time.AfterFunc() accepts a duration and a function to be executed when that duration has expired. But the function cannot be a function that accepts parameters. For example: The following function cannot be passed: func Foo (b *Bar) {} Although, it is possible to initialize a new function that calls...
sieberts
1

votes
1

answer
233

Views

The filename, directory name, or volume label syntax is incorrect - when trying to readfile in go lang

I want to read contents of text file. When I am passing the file name as string like this: stream, err = ioutil.ReadFile('sample.txt') its working. Its even working if do in this way: filename := 'sample.txt' stream, err = ioutil.ReadFile(filename) But when I get the value of filename from string a...
Varun Gupta
1

votes
2

answer
654

Views

Override Go Method in Tests

So I have this Client struct that has a method UserByID that makes a HTTP request to an endpoint for a User. I want to unit test this function but also not make an actual HTTP request in the function c.Request. I want to stub that function with a response and error I can control. func (c Client) Use...
KA01
1

votes
2

answer
1.1k

Views

Fixing import cycle in Go

So I have this import cycle which I'm trying to solve. I have this following pattern: view/ - view.go action/ - action.go - register.go And the general idea is that actions are performed on a view, and are executed by the view: // view.go type View struct { Name string } // action.go func ChangeName...
flooblebit
1

votes
2

answer
1.7k

Views

Golang: Connect with postgreSQL schema

I am looking to connect and query to a PostgreSQL. But I only want to connect to a particular Schema. As per the doc (JDBC) we can use jdbc:postgresql://localhost:5432/mydatabase?searchpath=myschema or update As of 9.4 you can specify the url with the new currentSchema parameter like so: jdbc:postg...
Abhishek Soni
1

votes
1

answer
721

Views

Golang mapstructure not working as expected

I am trying to decode a map[string]interface{} to a struct, but the 'hours' field is not getting populated. I am using https://github.com/mitchellh/mapstructure for decoding. This is the struct: BusinessAddRequest struct { Name string `json:'name'` Phone string `json:'phone'` Website...
Pramod Shashidhara
1

votes
1

answer
303

Views

Implementation of Go-routines vs Task Parallel Library

I have just started learning Go. The strength of Go lies in goroutines for handling multiple concurrent connections. It was mentioned Goroutines can be considered as light-weight threads (but not actually threads) which can grow/shrink stack size and these are multiplexed into multiple os threads....
user3205479
1

votes
1

answer
598

Views

Flutter parsing json with DateTime from Golang RFC3339: FormatException: Invalid date format

When trying to read json files generated with golangs json package in Dart / Flutter I noticed that parsing dates produce an error: FormatException: Invalid date format An example is the following json generated on the Go server: { ... 'dateCreated': '2018-09-29T19:51:57.4139787-07:00', ... } I am u...
Oswin Noetzelmann
1

votes
3

answer
839

Views

go routine for range over channels

I have been working in Golang for a long time. But still I am facing this problem though I know the solution to my problem. But never figured out why is it happening. For example If I have a pipeline situation for inbound and outbound channels like below: package main import ( 'fmt' ) func main() {...
Himanshu
1

votes
2

answer
69

Views

Difference between method signatures of structs

As a programmer coming from other languages like C++, I find it rather strange that go allows to specify methods for structs that allow either a pointer or an instance as a parameter. According to go by example once could use either of them if we didn't want to modify the origin: Go automatically ha...
muffel
0

votes
0

answer
16

Views

How to mock GCP's storage in golang?

I'm really new to mocking third-party library in go, I'm mocking cloud.google.com/go/storage right now I'm using mockery. This is my current interface: //Client storage client type Client interface { Bucket(name string) BucketHandle Buckets(ctx context.Context, projectID string) BucketIterator } //B...
kkesley
1

votes
1

answer
636

Views

Mongo-Go-Driver Failing to Connect

So I am trying to use https://github.com/mongodb/mongo-go-driver to connect to a mongo database in golang. Here is my connection handler: var DB *mongo.Database func CreateConnectionHandler()(*mongo.Database, error){ fmt.Println('inside createConnection in database package') godotenv.Load() fmt.Pri...
Peter Weyand
1

votes
1

answer
66

Views

Golang how to check struct field int is set? [duplicate]

This question already has an answer here: How check if a property was set in a struct 3 answers With golang script, I have a struct type and json below struct admin type Admin struct { Id string `json:'id'` Status int `json:'status'` } json jsonData { 'id': 'uuid' } When I using json.Unmarshal(json...
Hung Quyen
1

votes
2

answer
51

Views

How to omit some parameters of structure Gin gonic

I have big structure with more than 50 params type Application struct { Id int64 `json:'id'` FullName string `json:'fullName,omitempty'` ActualAddress string `json:'actualAddress,omitempty'` ..... } I use gin-gonic and when I return application I need to omit so...
mondayguy
1

votes
1

answer
56

Views

Map seems to drop values in recursion

I've been working on a problem and I figured I would demonstrate it using a pokemon setup. I am reading from a file, parsing the file and creating objects/structs from them. This normally isn't a problem except now I need to implement interface like inheriting of traits. I don't want there to be dup...
1

votes
1

answer
54

Views

trying to understand golang chan cause crash or do something else

The following is a example from https://golang.org/ref/mem: var c = make(chan int) var a string func f() { a = 'hello, world'
Geln Yang
1

votes
1

answer
27

Views

JSON decoded value is treated as float64 instead of int

I have a json response from a api as map[message:Login Success. userid:1] Server: c.JSON(200, gin.H{'message': 'Login Success.', 'userid': 1}) Client: var result map[string]interface{} json.NewDecoder(resp.Body).Decode(&result) msg, ok := result['message'].(string) if !ok { msg = 'Something went wro...
majidarif
1

votes
1

answer
44

Views

How to add an element to a json field array in Postgres

I'm trying to append data to an array that belongs to a json field in postgres. While using pgAdmin I know the following query works. ~ UPDATE lesson SET data = jsonb_set (data, '{pages, 999999}', '{'pageNum': 2, 'pageType': 'voc'}', True) WHERE id = 2; I am simply trying to get the above query to...
Joseph Vargas
1

votes
2

answer
42

Views

How to add into map in range loop

package main import ( 'fmt' ) func main() { m := make(map[int]int, 4) m[1] = 0 m[2] = 0 for k, _ := range m { i := 10 + k m[i] = 0 } fmt.Println(m) fmt.Println('len:', len(m)) } This code returns: 8 or 10 or 6 as length of map after loop. Video is here, playgroud here. I see that new added elements...
Vladimir Kovpak
1

votes
1

answer
59

Views

golang bufio.Read or bufio.ReadByte to detect if file is at EOF

I wish to confirm there are no more bytes to be read from a buffered reader (neither from the internal buffer, nor from the underlying file object) by trying to read one more byte (and catching EOF). Is using bufio.Read or bufio.ReadByte suitable for this purpose? It's not clear from the bufio.Read...
init_js
1

votes
1

answer
51

Views

nil point deference in golang using govmomi library

I'm trying to use the govmomi library (https://github.com/vmware/govmomi) to make some automated changes to a VM but I can't seem to get around the nil pointer exceptions on line 134 and 136 for the last few hours. I got it to work at one point but then I'm not sure what I'm doing wrong now as I've...
lightweight
1

votes
3

answer
41

Views

How to resolve user environment variables in filepath

Golang on windows. Trying to use os.Open('%userprofile%\\myfile.txt') Getting file path not found and golang is not resolving %userprofile% to my C:\users\myusername folder.
user3051040
1

votes
3

answer
320

Views

Axios request receiving a CORS error only when inside a callback/async function

I'm using VueJS for an app I am building. The server I have is written in Golang and has been set to accept CORS. In the app, in one of my components, searchBar, I have set it to fetch some data before it is created. var searchBar = { prop: [...], data: function() { return { ... }; }, beforeCreate:...
1

votes
1

answer
28

Views

How to insert an interface{} type to mongodb with bulk.Insert()

I can't insert a big array into my collection; I have a problem with the interface{} type. Here's the code: collections = getSession().DB('go').C('comments') func BenchmarkBulkInsert(data interface{}) { bulk := collections.Bulk() bulk.Insert(data...) _, bulkErr := bulk.Run() if bulkErr != nil { pani...
Hernan Humaña
1

votes
1

answer
76

Views

How to do idiomatic synchronization with time.After?

I'm writing an application that queues incoming requests. If a request has been on the queue for more than a certain amount of time, I'd like to throw a timeout. I'm doing that with time.After: timeoutCh := time.After(5 * time.Second) select { case
nickackerman42
1

votes
2

answer
43

Views

Add custom method for slice string[]

I'm creating a utility package for my project. Many of my string slices need a function to 1. remove duplicates 2. remove empty strings I know 1 way to do this:1. Add a function for each case which accepts a string slice and returns a string slice func removeEmpty(s []string) []string { i := 0 // i...
sfdcnoob
1

votes
1

answer
42

Views

Golang: reflect.DeepEqual returns unexpected false

I have the following code and code test below and for some reason the deepEqual is returning a false and failing the test. Now from reading the doco on this I would expect this to pass with a true for something so simple? Any points would be much appreciated. Thanks // customer.go type Customer stru...
Luke Hamilton
1

votes
0

answer
14

Views

Gorm (Golang) and database with Single Table Inheritance “type” column

I'm experimenting with using Go to read from a database that's been part of an existing Rails app. A few of the models and therefore tables use single table inheritance via a type column. In Rails/ActiveRecord, the presence of this column will create an automatic mapping to the appropriate model. If...
subvertallchris
0

votes
0

answer
3

Views

How to serve two static sites with gin in golang?

I want to create an application that will call a boolean function and depending on the result provide 1 of 2 compiled react apps as static sites. I'm using the LoadHTMLGlob function recommended by gin and it works fine with .tmpl files like the example in thier docs. However when doing just static h...
Jbar
2

votes
0

answer
20

Views

How to fix 'http: named cookie not present' in golang?

I'm building a small dinner/plan management application (with the use of microservices) for a couple of people I know. The intention is that each person can login to their own account and can then authenticate to other services using a bearer token (JWT). This bearer token is stored in a cookie. How...
Abe Brandsma
0

votes
0

answer
5

Views

Orderer Client Status Code: (2) CONNECTION_FAILED. Description: dialing connection timed out [localhost:7050]

When trying to initialize the SDK with my local network I'm facing below issue. I saw some similar posts in which it is mentioned that by adding entityMachers in config.yaml file fix this issue but even after adding the entityMatchers I'm facing this issue. [email protected]:/c/Projects/Go/src/githu...
alpha
1

votes
1

answer
1.4k

Views

Marshalling DIDL-Lite with Go's xml package

Here's a sample DIDL-Lite XML document from the UPnP AV ContentDirectory v2 Service Template: ... How would one go about marshalling to this with Go's xml package? More specifically: How are namespace prefixes defined, such as xmlns:dc and xmlns:upnp? How are multiple name spaces configured on an el...
Matt Joiner
0

votes
1

answer
15

Views

How to make changes or fixes to Cadence Workflow without breaking determinism?

What is the recommended practice for upgrading running workflows? If there are already running executions created using previous workflow implementation, then making any code change or updating workflow logic results in 'Non Deterministic Error' from Cadence as it is unable to replay history for ex...
Samar Abbas
2

votes
2

answer
20

Views

Golang: what is atomic read used for?

Here we have a go case provided by Go by Example, to explain the atomic package. https://gobyexample.com/atomic-counters package main import 'fmt' import 'time' import 'sync/atomic' func main() { var ops uint64 for i := 0; i < 50; i++ { go func() { for { atomic.AddUint64(&ops, 1) time.Sleep(time.Mil...
Ryan Lv
0

votes
0

answer
3

Views

Library Framework Development and package names path

Developing application in a modular way, developing libraries independently and then uploading each to github and then importing them into my main project. The problem is with broken paths The question is how to give paths when one is developing locally so when I download it, so the path works seaml...
Developer
1

votes
0

answer
16

Views

Binding GoRoutines to cpu cores

I need to run a number of go routines and bind them to separate CPU cores for a benchmark test. I've tried with runtime.LockOSThread() but this degrades performance significantly. I do not want to lock go rountines to specific threads and in my understanding LockOSThread does just that.
1

votes
2

answer
812

Views

Go , there is no parameter $1

Im trying to get the values of the database by this way. But the compiler throw me an error when I go to /myapps direction. Structure: type App struct{ Title string Author string Description string } Function: func myappsHandler(w http.ResponseWriter, r *http.Request){ db, err := sql.Open('postgres'...
hdraven

View additional questions