FAQ Database Discussion Community


Getting a PHP configuration variable in Go

php,go
I want to get the output of the command php -r 'echo get_cfg_var("some_var");' to check it against a predefined value. Currently, I have the following code: variableName := "default_mimetype" cmd := exec.Command("php", "-r", "'echo get_cfg_var(\"" + variableName + "\");'") out, err := cmd.CombinedOutput() after running, err.Error() returns "exit status 254"...

Why won't mgo unmarshall my struct properly?

mongodb,go,bson,mgo
Earlier I posted this question asking about writing custom BSON marshalling/unmarshalling in Go using mgo. Now I've come to test it I think I've hit on a bigger problem. All my structs unmarshal to nil values. This is my currency struct with the implementations of bson.Getter and bson.Setter: type Currency...

Although maps are always reference types, what if they're returned from a non-pointer receiver?

pointers,dictionary,go
Supposedly maps are reference types in Go, so when returning them from functions, you don't need to pass as a pointer to the map in order for the changes to be visible outside the function body. But what if said map is returned from a method on a non-pointer struct?...

error libxml2 not found on installing gokogiri on windows

go,libxml2,gokogiri
I'm trying to install gokogiri on Windows 8 machine following instructions in their github page : To install: sudo apt-get install libxml2-dev go get github.com/moovweb/gokogiri skipping the first command (as it isn't available on Windows), I get the following error : What is the error complaining about? Should I install...

convert chan to non chan in golang

go,type-conversion
Is it possible to let function funcWithNonChanResult have the following interface: func funcWithNonChanResult() int { And if I want it to use function funcWithChanResult with the interface: func funcWithChanResult() chan int { In other words, can I somehow convert chan int to int? Or I must have chan int result...

How to serialize a custom formatted time to/from xml in Go?

xml,go,formatting,date-formatting
When serializing a datetime to/from xml how do I make it use a custom time format?

Query total physical memory in Windows with Golang

windows,go
Trying to get the total physical memory using Go on Windows but not sure which package(s) to use and calls to make. I believe this can be done with syscall. Would also prefer not to interface with C to do this.

Golang - structs, intializing and memcpy - what is the proper way?

arrays,struct,go,initialization,custom-type
I'm new to Go and I wish to translate some C/C++ code I have to Go but I haven't been able to. The problem resides in 2 places: how can I initialize a struct I've defined and how to do a "memcopy" The code I'm talking about is this: http://play.golang.org/p/e8N255qEAk...

image.Decode results in “unknown format” when source is multipart.File

image,go,martini
I have a multipart.File that a user uploads to my server, and then I take that file and upload it to s3 using aws-sdk-go, but I also want to create a thumbnail of that image. The code below works fine in my tests when I file is the return value...

Golang add function to struct defined elsewhere

struct,go
I want to create a function on the sql.Row struct that scans a row into my struct ErrorModel. This is what I am doing: func (row *sql.Row) ScanErrorModel(mod *model.ErrorModel, err error) { err = row.Scan(&mod.MessageId, &mod.ServiceName, &mod.EventName, &mod.Hostname, &mod.Message, &mod.CriticalRate, &mod.Extra, &mod.Timestamp) return } func (dao *ErrorsDAO) Fetch(id string) (mod...

Parenthesis after a slice in go?

go,slice
I've recently started learning go, and following through a tutorial. In the tutorial there is the line: p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")} They have a slice with parenthesis defined: []byte("This is a sample Page.") However from all the docs I've read I've never seen parenthesis...

Go - loop through map on the same order multiple times

go
How can I loop through a map on a constant order multiple times ? In my go code I am looping through a map twice but the values are not appearing on the same order on both loops : fieldMap := map[string]int{...} First loop : for k, _ := range...

Why does my concurrent function exit prematurely in Go?

concurrency,go
I am looking through Go Bootcamp and am reading the Go Concurrency chapter right now. I have never used concurrency before in programming and don't understand the output of this program: package main import ( "fmt" "time" ) func say(s string) { for i := 0; i < 2; i++...

Are pointers dereferenced by default in golang struct methods?

pointers,go
I'm confused by golang methods on structs. I've following along in a tutorial in which they have: func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } From my understanding p is pointer and you would need to dereference the pointer before retrieving a...

Go - close an external application

osx,go
I'm using Go on an OSX machine and trying to make a program to open an external application and then after few seconds, close it - the application, not exit the Go script. I'm using the library available on https://github.com/skratchdot/open-golang to start the app and it works fine. I also...

How to make this code more performant?

performance,go,hashmap
I have this snippet of code that iterate over a map and filter some fields based on relation type, I have to run two loops and have a feeling that it is going to be slow for big maps. Is there any way I can technique/refactoring to make this code...

Encode array to base64 in go

xml,go,base64,gorp
Here is my complete code for a function I develop: package main import ( "database/sql" "log" "encoding/xml" "github.com/gin-gonic/gin" //golang frameworks _ "github.com/go-sql-driver/mysql" "gopkg.in/gorp.v1" //work with database(mysql, etc.) ) type Genre struct { Title string `xml:"genre"` } type GenreArray struct { Auth_state int `xml:"auth_state"` Count int64 `xml:"count"` Item genreAPI `xml:"item"` }...

panic: runtime error: invalid memory address or nil pointer dereference when running Blockchainr

go,blockchain
I run blockchainr and get the following terminal output: 17:39:57 2015-06-16 [INF] loading db leveldb panic: runtime error: invalid memory address or nil pointer dereference panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x0 pc=0x402cb63] goroutine 1 [running]: main.search(0x4911ef8, 0xc20806e2d0, 0x0, 0x0, 0x4911ef8) /Users/mesquka/Downloads/blockchainr-master/src/blockchainr/main.go:185 +0x3fa...

How to find Relationships between Objects

javascript,python,arrays,recursion,go
For People With A Similar Question (written after finding a solution): This problem, as you might notice according to the answers below, has a lot of different solutions. I only chose Evan's because it was the easiest one for me implement into my own code. However, from what I tried,...

Golang+PostgreSQL - How to print exact query without escape HTML tags?

postgresql,go
data stored in PostgreSQL: The <b>Argentine Army</b> is. Data type: "content" text COLLATE "default". When print through Golang, it become The &lt;b&gt;Argentine Army&lt;/b&gt; is I need to print exact data from PostgreSQL without escaping HTML tags. I'm not sure if this is Go or PostgreSQL issue. below is my Golang...

Convert json to struct using reflection in golang

json,reflection,go
func deserialize(request *http.Request,typ reflect.Type) (interface{}, *httpNet.HandlerError){ data,e:=ioutil.ReadAll(request.Body) fmt.Println(string(data)) if e !=nil{ return nil,&httpNet.HandlerError{e,"could not read request",http.StatusBadRequest} } v:=typ.Elem() payload:=reflect.New(v).Elem().Interface() eaa:= json.NewDecoder(request.Body).Decode(payload) if e!=nil{ fmt.Println(eaa.Error()) } fmt.Println(payload) fmt.Println(reflect.ValueOf(payload) ) return payload,nil } to call it: r,_:=...

Declare variable with format specifier in Go

go
In Python, I can declare a variable as d ='/some/dir/%s' and later replace %s with any value as >>> d = '/some/dir/%s' >>> d % "hello" '/some/dir/hello' Is it possible to do the same in Go? If so, how?...

Referencing yourself inside of a struct

struct,go
Let's say I have a type that's a struct like so: type Authorization struct { Username string Password string Handler func(http.HandlerFunc) http.HandlerFunc } And I have an array of these: type Authorizations map[string]*Authorization I want to be able to do something like this: var auth = Authorizations{ "test": *Authorization{ "someusername",...

Using encoding/xml.Encoder how do I place the xml header on its own line?

xml,go
I have the following code that uses xml.Encode. package main import ( "bytes" "encoding/xml" "fmt" ) type Stuff struct { Name string `xml:"name"` } func main() { w := &bytes.Buffer{} enc := xml.NewEncoder(w) enc.Indent("", " ") procInst := xml.ProcInst{ Target: "xml", Inst: []byte("version=\"1.0\" encoding=\"UTF-8\""), } if err := enc.EncodeToken(procInst); err...

Golang: Type cast custom types to base types

go
How can I convert custom type to interface{} and then to base type (ex. uint8)? I can't use direct cast like uint16(val.(Year)) because I may not know all custom types, but I can determinate base types (uint8, uint32,...) in runtime There are many custom types (usually used as enums) based...

Golang switch between structs

struct,go,interface,switch-statement
I'm new to golang and I'm trying to create a function that, based on the struct it's used on, will return a formatted string using Sprintf type Name struct { Title string First string Last string } type Location struct { Street string City string State string Zip string }...

Correct use of go context.Context

concurrency,go,gorilla
I just read the article: Build You Own Web Framework In Go and for sharing values among handlers I picked the context.Context and I'm using it in the following way to share values across handlers and middlewares: type appContext struct { db *sql.DB ctx context.Context cancel context.CancelFunc } func (c...

Different performances in Go slices resize

go,stack,benchmarking,slice
I'm spending some time experimenting with Go's internals and I ended up writing my own implementation of a stack using slices. As correctly pointed out by a reddit user in this post and as outlined by another user in this SO answer Go already tries to optimise slices resize. Turns...

How can I turn a string into an operator?

go
Is there a way to convert a string (e.g. "+", "-", "/", "*") into their respective math operators (+, -, /, *)? In Python you can do: import operator ops = {"+": operator.add, "-": operator.sub} # etc. print ops["+"](1,1) # prints 2 Is there a similar library or method for...

How do I get the submit value from the request object

html,go
I am trying to make a form POST request with two different submit buttons. I would like to try and get the submit button value in go. How do I go about getting this from the http.Request object. HTML Code: <form action="/save" method="POST"> <div><span>Title: </span><textarea name="title" placeholder="Link">{{printf "%s" .Title}}</textarea></div> <div>...

Using Go's HTTP server for production [closed]

go
I'm a PHP developer new to Golang. PHP comes with an inbuilt server which is not recommended for production. I read the beautiful book by astaxie on web development in Go and also the golang.org example on writing a web app. They both use the http.ListenAndServe() to create a web...

Differences between string.Contains and strings.ContainsAny in Golang

go
In the source code: // Contains returns true if substr is within s. func Contains(s, substr string) bool { return Index(s, substr) >= 0 } // ContainsAny returns true if any Unicode code points in chars are within s. func ContainsAny(s, chars string) bool { return IndexAny(s, chars) >= 0...

What does an empty map of interfaces do in a golang function?

go
I was reading through an article on golang templates and this came up in the example code. func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}) error { // Ensure the template exists in the map. tmpl, ok := templates[name] if !ok { return fmt.Errorf("The template %s does not exist.", name) }...

goroutine channels over a for loop

json,struct,go,channels
My main function reads json from a file, unmarshals it into a struct, converts it into another struct type and spits out formatted JSON through stdout. I'm trying to implement goroutines and channels to add concurrency to my for loop. func main() { muvMap := map[string]string{"male": "M", "female": "F"} fileA,...

Go + Protocol buffers acting really strange

go,protocol-buffers
I'm writing a service-based server for a project I'm working on, which is written in Go and uses Protocol Buffers for inter-service communication. Everything was working fine until I added protocols named DeviceRequest and DeviceResponse, now the compiler can't find them, while the go source of the protocol exists and...

How check error codes with couchbase gocb?

go,couchbase
When handling errors returned by gocb (the official Couchbase Go Client) I would like to check for specific status codes (e.g. StatusKeyNotFound or StatusKeyExists). Like so _, err := bucket.Get(key, entity) if err != nil { if err == gocb.ErrKeyNotFound { ... } } Can this be done?...

Handling Custom BSON Marshaling (Golang & mgo)

json,mongodb,go,bson
I have a number of structs that require custom marshalling. When I was testing I was using JSON and the standard JSON marshaller. As it doesn't marshal unexported fields, I needed to write a custom MarshalJSON function, which worked perfectly. When I called json.Marshal on the parent struct containing the...

How can I redirect, in Go, the stdout and stderr of a command to both the console and a log file while outputting in real time?

go,io,sync
The following bit of code does exactly what I want, except it only prints to the console. cmd := exec.Command("php", "randomcommand.php") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } randomcommand.php: // randomcommand.php simply alternates output between stdout and stderr 20 times $stdout...

Run Golang as www-data

security,go
When I run a Node HTTP server app I usually call a custom function function runAsWWW() { try { process.setgid('www-data'); process.setuid('www-data'); } catch (err) { console.error('Cowardly refusal to keep the process alive as root.'); process.exit(1); } } from server.listen(8080,'localhost',null,runAsWWW); so the server is actually running as the www-data user to...

Cannot call tests inside packages other than main

go
I am writing tests for my go code and inside sender folder, sender package I have added exposed_api_test.go ( also tried exposed_api_test.go because I have code in exposed_api.go) package sender import ( "log" "testing" "github.com/stretchr/testify/assert" ) func TestTimeConsuming(t *testing.T) { assert.Equal(t, "test", "test1") } and when I run build and...

Trouble retrieving Has Many using Gorm

go,go-gorm
When I try to get episodes back from a podcast I get invalid association []. Not sure what I'm doing wrong. package main import ( "log" "github.com/jinzhu/gorm" _ "github.com/mattn/go-sqlite3" ) type Podcast struct { Id int Title string RssUrl string `sql:"unique_index"` Url string Episodes []Episode } type Episode struct {...

Go Yaml Interpretation Example

go,yaml
This Go Yaml Interpretation Example, https://gist.github.com/suntong001/74c85d15b19ef4b14b0e, can unmarshal a simple YAML like this: foo: 1 bar: - one - two Now I want to interpretation an array of the exact same data structure, what's the correct way to do? Below is my code so far, and it is not working...

CGO converting Xlib XEvent struct to byte array?

c,go,xlib,cgo
I am creating a simple window manager (code based of the c code in tinywm) in Golang. To use Xlib, I am using cgo, so my header is: // #cgo LDFLAGS: -lX11 // #include <X11/Xlib.h> And I have a variable declaration, like: event := C.XEvent{} And then, I use this...

How do I do a literal *int64 in Go?

go
I have a struct type with a *int64 field. type SomeType struct { SomeField *int64 } At some point in my code, I want to declare a literal of this (say, when I know said value should be 0, or pointing to a 0, you know what I mean) instance...

Passing Variables to a Golang Package

design,go,singleton
Given a package containing the following local variable and functions: var bucket *gocb.Bucket func Init(b *gocb.Bucket) { bucket = b } func DoSomething() { // do something with 'bucket' } Is it acceptable to call the Init function, passing in an instance of bucket, before calling DoSomething, which is dependent...

Boltdb-key-Value Data Store purely in Go

go,backend,datastore,key-value-store,boltdb
Bolt obtains a file lock on the data file so multiple processes cannot open the same database at the same time. Opening an already open Bolt database will cause it to hang until the other process closes it. As this is the case,is there any connection pooling concept like various...

Challenge of finding 3 pairs in aray

go,refactoring
The length L at the time of joining, when the length of the bar of the N (1 ≦ N ≦ 5000) is supplied from standard input, is the L by connecting three lengths among the N number of bars please write a program to find the total number of...

Is os.File's Write() threadsafe?

go
I was wondering if calling Write() on an os.File is threadsafe. I'm having a hard time finding any mention of threadsafety in the docs. Thanks!...

Mail with html content shows break lines or ignores newlines

email,templates,go,mandrill
I am sending mail to users via mandrill and I using both smtp and mandrill api to send. Content of the mail is rendered go template (.tpl) When I put template like Hi {{.name}}, <br/> This is support. <br/> it sends via mandrill api ok, but is visible when I...

Marshalling empty map[string]interface{} results in “null” instead of nil

go
I have a problem where Go is inserting "null" into my PostgreSQL database's jsonb columns if I try to do the following, and the structs property (in this case of type map[string]interface{}) is empty: accessMembers, _ := json.Marshal(c.AccessMembers) Doing a test print it outputs the same as the value which...

Golang, how to return in func FROM another func?

go,return,func
I want to end execution in parent func apiEndpoint() upon calling/exiting in a child func apiResponse() func apiEndpoint() { if false { apiResponse("error") // I want apiResponse() call to return (end execution) in parent func // so next apiResponse("all good") wont be executed } apiResponse("all good") } func apiResponse(message string)...

Golang failes to change the name of imported module

go,docker,skydns
I'm trying to bring SkyDNSv1 back to life and build it from my fork (here is Dockerfile). SkyDNS was really good and simple tool for the quick service discovery, but it wasn't updated for a long time. There is an error in build process and it's caused by third party...

Golang ORDER BY issue with MySql

mysql,database,go
I can't seem to dynamically ORDER BY with db.Select(). I've Googled without any luck... WORKS rows, err := db.Query("SELECT * FROM Apps ORDER BY title DESC") DOES NOT WORK rows, err := db.Query("SELECT * FROM Apps ORDER BY ? DESC", "title") I'm not getting any errors, the query simply fails...

How do I save an entire string as a txt file in Go?

string,go
I'm creating a simple word processing program in Go. From the command line, I have two prompts: $Enter Title: $Enter Body: The program is supposed to save the document as a txt file and print it to the command line. The program works if the user user types in a...

JSON decoding in golang

json,curl,go
So I tried something based on the example here in my code, and get no data, but no error either. The code is: import ( "io" "fmt" "net/http" "encoding/json" ) type Credential struct { username string `json:"username"` password string `json:"password"` } func login(res http.ResponseWriter, req *http.Request) { if req.Method ==...

Git tag name as version in Go via Travis-CI

github,go,makefile,travis-ci
Essentially what I want to do is embed the git tag name (from a github release) to a version string within my GO code. If I use this code; package main import ( "flag" "fmt" ) var version string func main() { var verFlag bool flag.BoolVar(&verFlag, "version", false, "Returns the...

POST golang request with string data

rest,go
I can do a POST request with string data, using POSTMAN chrome extension. I need to do the same using golang code. But my Go code loses string INSERT INTO V SET name = 'jack', boss = #11:19 and posts empty data to the server. package main import ( "bytes"...

Unable to send JSON as body for HTTP POST request in GO

go
When i make the POST request using the below GO Function. I get a invalid json on the server side. If i send static json for example var jsonprep = []byte(`{"username":"[email protected]","password":"xyz123"}`) it does work instead of var jsonprep string = "`{username:"+username+",password:"+password+"}`" . func makeHttpPostReq(url string, username string, password string){ client...

How to exclude generated code from coverage statistics

testing,go
I have thrift generated code in my project? How do I stop this from affecting my coverage stats? They're dismal.

Streaming commands output progress

go,execution
I'm writing a service that has to stream output of a executed command both to parent and to log. When there is a long process, the problem is that cmd.StdoutPipe gives me a final (string) result. Is it possible to give partial output of what is going on, like in...

Why doesn't “go get gopkg.in/…” work while “go get github.com/…” OK?

windows,git,powershell,github,go
I try to use go get gopkg.in/fatih/pool.v2 to install pool according to Readme.md, but can't success: C:\Users\xiaona\Documents\GitHub> go get -v gopkg.in/fatih/pool.v2 Fetching https://gopkg.in/fatih/pool.v2?go-get=1 https fetch failed. Fetching http://gopkg.in/fatih/pool.v2?go-get=1 import "gopkg.in/fatih/pool.v2": http/https fetch: Get http://gopkg.in/fatih/poo l.v2?go-get=1: dial tcp 107.178.216.236:80: ConnectEx tcp: A connection attempt failed because the connected party did not...

Is there a function in the Go standard library that will encode a buffer to any image format in go

go
I'm writing a micro-service with some simple image manipulation in go. When I come to sending the manipulated image back to the user I have to encode it correctly before writing it via a buffer. I can detect the format easily enough, so it's not precisely a problem. Currently I...

Unmarshal JSON into a map in Go

json,dictionary,go
I'm having trouble figuring out how to load a "subsection" of JSON file into a map element. Background: I'm trying to unmarshal a somewhat complicated configuration file which has a strict structure, so I assume it's preferable to unmarshal into a "static" structure rather than into an interface{}. Here's a...

What is the top level interface in go? [duplicate]

go
This question already has an answer here: what is the meaning of interface{} in golang? 4 answers Or what is the interface that all types implement? I'm looking for something like the Object class in Java. Is it possible for me to make my own kind of "Root" interface?...

Build a go binary for both Linux and Mac [duplicate]

go
This question already has an answer here: Cross compile Go on OSX? 2 answers How can I go build a project in a way that it works for both Mac and Linux (x86 and x64)? Is that even possible? I searched and found some stuff, but cannot make them...

Inheritence in GoLang with data and member functions

go
I am a golang newbie so pardon me if there is something obvious I am missing. I have the following structures: type base interface { func1() func2() common_func() } type derived1 struct { base // anonymous meaning inheritence data DatumType } type derived2 struct { base // anonymous meaning inheritence...

Does Mgo cache connection strings?

mongodb,go,mgo,compose
My Go application has been connecting to a MongoDB (hosted on Compose.io) using MGO with no issues. Today I decided to delete this database and add a different one (again using Compose). I updated the connection string. So I connect using: db, err := mgo.Dial("mongodb://<username>:<password>@dogen.mongohq.com:10048/db-name") with the username and password...

How do I represent an Optional String in Go?

string,go,null,optional,variant
I wish to model a value which can have two possible forms: absent, or a string. The natural way to do this is with Maybe String, or Optional<String>, or string option, etc. However, Go does not have variant types like this. I then thought, following Java, C, etc., that the...

In html/templates is there any way to have a constant header/footer across all pages?

go,go-html-template
Reading the docs wasn't particularly helpful and I want to know if the structure {{header}} {{content that always changes}} {{footer}} is achievable with golang....

Running multi-file go program

go
So I'm pretty new to go and I'm trying to follow this tutorial - http://thenewstack.io/make-a-restful-json-api-go/ Right now, this is my file structure - EdData/ dataEntry/ populateDb.go main.go handlers.go routes.go When I run go run main.go, I get this error ./main.go:11: undefined: NewRouter This is what my main.go looks like -...

Handle response from post request to Json

go
I'm using the following code to get a response from a server after a post request: type ResponseFromPost struct { N_expediente string Enviar string } func main(){ ...... res, err := client.Do(req) if err != nil { return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) var re ResponseFromPost err =...

single ampersand between 2 expressions in golang

go
I was looking at golang source code, module math/rand. I found there one interesting line if n&(n-1) == 0 { // n is power of two, can mask I'm just curious, what does n&(n-1) mean? I would understand n && (n-1). It would be AND operator between 2 boolean expressions....

Golang overflows int64

go,biginteger,int64
I try to use this code, but gives me an error: constant 100000000000000000000000 overflows int64 How can I fix that ? // Initialise big numbers with small numbers count, one := big.NewInt(100000000000000000000000), big.NewInt(1) ...

Serving Static Files with a HTTP 500 Status

go
Is there a way to serve static files over HTTP in Go with a custom status code (without re-writing a significant amount of private code)? From what I can see: http.ServeFile calls the helper function http.serveFile It then calls http.ServeContent after determining the mod time and size of the file/dir...

measure execution time and stop waiting if too long in golang

go
I am trying to measure execution time of funcWithUnpredictiveExecutionTime function. func measureTime(expectedMs float64) (ok bool) { t1 := time.Now() funcWithUnpredictiveExecutionTime() t2 := time.Now() diff := t2.Sub(t1) The measuring is fine when funcWithUnpredictiveExecutionTime works faster than I expected. But if it works slower than expectedMs the measuring will not stop right...

Go program not statically linked using 1.4.2

go,static-linking
Trying to build a statically linked version of a go program that runs an http server, and uses the net package to determine and parse the IP address of the incoming request. With this build statement: CGO_ENABLED=0 go install -a -ldflags '-s' . And this preamble in my program: package...

multiline input in a terminal Go application

go
I need to let a user input multiline text to the console. Here is my code: package main import ( "bufio" "fmt" "os" ) func main() { for { fmt.Println("How to read all lines here?") in := bufio.NewReader(os.Stdin) result, err := in.ReadString('\n') if err != nil { fmt.Println(err) } fmt.Println("\nresult")...

golang goroutine use SSHAgent auth not work well and throw some unexpect panic

go,ssh-agent
I am writing a little tool for excuting commands paiallelly on many different hosts. All the hosts could login with a same private key. So, I want to use SSHAgent to get auth to login. When I use it for a single host, it works well. But when I use...

Golang - using/iterating through JSON parsed map

json,parsing,go
With PHP and Javascript (and Node) parsing JSON is a very trivial operation. From the looks of it Go is rather more complicated. Consider the example below package main import ("encoding/json";"fmt") type fileData struct{ tn string size int } type jMapA map[string] string type jMapB map[string] fileData func parseMapA(){ var...

Getting syntax error: unexpected comma, expecting {

go
I was trying for, break and continue in golang and I did this... func main() { for k, i := 0, 0; i < 10; i++, k++ { for j := 0; j < 10; j++ { if k == 10 { fmt.Println("Value of k is:", k) break } }...

golang The zero value of a slice is not nil.

go,slice
I was following the example https://tour.golang.org/moretypes/10 I modified the code expecting to get the same result. I did not. Is this a bug, or a documentation error? The tour states A nil slice has a length and capacity of 0. My y variable has a length and capacity of 0....

Why using naked return and the normal return give me different results?

go,rot13
I'm playing around with Golang tour and I wonder why using naked return give me the correct result but the normal one doesn't. This is the exercise that I have this problem https://tour.golang.org/methods/12. The objective is to create a reader that can decipher rot13. and the rot13 function is already...

Where is the retrying logic in the Google Cloud Storage go client?

go,google-cloud-storage
Some Google documentation for the go client for Cloud Storage says: This library supports reading and writing large amounts of data to Cloud Storage, with internal error handling and retries, so you don't have to write your own code to do this. However, when using the below snippet of code...

More strict compile options in GoLang

go
Is there an option in golang to fail build if a function returns a value and the returned value is not used? For example, I want an error / warning when we have: func abc() error and it is called without an lvalue as: abc() EDIT: This is not for...

How to interpolate a byte slice?

go
I'm attempting to build a JSON payload for a POST request: var payload = []byte(`{"foo":"bar", "hello":"world"}`) However, I would like the values to be interpolated from an existing string. I've tried to use %s, but this is obviously not syntactically correct: var payload = []byte(`{"foo":%s, "hello":%s}`, val1, val2) Feels like...

Which channel type uses the least amount of memory in Go?

memory,go,resources,channel,internals
I find myself frequently using channels to get things to stop. In these cases the channel is being used solely as a means of signaling, and none of the data is actually used. For example: package main import ( "fmt" "time" ) func routine(stopChan chan bool) { fmt.Println("goroutine: I've started!")...

http.newRequest not sending post data

php,go
I have the following code to send post data to a server, but the server is not detecting any post data on the request. Client code: cookieJar, _ := cookiejar.New(nil) client := &http.Client{ Jar: cookieJar, } postUrl := os.Args[1] username := os.Args[2] password := os.Args[3] data := url.Values{} data.Set("username", username)...

How to change a float64 number to uint64 in a right way?

go,floating-point,type-conversion,floating-point-conversion
package main func main() { var n float64 = 6161047830682206209 println(uint64(n)) } The output will be: 6161047830682206208 It looks like that when float64 change to uint64, the fraction is discarded....

Does exist on Go something like macros in C++ like #ifdef so I can choose what to build based on flag?

go
I need to build in go for linux and windows with different packages same file on windows I need to import github.com/hashicorp/go-syslog and on linux import log/syslog and inside code in file I have to use syslog.ALERT or gsyslog.ALERT depending on os. Does exist on Go something like macros in...

Server initiated requests

http,go,http2
I know that http is a request-response protocol, the problem in short is a client makes a request to the server to start a long running process, and i want to inform the client over the progress with a simple json message containg progress info. in http1 i know that...

Error when using AWS-SDK-GO (NoCredentialProviders: no valid providers in chain)

amazon-web-services,go
I've recently started using the aws-sdk-go package. Walking through the instructions, my folder structure is as follows: bin/ , pkg/ (as always) src/ app/main.go (code taken from the docs) github.com/aws Now when I run go install, and then execute the app.exe (using windows here), I'm getting the following error: panic:...

Find the shortest path sum in a matrix. Is Dijkstra not optimal for this case?

algorithm,go
I am trying to solve the following problem from project euler (please take a look at description and the example in the link, but here is the short explanation). in the matrix, find the minimal path sum from the top left to the bottom right, by moving left, right, up,...

'invalid memory address' error with go-mssql

go
I'm having an issue that I can't seem to resolve, probably due to my inexperience with GO. I have the following code working on one server, but not on another. Here is the code: // Build out the connection string to the database, and then open the connection to the...

How do I get all the attributes of an XML element using Go?

go
I am trying to parse xml content along with all the attributes of an XML element like this type Node struct { XMLName xml.Name Attributes []xml.Attr `xml:",attr"` BodyElements string `xml:",innerxml"` Nodes []Node `xml:",any"` } var xmldata = []byte("<div><div data-id=\"images/6C7161080\" data-imagesize=\"medium\" data-alignment=\"none\"></div></div>") func walk(nodes []Node, f func(Node) bool) { for _,...

how to use share memory with Golang? [closed]

go,ipc
How does golang share or read other processes shared memory? I've checked some information, but did not find relevant information. Can anyone give me an example?

How do I synchronize a variable number of channels in Go?

go
I am testing out concurrency in Go by writing a client (in the form of a web server) that makes many requests to a web server and then returns how long it took to make those requests. Basically a benchmark tool. Here is to code I am using currently: main.go...

Print out repository releases with go-github

go,github-api
I am very new to Go and am having issues printing out all releases for a given repo using the go-github api. I am adapting my code from the example in the project here. This is the code I have so far. package main import ( "fmt" "github.com/google/go-github/github" "golang.org/x/oauth2" )...

How to keep a strong reference in Go?

arrays,go,slice
Is there any way I can keep a strong reference in Go? Given the following convoluted piece of code: package main import ( "fmt" ) func main() { slice := make([]int, 5) slice[3] = 25 // whatever index between 0 and 4 included I don't care slicesArray := make([]*[]int, 2)...

How to parse parameters from POST body to map[string] string?

go
How to parse parameters from POST body to map[string] string? I am using gin and I can parse to predefined structure but in this case I don't know key names. ( I can when I know key names but when I don't know is a problem ) type Body struct...

Why does adding parentheses in if condition results in compile error?

syntax,go,syntax-error
The following Go code runs OK: package main import "fmt" func main() { if j := 9; j > 0 { fmt.Println(j) } } But after adding parentheses in condition: package main import "fmt" func main() { if (j := 9; j > 0) { fmt.Println(j) } } There is...