Questions tagged [go]

14470 questions
1

votes
1

answer
953

Views

How do I get a slice from a Postgres array in Golang?

Let's say I have a postgres query like: SELECT id, ARRAY_AGG(code) AS code FROM codes WHERE id = '9252781' GROUP BY id; My return looks like: id | codes -----------+------------- 9252781 | {H01,H02} Both id and codes are varchar. In Golang when I scan along the rows for my result, it just...
cigrainger
1

votes
1

answer
18

Views

How to iterate through a map in the given order in golang? [duplicate]

This question already has an answer here: Map in order range loop 1 answer I have a map as given below var sampleDict map[int]string = map[int]string{ "john": "doctor", "tim": "engineer", "adam": "lawyer" } and have to iterate over this map to get the key and value pairs in the same given order as...
pawan A
1

votes
1

answer
2.1k

Views

How to marshal array to binary and unmarshal binary to array in golang?

I want to use gob to encode and decode object, I do it like this: type transProp struct { a []int b []float64 } func (p transProp) MarshalBinary() ([]byte, error) { // A simple encoding: plain text. var b bytes.Buffer fmt.Fprintln(&b, p.a, p.b) return b.Bytes(), nil } // UnmarshalBinary modifies the...
roger
-1

votes
0

answer
14

Views

Accessing variables of a struct from another nested structs variable in Go

Given are 2 structs I wrote. type DNSPacket struct { header DNSHeader.DNSHeader questions []DNSQuestion.DNSQuestion answers []DNSRecord.DNSRecord authorities []DNSRecord.DNSRecord resources []DNSRecord.DNSRecord } type DNSHeader struct { id uint16 //16bits recursion_desired bool //...
Sumukha Pk
1

votes
1

answer
31

Views

fmt.Print in go routine *may* not output when master thread is loop

The following code as is in https://play.golang.org/p/X1-jZ2JcbOQ package main import ( "fmt" ) func p(s string) { fmt.Println(s) } func main() { go fmt.Println("1") go p("2") for {} // infinite loop } prints 1 2 definitely in Windows with golang 1.11 but prints nothing definitely in Linux with go...
crukedsh
1

votes
2

answer
45

Views

different Content-Type with httptest and curl

I'm trying this Go code package main import ( "github.com/gorilla/mux" "io" "log" "net/http" ) func HealthCheckHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") io.WriteString(w, `{"alive": true}`) } func main() { router...
JuanPablo
0

votes
0

answer
20

Views

How do I convert a python string array to POINTER(c_void_p)

I'm trying to pass a python string array to Go, so I need to construct a 'GoSlice' from a python string array. A quick google search shows how to do this for integer arrays but I'm struggling to so the same for string arrays. Any help would be appreciated
beegee
0

votes
1

answer
28

Views

Go Language Merge Consecutive Integers

I just want to know if there's a good way to return true if both integers can be merged but it must be in consecutive means, {100,101} can be merge with {103, 104, 102 }, but not {100,101} and {103,104,105} (Missing 102) coding based on the question. package main import ( "fmt" "math/rand" "time...
Faker
-2

votes
0

answer
22

Views

Evenly distributing items in slices

I'm porting a legacy code base from c++ to Golang. Is there a builtin method other than a loop that chunks slices in Go? The c++ code is the following: void Tree::redistributeEntries(EntryMultiSet &entries, std::list siblings) { unsigned long batchSize = (unsigned long)std::ceil( (double)entries.siz...
Odinovsky
3

votes
1

answer
28

Views

tuple assignment in Go

Using this code: for i := uint64(3); n > 1; i, n = i+2, n-1 { The Go Playground output is: 1999993 Which is not correct result. And this code, which uses : for i := uint64(3); n > 1; i += 2 { then n-- The output is correct: 15485863 go version go1.11.5 linux/amd64 Am I missing something on tuple...
A.R
2

votes
2

answer
15

Views

Set pointer to nil from method or function

Why both these destroy functions do not change pointer to nil and how can I create such function? package main import ( "fmt" ) type position struct { x int y int } func (p *position) destroy() { p = nil } func destroy(p *position) { p = nil } func main() { p1 := &position{1,1} p2 := &position{2,2}...
Marcin Doliwa
0

votes
0

answer
17

Views

Golang: Interfaces From Other Packages

I'm trying to understand this example from the golang-restful-starter-kit boilerplate to learn more about golang. I've copy and pasted some code below that I'm confused about. We have daos which are data access objects for reading and writing from the database. We also have the service which is what...
arooo
0

votes
0

answer
18

Views

How to retry HTTP POST requests

I have implemented the following code for retrying http post requests in Go. In second retry attempt, I always get request body as null. I have tried defer req.body.close() but it is not working. Can anyone please help me this issue? func httpRetry(req *http.Request, timeOut time.Duration, retryAtt...
Gaurav Palav
0

votes
0

answer
11

Views

Is there a PubSub implementation (C & golang) that optimizes for local delivery, but scales to IP?

I'm working on a system whose message passing schemes (plural!) have evolved organically over the last few years. In some cases, listening for a message involves opening a socket. In others you open an OS pipe. In still others, you inherit from an interface and implement a handler method. In others,...
0

votes
0

answer
4

Views

CORS Error When Trying To Access Golang Backend With Ember Frontend

So here is my problem. I am writing a simple application that posts data to an API. Unfortunately I cannot get data to post. Every Time I try to post I get the following error: Access to XMLHttpRequest at 'http://localhost:8000/api/v1/users' from origin 'http://localhost:4200' has been blocked by CO...
Joe Alvini
1

votes
3

answer
264

Views

How to use SendGrid from Google App Engine Golang?

The example code at: https://sendgrid.com/blog/send-email-go-google-app-engine/ My guess this is very old sample code to use sendgrid-go on Google App Engine. I've attempted 4 permutations and failed each time with: https://api.sendgrid.com/v3/mail/send: http.DefaultTransport and http.DefaultCli...
Darian311
1

votes
1

answer
418

Views

golang static server always returns 404 page not found

I try to get a Go webserver running on a raspberry pi (using 1.10.1) I have a go webserver implemented like (StatPiPrivider.go): package main import ( "net/http" ) func main() { http.Handle("/", http.FileServer(http.Dir("./static/templates"))) http.ListenAndServe(":3000", nil) } and the static folde...
ket0ma
1

votes
1

answer
828

Views

Connect to AWS RDS PostgreSQL with AWS Lambda and Golang

I am trying to connect to a AWS RDS PosgreSQL database from a lambda in Go. The authToken seems good in the logs. creds := credentials.NewEnvCredentials() authToken, err := rdsutils.BuildAuthToken("something.eu-west-3.rds.amazonaws.com", "eu-west-3", "Username", creds) if err != nil { fmt.Println("C...
Ludonope
1

votes
1

answer
322

Views

Read and merge two Yaml files

Assuming we have two yaml files master.yaml someProperty: "someVaue" anotherProperty: "anotherValue" override.yaml someProperty: "overriddenVaue" Is it possible to unmarshall, merge, and then write those changes to a file without having to define a struct for every property in the yaml file? The m...
DominicEU
0

votes
0

answer
6

Views

How to control indent after including file content in Helm configMap?

I'm setting up a ConfigMap for my Helm chart. As per good practice, I want to include non-yaml resources through separate files rather than inline. Currently I am trying to include both an xml file and a tpl helper in my ConfigMap under "data". Both are read without issue in the below code. But I ca...
Bluebluebleu
1

votes
2

answer
322

Views

Docker container running golang http.Client getting error `certificate signed by unknown authority`

I created a docker container for talking to the google api using GoLang. I started off using a SCRATCH container and am getting the error certificate signed by unknown authority upon changing to ubuntu/alpine i still get the error. resp, err := client.Get("https://www.googleapis.com/oauth2/v3/useri...
Westy10101
1

votes
2

answer
120

Views

Cast int96 timestamp from parquet to golang

Having this 12 byte array (int96) to timestamp. [128 76 69 116 64 7 0 0 48 131 37 0] How do I cast it to timestamp? I understand the first 8 byte should be cast to int64 millisecond that represent an epoch datetime.
ZAky
1

votes
1

answer
60

Views

Revel and Docker container

I am attempting to create a docker container that contains the revel skeleton app. Everything seems to build OK and the container is created but when I go to localhost:9000 in my browser nothing comes up. To make sure my environment is working properly I created a simple hello world go app and crea...
Tom Vaughan
1

votes
1

answer
42

Views

How to IOCTL properly from golang

I am trying to port bit of raspberrypi's userspace code from C to golang and I've run into a program involving ioctl(). I am having trouble specifically with following C code #define MAJOR_NUM 100 #define IOCTL_MBOX_PROPERTY _IOWR(MAJOR_NUM, 0, char *) static int mbox_property(int file_desc, void *...
Sigma
1

votes
2

answer
20

Views

Do I need one or many sarama.SyncProducer inside my Golang app?

I am new in Golang, I need to write the app that will publish events to kafka, I can't find the answers on the following questions: How many sarama.SyncProducer do I need? Is it fine to use one across all app? Shall I have some kind of producer pool?
Maksym
1

votes
1

answer
40

Views

Pointers and references to struct in functions

I'm starting with Go and I'm having difficulty understanding pointers and references to structs inside functions. Considering the example https://play.golang.org/p/zd8La4ecNXw package main import "fmt" type User struct { Name string } func main() { // 1st u := User{Name: "Anne"} fmt.Println("1st: ",...
Luis
1

votes
1

answer
27

Views

Can Goland autocomplete SQL statements using other SQL packages?

Goland is great at auto-completing SQL statements if I use the sql.DB package functions. For example, Goland will provide SQL autocompletion (including DDL data) in this setting: result, err := someDB.Exec(`INSERT INTO `) Can I configure Goland to show me SQL autocompletion in other contexts? For in...
Duncan Jones
1

votes
1

answer
55

Views

go modules multiple main methods

I have a project with mutliple main methods. When running go build program1/main1.go which has a different set of dependencies than program2/main2.go, my first go build seems to alter my go.mod file and removes the dependencies it thinks it does not need. Yet main2 would need these dependencies. I'v...
Dylan Meeus
-2

votes
0

answer
36

Views

map performance comparison between go and c++

I don't understand how golang is outperforming c++ in this operation by 10 times, even the map lookup is 3 times faster in go than c++. this is the c++ snippet #include #include #include std::chrono::nanoseconds elapsed(std::chrono::steady_clock::time_point start) { std::chrono::steady_clock::tim...
mrclx
-2

votes
3

answer
27

Views

Go Channels and delays

I was just experimenting with Go channels on my Ubuntu 64 bit environment and got confused with the output the following program produced. I got the output: 0 1 2 3 Exit The output when I uncommented the two commented lines: 0 1 2 3 4 Exit Please explain the behavior. TIA. package main import ( "fmt...
Hardy
0

votes
0

answer
3

Views

What does runtime.memclrNoHeapPointers do?

I am profiling a library and see that a function called runtime.memclrNoHeapPointers is taking up about 0.82seconds of the cpu-time. What does this function do, and what does this tell me about the memory-usage of the library i am profiling? The output, for completeness: File: gribtest.test Type: c...
nilsmagnus
8

votes
2

answer
762

Views

Efficiently mapping one-to-many many-to-many database to struct in Golang

Question When dealing with a one-to-many or many-to-many SQL relationship in Golang, what is the best (efficient, recommended, "Go-like") way of mapping the rows to a struct? Taking the example setup below I have tried to detail some approaches with Pros and Cons of each but was wondering what the c...
Ewan
-1

votes
1

answer
29

Views

Unknown bug in Golang code: insertion sort in 2nd pass?

I'm new to Go. I'm using go version go1.10.4 linux/amd64. My objective is to ask a single integer input from the user append it to an array and sort it. I'm using insertion sort for this. The program needs to exit on receiving 'X' as input from the user. This is my code: package main import ( "fmt"...
pyofey
1

votes
1

answer
296

Views

How to figure out if `value.FieldByName(name)` finds the field?

I'm trying to figure out how to stop the execution of my program when the field is not found in the example below. If FieldByName(key) returns a zero Value how can I warn the user that the field was not found? field := mutable.FieldByName(key) // need to figure out if the field exists before callin...
harlow
1

votes
1

answer
542

Views

Golang Decode Nested JSON into Nested Struct

Lets look at the following code snippet: type Input struct { Value1 string Value2 string Value3 string Value4 string Nest } type Nest struct { ID string } input := &Input{} decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&input); err != nil { fmt.Printf("something went...
TinuC
0

votes
0

answer
2

Views

GORM Zero-to-Many: Cannot add or update a child row: a foreign key constraint fails

I am new to Golang and Gorm. I want to parse API response and store two tables. For each "reports" table, there can be zero-to-many tables of "personal_details". However, gorm gave error when applying foreign key constraint because there's no record for PersonalDetail in API response sometimes. I...
Giwi
1

votes
3

answer
4.5k

Views

How do you find the FQDN of the local host in GO (golang)?

How do you find the FQDN of the local host in GO (golang)? BTW: net.LookupAddr() doesn't work on Windows. So that's not an option.
Kevin Bailey
1

votes
1

answer
9.1k

Views

Golang os.Open No such file or directory error

I am struggling to figure out an issue with os.Open. I keep getting a 'no such file or directory' error when using os.Open on a folder named templates. So I have my folder MVCApp with bin pkg src and templates in it. Then I have main in the src folder. So I have this code: basePath := "templates" te...
j5juice
1

votes
3

answer
138

Views

Go pipeline using channels

I'm exploring Go and trying to set up a sort of pipeline using channels. I just want to read something in main() and send them to process() for processing, in this case just print the value to the screen. Unfortunately, in the code below, it appears that process() never reads from the channel, or at...
jmng
0

votes
0

answer
5

Views

Inconsistent append behavior in Go?

I'm writing a function that returns the vertical order traversal of a binary tree's node values. (ie, from top to bottom, column by column). Here's an example of expected input and output: Input: [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5) 3 /\ / \ 9 8 /\ /\...
solo

View additional questions