74,477 questions
336
votes
2
answers
560k
views
Converting Go struct to JSON [duplicate]
I am trying to convert a Go struct to JSON using the json package but all I get is {}. I am certain it is something totally obvious but I don't see it.
package main
import (
"fmt"
"encoding/...
332
votes
9
answers
407k
views
Handling JSON Post Request in Go
So I have the following, which seems incredibly hacky, and I've been thinking to myself that Go has better designed libraries than this, but I can't find an example of Go handling a POST request of ...
332
votes
20
answers
394k
views
What's the proper way to "go get" a private repository?
I'm searching for the way to get $ go get work with private repository, after many google try.
The first try:
$ go get -v gitlab.com/secmask/awserver-go
Fetching https://gitlab.com/secmask/...
329
votes
11
answers
257k
views
Constructors in Go
I have a struct and I would like it to be initialised with some sensible default values.
Typically, the thing to do here is to use a constructor but since go isn't really OOP in the traditional sense ...
321
votes
4
answers
168k
views
How to `go test` all tests in my project?
The go test command covers *_test.go files in only one dir.
I want to go test the whole project, which means the test should cover all *_test.go files in the dir ./ and every children tree dir under ...
320
votes
7
answers
351k
views
List directory in Go
I've been trying to figure out how to simply list the files and folders in a single directory in Go.
I've found filepath.Walk, but it goes into sub-directories automatically, which I don't want. All ...
319
votes
15
answers
365k
views
Is there a way to iterate over a range of integers?
Go's range can iterate over maps and slices, but I was wondering if there is a way to iterate over a range of numbers, something like this:
for i := range [1..10] {
fmt.Println(i)
}
Or is there a ...
316
votes
10
answers
190k
views
Type converting slices of interfaces
I'm curious why Go does't implicitly convert []T to []interface{} when it will implicitly convert T to interface{}. Is there something non-trivial about this conversion that I'm missing?
Example:
...
315
votes
5
answers
81k
views
What does an underscore in front of an import statement mean?
In this code from go-sqlite3:
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
what ...
307
votes
6
answers
294k
views
How can I read a whole file into a string variable
I have lots of small files, I don't want to read them line by line.
Is there a function in Go that will read a whole file into a string variable?
302
votes
17
answers
344k
views
Removing fields from struct or hiding them in JSON Response
I've created an API in Go that, upon being called, performs a query, creates an instance of a struct, and then encodes that struct as JSON before sending back to the caller. I'd now like to allow the ...
302
votes
2
answers
251k
views
Convert byte slice to io.Reader
In my project, I have a byte slice from a request's response.
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Println("StatusCode为" + strconv.Itoa(resp.StatusCode))
return
}
...
299
votes
9
answers
329k
views
How do you print in a Go test using the "testing" package?
I'm running a test in Go with a statement to print something (i.e. for debugging of tests) but it's not printing anything.
func TestPrintSomething(t *testing.T) {
fmt.Println("Say hi")
}
When I ...
298
votes
4
answers
284k
views
What is the `zero` value for time.Time in Go?
In an error condition, I tried to return nil, which throws the error:
cannot use nil as type time.Time in return argument
What is the zero value for time.Time?
297
votes
4
answers
347k
views
How to set headers in http get request?
I'm doing a simple http GET in Go:
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
res, _ := client.Do(req)
But I can't found a way to customize the request header in the doc, ...
295
votes
11
answers
185k
views
Is it possible to capture a Ctrl+C signal (SIGINT) and run a cleanup function, in a "defer" fashion?
I want to capture the Ctrl+C (SIGINT) signal sent from the console and print out some partial run totals.
291
votes
5
answers
271k
views
Force retesting or disable test caching
Problem:
When I run the same go test twice the second run is not done at all. The results are the cached ones from the first run.
PASS
ok tester/apitests (cached)
Links
I already ...
290
votes
8
answers
342k
views
How to point Go module dependency in go.mod to a latest commit in a repo?
Starting with v1.11 Go added support for modules. Commands
go mod init <package name>
go build
would generate go.mod and go.sum files that contain all found versions for the package ...
289
votes
4
answers
278k
views
How to get the last element of a slice?
What is the Go way for extracting the last element of a slice?
var slice []int
slice = append(slice, 2)
slice = append(slice, 7)
slice[len(slice)-1:][0] // Retrieves the last element
The solution ...
288
votes
9
answers
416k
views
How to set default values in Go structs
There are multiple answers/techniques to the below question:
How to set default values to golang structs?
How to initialize structs in golang
I have a couple of answers but further discussion is ...
282
votes
6
answers
350k
views
Declare a constant array
I have tried:
const ascii = "abcdefghijklmnopqrstuvwxyz"
const letter_goodness []float32 = { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,....
280
votes
8
answers
93k
views
Is it OK to leave a channel open?
Is it OK to leave a Go channel open forever (never close the channel) if I never check for its state? Will it lead to memory leaks? Is the following code OK?
func (requestCh chan<- Request) ...
279
votes
14
answers
82k
views
Does Go provide a REPL?
The interactive environment is VERY helpful for a programmer. However, it seems Go does not provide it. Is my understanding correct?
278
votes
9
answers
248k
views
How does Go update third-party packages?
Looking how actively golang packages grow and improve I wonder how the problem with package versions is solved?
I see that one way is to store third-party packages under a project folder.
But what ...
278
votes
5
answers
297k
views
cannot convert data (type interface {}) to type string: need type assertion
I am pretty new to go and I was playing with this notify package.
At first I had code that looked like this:
func doit(w http.ResponseWriter, r *http.Request) {
notify.Post("my_event", "Hello ...
275
votes
8
answers
241k
views
What is the shortest way to simply sort an array of structs by (arbitrary) field names?
I just had a problem where I had an array of structs, e.g.
package main
import "log"
type Planet struct {
Name string `json:"name"`
Aphelion float64 `json:"aphelion"` // in ...
272
votes
9
answers
355k
views
Import cycle not allowed
I have a problem with
import cycle not allowed
It appears when I am trying to test my controller. Here is the output:
can't load package: import cycle not allowed
package project/controllers/account
...
272
votes
8
answers
294k
views
Can functions be passed as parameters?
In Java I can do something like
derp(new Runnable { public void run () { /* run this sometime later */ } })
and "run" the code in the method later. It's a pain to handle (anonymous inner class), but ...
269
votes
14
answers
230k
views
"undefined" function declared in another file?
I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:
undefined: NewEmployee
Here is the source code:
main.go:
...
265
votes
13
answers
472k
views
The maximum value for an int type in Go
How does one specify the maximum value representable for an unsigned integer type?
I would like to know how to initialize min in the loop below that iteratively computes min and max lengths from some ...
263
votes
3
answers
301k
views
Go test string contains substring
How do I check if a string is a substring of another string in Go?
For example, I want to check someString.contains("something").
261
votes
4
answers
178k
views
Golang tests in sub-directory
I want to create a package in Go with tests and examples for the package as subdirectories to keep the workspace cleaner. Is this possible and if so how?
All the documentation always puts the ...
260
votes
8
answers
412k
views
Parsing RFC-3339 / ISO-8601 date-time string in Go
I tried parsing the date string "2014-09-12T11:45:26.371Z" in Go. This time format is defined as:
RFC-3339 date-time
ISO-8601 date-time
Code
layout := "2014-09-12T11:45:26.371Z"
...
260
votes
12
answers
82k
views
How does Go compile so quickly?
I've Googled and poked around the Go website, but I can't find an explanation for Go's extraordinary build times. Are they products of the language features (or lack thereof), a highly optimized ...
260
votes
7
answers
175k
views
Organizing a multiple-file Go project [closed]
Note: this question is related to this one, but two years is a very long time in Go history.
What is the standard way to organize a Go project during development ?
My project is a single package ...
258
votes
6
answers
74k
views
Stack vs heap allocation of structs in Go, and how they relate to garbage collection
I'm experiencing a bit of cognitive dissonance between C-style stack-based programming, where automatic variables live on the stack and allocated memory lives on the heap, and Python-style stack-based-...
258
votes
4
answers
85k
views
Value receiver vs. pointer receiver
It is very unclear for me in which case I would want to use a value receiver instead of always using a pointer receiver.
To recap from the docs:
type T struct {
a int
}
func (tv T) Mv(a int) int ...
257
votes
12
answers
456k
views
How to import local packages in go?
I am new to go and working on an example code that I want to localize.
In the original main.go import statement it was:
import (
"log"
"net/http"
"github.com/foo/...
256
votes
5
answers
320k
views
Default value in Go's method
Is there a way to specify default value in Go's function? I am trying to find this in the documentation but I can't find anything that specifies that this is even possible.
func SaySomething(i string ...
248
votes
12
answers
235k
views
How to properly seed random number generator
I am trying to generate a random string in Go and here is the code I have written so far:
package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println(...
248
votes
8
answers
235k
views
How to trim leading and trailing white spaces of a string?
Which is the effective way to trim the leading and trailing white spaces of string variable in Go?
248
votes
3
answers
731k
views
How can I install a package with go get?
I want to install packages from github to my $GOPATH, I have tried this:
go get github.com:capotej/groupcache-db-experiment.git
the repository is here.
245
votes
3
answers
343k
views
How to join a slice of strings into a single string?
package main
import (
"fmt"
"strings"
)
func main() {
reg := [...]string {"a","b","c"}
fmt.Println(strings.Join(reg,","))
}
gives me an error of:
prog.go:10: cannot use reg (type [3]string) as ...
243
votes
5
answers
387k
views
Access HTTP response as string in Go
I'd like to parse the response of a web request, but I'm getting trouble accessing it as string.
func main() {
resp, err := http.Get("http://google.hu/")
if err != nil {
// handle ...
242
votes
8
answers
122k
views
Application auto build versioning
Is it possible to increment a minor version number automatically each time a Go app is compiled?
I would like to set a version number inside my program, with an autoincrementing section:
$ myapp -...
238
votes
16
answers
540k
views
Error message "go: go.mod file not found in current directory or any parent directory; see 'go help modules'"
I just updated to the new version of Go - Go version 1.16.2 Linux/amd64 and am getting an error when I build a Hello, World! example:
go: go.mod file not found in current directory or any parent ...
238
votes
7
answers
211k
views
Does a break statement break from a switch/select?
I know that switch/select statements break automatically after every case. I am wondering, in the following code:
for {
switch sometest() {
case 0:
dosomething()
case 1:
...
233
votes
16
answers
334k
views
How to measure test coverage in Go
Has anyone succeeded in generating code coverage for Go unit tests? I can't find a tool for that on the web.
232
votes
11
answers
211k
views
How to pad a number with zeros when printing?
How can I print a number or make a string with zero padding to make it fixed width?
For instance, if I have the number 12 and I want to make it 000012.
232
votes
9
answers
143k
views
How can I "go run" a project with multiple files in the main package?
I have a single file in the main package called main.go. Because the code isn't reusable I want to separate part of the code in a different file but in the same package.
How do I split the contents of ...