2018-10-22         Deirdre

How does gc handle slice memory reclaim

var a = [...]int{1,2,3,4,5,6}s1 := a[2:4:5]Suppose s1 goes out of scope later than a. How does gc know to reclaim the memory of s1's underlying array a?Consider the runtime representation of s1, spectype SliceHeader struct { Data uintptr Len int Cap int}The GC doesn't even know about the beginning of a. Go uses mark-and-sweep collector as it's present implementation.As per the algorithm, there will be one root object, and the rest is tree like structure, in case of multi-core machines gc runs along with the program on one core.gc will traverse the ...

 go                     1 answers                     107 view
 2018-10-22         Warner

Type conversion to similar type

I am trying to re-use code (Key/Value) pair to build ec2.Tag and autoscaling.Tag types, which are also Key/Value pairs. But I don't think I know enough about conversion/casting, please advise. Thank you in advance. panic: interface conversion: interface {} is []struct { Key string; Value string }, not []*ec2.Tagfunc (c *CloudWorks) GetTagCollection() interface{} { return []struct { Key string Value string }{ { Key: "key-a", Value: "value-a", }, { Key: "key-b", Value: "value-b", }, { Key: "key-c"...

 go                     1 answers                     66 view
 2018-10-22         Claude

How to handle manual invoked AWS lambda using serverless framework

I am manually invoking my lambda function since the 30s HTTP gateway timeout is too short for my purpose. The function was working when using HTTP, but when I manually invoke the function, the request.Body is empty.Here is the handler on my lambda code:func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { // Left out implementation details. // request.Body == "" here}Here is how I invoke it:func InvokeHooknode(req *HooknodeReq) error { // Serialize params payload, err := json.Marshal(*req) if err != nil { ret...

 go                     1 answers                     88 view
 2018-10-22         Maxine

How to separate initializing DB connection as a package in Go?

I have two packages, main and db.However, I get "DB declared and not used" error.db.gopackage dbimport ( "database/sql")var DB *sql.DBfunc Connect() { DB, err := sql.Open("mysql", "root:Berlin2018@/jplatform") if err != nil { panic(err.Error()) }}func Close() { DB.Close()}main.gopackage mainimport ( "database/sql" // "fmt" _ "github.com/go-sql-driver/mysql" "html/template" "net/http" "github.com/****/****/config" "github.com/****/****/db")var tpl *template.Templatefunc init() { tpl = template.Must(template.ParseGlob("templates/*.gohtml"))}func ma...

 go                     2 answers                     83 view
 2018-10-22         Taylor

Copy a string into a struct of strings

I am trying to simulate the memcpy from C in Go using unsafe.Pointer.I have to map a string into a struct of strings in the following way:package mainimport ( "fmt" "unsafe")type myMessage struct { Field1 [30]string Field2 [2]string Field3 [4]string Field4 [1]string Field5 [1]string}func main() { var inputString string = "Abcdefghi" inputPtr := &inputString unsafePtr := unsafe.Pointer(inputPtr) messPtr := (*myMessage)(unsafePtr) var messageString myMessage = *messPtr fmt.Println(messageString)}The result is as following:./test{[Abc...

 go                     1 answers                     74 view
 2018-10-22         Drew

Calling Apps Script API function from Golang with Parameters?

I want to call Apps Script function from Golang.I can send the Parameter from Golang but cannot make it work in runMyFunction. If I add return myParameter; - I can see the parameter I am passing but using it inside SQL to BigQuery is not working. I am getting undefinedvar sql = ' SELECT column1, column2 ' + ' FROM dataset.mytable WHERE SUBSTR ( column1) = "'+ myParameter + '" ;'My Apps Script Function:function runMyFunction(myParameter) {...return myParameter;}In Golang, calling runMyFunctiontype Message struct { myParameter string}m := Message{"1234"}a := make([]inter...

 go                     1 answers                     74 view
 2018-10-22         Quintion

Go Unicode combining characters (grapheme clusters) and MS Windows Console cmd.exe

In the following code, the ü is not the single Unicode character U+00FC but is a single grapheme cluster composed of two Unicode characters, the plain ASCII u U+0075 followed by the combining diaeresis U+0308.fmt.Println("Jürgen Džemal")fmt.Println("Ju\u0308rgen \u01c5emel")If I run it in the go playground, it works as expected. If I run it in a MS Windows 10 "Command Prompt" window, it doesn't visually combine the combining character with the prior character.However when I cut and paste the text into here it appears correctly:C:\> verMicrosoft Windows [Version 10.0.171...

 go                     1 answers                     75 view
 2018-10-22         Alma

How to handle channel closing synchronisation in case of slow producer, fast consumer in go?

I am new to go, and couldn't find an answer to this problem. What I am doing, is to read a CSV file in producer, doing some stuff which may take time, and then sending the output to a consumer via a channel. There's a chain of producer-consumers, and any producer may end up being slower than it's consumer. producer(1 goroutine) -> chan0 -> consumer-producer-1(>1 goroutines) -> chan1 -> consumer-producer-2(>1 goroutines) -> chan2 -> consumer(>1 goroutines)There can be up to 15 consumers here.Now the problem that I face is how to decide on the consumer side if the producer ...

 go                     1 answers                     94 view
 2018-10-22         Winifred

A question about main routine and a child routine listening on the same channel simultaneously

func main() { c := make(chan os.Signal, 1) signal.Notify(c) ticker := time.NewTicker(time.Second) stop := make(chan bool) go func() { defer func() { stop <- true }() for { select { case <-ticker.C: fmt.Println("Tick") case <-stop: fmt.Println("Goroutine closing") return } } }() <-c ticker.Stop() stop <- true <-stop fmt.Println("Application stopped")}No matter how many times I run the code above, I got the same resul...

 go                     1 answers                     62 view
 2018-10-22         Matt

Does closing a channel block until the receiver read it

I've implemented a method to shutdown my server by closing a channel, so other goroutines read the closed channel then exit. After the shutdown, I need to do some cleaning with server data, if close() blocks until all other goroutines read the closed channel, I can access the data without lock. So the question is: does closing a channel block until the receiver read from it? Below is the example code:package maintype server struct { chStop chan struct{} data map[int]interface{}}func newServer() *server { return &server { chStop: make(chan struct{}) }}...

 go                     1 answers                     60 view
 2018-10-22         Godfery

Doesn't receive a message from a channel

Edit:After I added a small part of file I was using (7 GB) and tried to run the program, I could see this:fatal error: all goroutines are asleep - deadlock!goroutine 1 [chan receive]:main.main() /media/developer/golang/manual/examples/sp/v2/sp.v2.go:71 +0x4a9exit status 2Situation:I'm completely new to GO, so I'm sorry if my question is really simple.I am trying to stream xml file, split documents and then parse them in different GO Routines.Example of XML file I'm using:<?xml version="1.0" encoding="UTF-8"?><osm version="0.6" generator="CGImap 0.0.2"> <...

 go                     2 answers                     62 view
 2018-10-22         Herman

Can I get some help to reason about the `concurrent prime sieve` example?

I am very new to go, Can someone help me to reason about this example:// A concurrent prime sievepackage main// Send the sequence 2, 3, 4, ... to channel 'ch'.func Generate(ch chan<- int) { for i := 2; ; i++ { ch <- i // Send 'i' to channel 'ch'. }}// Copy the values from channel 'in' to channel 'out',// removing those divisible by 'prime'.func Filter(in <-chan int, out chan<- int, prime int) { for { i := <-in // Receive value from 'in'. println("debug", i, prime) if i%prime != 0 { out <- i // Send 'i' to 'ou...

 go                     2 answers                     64 view
 2018-10-22         Edith

how to select for input on a dynamic list of channels in Go?

Go has a mechanism to do a blocking read from one of several channels, the select statement. So you can sayselect { case <- c1: case <- c2:}will block until we get input from either of these two channels. Very nice. But this requires that I specify in the source code how many channels I want to poll. What if I have a slice or array of channels and I want to block until I get input on any of them? Just a thought, but you could use a multiplexing pattern, where you spawn off a goroutine with 2 channels that blocks on both and sends the output to a new channe...

 go                     4 answers                     71 view
 2018-10-22         Sebastiane

using channels with google pubsub poll subscriber

I'm trying to create a google pubsub subscriber in golang where I take 100 messages at at a time and then write them to influx. I'm trying to use channels to do this like this:package mainimport ( "os" "fmt" "cloud.google.com/go/pubsub" "log" "sync" "golang.org/x/net/context" "encoding/json" clnt "github.com/influxdata/influxdb/client/v2" "time")type SensorData struct { Pressure float64 `json:"pressure"` Temperature float64 `json:"temperature"` Dewpoint float64 `json:"dewpoint"` Timecollected int64 `json:"timecollected"` ...

 go                     1 answers                     98 view
 2018-10-22         Felix

Can I have a dynamic host policty with autocert?

I am looking at some sample code for using autocert with a go web server.Would it be possible for the hostPolicy implementation to by dynamic i.e. read the while listed hosts from the database (as they will change constantly).m := autocert.Manager{ Cache: certcache, Prompt: autocert.AcceptTOS, HostPolicy: hostPolicy, }What would a skeleton structure look for a custom hostPolicy implementation?https://github.com/golang/crypto/blob/master/acme/autocert/autocert.go#L60Is has to return a function? Does it have to return a function?yes, this...

 go                     1 answers                     103 view
 2018-10-22         Muriel

List Traefik ingress controllers using Go client for Kubernetes

We have a little internal tool listing our Kubernetes services using Go client for Kubernetes.Now we have added Traefik to map our services to meaningful dns names using ingress controllers. We see that there is an ingress lister extension in Go client for Kubernetes that can be used to list ingress controllers. However, we could not make it work.Are there any Go client code snippets listing ingress controllers? What have you tried so far? Posting examples helps. Try the following arbitrary example to get you started: // imports // metav1 "k8s.io/apimachinery/pkg/...

 go                     1 answers                     67 view

Page 1 of 116  |  Show More Pages:  Top Prev Next Last