Code Answers

Golang bug or intended feature on map literals

Just started to learn Go and I need map of string string, that I initialize literally. mapa := map[string]string{ "jedan":"one", "dva":"two" } But compiler is complaining syntax error: need trailing comma before newline in composite literal So I had to add coma after "two", or delete a new line and have } after last valu...

Golang declaring variables as NULLs

As per the example below, I need to get email and firstname and dateofbirth and so on as NullStrings and NullTimes as required, as my User struct is using them. How do I declare variables as NULLs package entities import ( "database/sql" "github.com/go-sql-driver/mysql" "testing" "time" ) var ( email = sql.NullStr...

Go: One producer many consumers

So I have seen a lot of ways of implementing one consumer and many producers in Go – the classic fanIn function from the Concurrency in Go talk. What I want is a fanOut function. It takes as a parameter a channel it reads a value from and returns a slice of channels that it writes copies of this value to. Is there a correct/recommended way of ...

Go: what determines the iteration order for map keys

The Go Programming Language Specification says: 3. The iteration order over maps is not specified. […] That's to be expected since a map type can be implemented as a hash table, or as a search tree, or as some other data structure. But how is map actually implemented in Go? Put differently, what determines the iteration order of the keys in f...

Go – Local import in non-local package

I know local imports should be avoided, however special circumstances demand it in this case. It's a private repo, and the heroku buildpack fails in the go get ./... phase when used with absolute urls, due to a missing private key on the server. Now I get this error local import ".." in non-local package. All import paths were changed to the lo...

Go – convert string which represent binary number into int

I wrote a stupid solution for this, any better recipe? As you can see lots of useless conversions there. package main import ( "fmt" "strconv" "math" ) func conv(str string) int { l := len(str) result := 0.0 for i,n := range str { number,_ := strconv.Atof64(string(n)) result += math.Exp2(float64(l-i-1))...

Golang compile environment variable into binary

If I compile this program package main import ( "fmt" "os" ) var version = os.Getenv("VERSION") func main() { fmt.Println(version) } It prints the env var when I run it VERSION="0.123" ./example > 0.123 Is there a way to compile the env var into the binary, for example: VERSION="0.123" go build example.go Then get the same out...

Golang: Use one value in conditional from function returning multiple arguments

Suppose in Go we have a function returning two arguments func squareAndCube(int side) (square int, cube int) { square = side * side cube = square * side return } Then you would like to use the first (second) value of this function in the conditional: square, _ := squareAndCube(n) if square > m { ... } However, can we do first ...

Go – Runtime error: “assignment to entry in nil map”

I'm trying to create a slice of Maps. Although the code compiles fine, I get the runtime error below: mapassign1: runtime·panicstring("assignment to entry in nil map"); I attempt to make an array of Maps, with each Map containing two indicies, a "Id" and a "Investor". My code looks like this: for _, row := range rows { var inv_ids []s...

Golang methods with same name and arity, but different type

The following code works fine. Two methods operating on two different structs and printing a field of the struct: type A struct { Name string } type B struct { Name string } func (a *A) Print() { fmt.Println(a.Name) } func (b *B) Print() { fmt.Println(b.Name) } func main() { a := &A{"A"} b := &B{"B"} a.Print() b.Print() } ...

Golang http mux change handler function

I am fairly new to Go and have not been able to find any information on this, maybe it is just not possible at this time. I am trying to delete or replace a mux route (using http.NewServeMux, or gorilla's mux.Router). My end goal is to be able to enable/disable a route or set of routes without having to restart the program. I can probably acco...

Go modules: checksum mismatch

I recently started using modules in Go, but I frequently encounter issues where everything works fine on one machine, but a checksum mismatch is encountered when building the codebase on another machine. The issue always concerns the same third party dependency (github.com/ericlagergren/decimal): go: verifying github.com/ericlagergren/[email protected]

Go modules installing go tools

I'm using go modules as dependency management, and I'm having problem to install something like this: go get -u github.com/go-critic/go-critic/... the result from above was: go: cannot find main module; see 'go help modules' Solution to answer: Edit: The original answer herein referred specifically to the state of the tooling in Go 1.1...

Golang struct initialization

There is a simple struct like this: type Event struct { Id int Name string } What is the difference between these two initialization methods? e1 := Event{Id: 1, Name: "event 1"} e2 := &Event{Id: 2, Name: "event 2"} Any why would I use either of these initialization methods? Solution to answer: The first method e1 ...

Golang gin gonic web framework proxy route to another backend

How to reverse proxy web requests for a few routes to another backend in Gin Gonic web golang framework Is there a way to directly forward in the Handle function as shown below? router := gin.New() router.Handle("POST", "/api/v1/endpoint1", ForwardToAnotherBackend) Solution to answer: This was the solution I used for reverse-proxying a...

Go Resizing Images

I am using the Go resize package here: https://github.com/nfnt/resize I am pulling an Image from S3, as such: image_data, err := mybucket.Get(key) // this gives me data []byte After that, I need to resize the image: new_image := resize.Resize(160, 0, original_image, resize.Lanczos3) // problem is that the original_image has to be of type i...

Json parsing of int64 in go; null values

I'm trying to parse a json stream in Go. I've created a simplified example: package main import ( "encoding/json" "fmt" ) var d = []byte(`{ "world":[{"data": 2251799813685312}, {"data": null}]}`) type jsonobj struct{ World []World } type World struct{ Data int64 } func main() { var data jsonobj jerr := json.Unmarshal(d...

Golang returning functions

Can anyone explain why 0's and 1's are printed and not anything else? Thank you! func makeFunction(name string) func() { fmt.Println("00000") return func() { makeFunction2("abcef") } } func makeFunction2(name string) func() { fmt.Println("11111") return func() { makeFunction3("safsf") } } func makeFun...

Json unmarshal embedded struct

I would like to unmarshal to struct Outer defined as: type Outer struct { Inner Num int } type Inner struct { Data string } func (i *Inner) UnmarshalJSON(data []byte) error { i.Data = string(data) return nil } Using json.Unmarshal(data, &Outer{}) seems only to use Inner's UnmarshalJSON and ignores the Num field: https://pl...

Goland how to use gofmt

I started learning golang and installed GoLand from JetBrains. I am reading the book The Go Programming Language, and in the first chapter author strongly recommends using the gofmt tool before each save. How I can follow this recommendation in GoLand? Solution to answer: There are ways to format your code , you can do that by using any...