Menu
  • HOME
  • TAGS

How do I wrapper a function with variadic parameters

Tag: go

In Go, it's possible to prefix the final parameter in a function with the ... notation to indicate it is a variadic parameter.

template.ParseFiles is one such function:

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

I am trying to create a function of my own which sets up various common features of my templates and I'd like the calling function to pass in the list of files that need to be parsed but I'm not sure how.

For example if my code looked like this:

type templateMap map[string]*template.Template
func (tmpl templateMap) AddTemplate(name string, files ...string) {
    tmpl[name] = template.Must(template.ParseFiles(files)).Delims("{@","@}")
}

I get an error:

cannot use files (type []string) as type string in function argument

How do I wrapper variadic parameters?

Best How To :

To pass a slice in place of the variadic argument of a function, simply suffix it with .... So in your example code, you would instead want:

tmpl[name] = template.Must(template.ParseFiles(files...)).Delims("{@","@}")

Here is a simple example of the concept: http://play.golang.org/p/TpYNxnAM_5

Does Mgo cache connection strings?

mongodb,go,mgo,compose

No, mgo does not cache the connection strings you give to the mgo.Dial function. It's not even clear to me what that would mean? Using an incorrect database name after you explicitly asked it to connect to a different database would be a serious bug, rather than caching. As for...

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

image,go,martini

The call uploader.Upload reads to the end of the file. Seek back to the beginning of the file before calling CreateThumbnail: func UploadToS3(file multipart.File, /*snip*/) { _, uploadErr := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String(bucket), Key: aws.String(key), Body: file, ContentType: aws.String(mimeType), ACL: aws.String("public-read"), }) // Seek back to beginning of file for CreateThumbnail...

'invalid memory address' error with go-mssql

go

There is probably an error with db.Query. Check your error and if it is not nil, assume that rows is nil. i.e. calling rows.Next() will segfault. If you display the error, you will probably find out what the issue is.

Golang switch between structs

struct,go,interface,switch-statement

In your example you are trying to pass the struct itself to the function rather than an instance of the struct. When I ran your code it wouldn't compile. I agree with the comments above though, this would be much better handled by making sure each struct satisfies the fmt.Stringer...

Correct use of go context.Context

concurrency,go,gorilla

You have a problem with your code because you are storing the user into the app context. With multiple users at the same time, it doesn't work. The context must be related to the request to not be overwrote by other requests. The user must be stored in a request...

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

windows,git,powershell,github,go

The root cause has been found: Because my computer use a web proxy, so I need to set proxy in environment variable: C:\Users\xiaona>set https_proxy=https://web-proxy.corp.hp.com:8080/ C:\Users\xiaona>set http_proxy=https://web-proxy.corp.hp.com:8080/ C:\Users\xiaona>go get -v gopkg.in/fatih/pool.v2 Fetching https://gopkg.in/fatih/pool.v2?go-get=1 Parsing meta tags from https://gopkg.in/fatih/pool.v2?go-get=1 (status code 200) get "gopkg.in/fatih/pool.v2": found meta tag main.metaImport{Prefix:"gopkg.in/fa tih/pool.v2", VCS:"git",...

Go Yaml Interpretation Example

go,yaml

The contents of the example yaml file are sequence of objects, so do it like this: package main import ( "fmt" "log" "gopkg.in/yaml.v2" ) type Config struct { Foo string Bar []string } var data = ` - foo: 1 bar: - one - two - three - foo: 2...

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

go

I can't understand why this is not the same, as explicitly writing nil in the Exec functions parameter, since the []byte clearly must be nil, right? nil has a type. The database driver marshals nil differently for type map[string]interface{} or []byte than for interface{} (which is the type of...

Getting a PHP configuration variable in Go

php,go

The problem is your argument. If you change what you have written into a shell command, it would look like the following: $ php -r "'echo get_cfg_var(\"default_mimetype\");'" You will notice that there is an extra set of quotes around the 2nd argument that is causing the syntax error. You can...

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

go,floating-point,type-conversion,floating-point-conversion

The problem here is the representation of constants and floating point numbers. Constants are represented in arbitrary precision. Floating point numbers are represented using the IEEE 754 standard. Spec: Constants: Numeric constants represent values of arbitrary precision and do not overflow. Spec: Numeric types: float64 the set of all IEEE-754...

Run Golang as www-data

security,go

Expanding on @JimB's answer: Use a process supervisor to run your application as a specific user (and handle restarts/crashes, log re-direction, etc). setuid and setgid are universally bad ideas for multi-threaded applications. Either use your OS' process manager (Upstart, systemd, sysvinit) or a standalone process manager (Supervisor, runit, monit, etc)....

Server initiated requests

http,go,http2

Before websockets we had polling. This literally means having the client periodically (every few seconds, or whatever time period makes sense for your application), make a request to the server to find out the status of the job. An optimization many people use is "long" polling. This involves having the...

How to make this code more performant?

performance,go,hashmap

You don't need the outer loop as one improvement: func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) { if fieldFilter, ok := filter[relationString(msg)]; ok { for _, f := range msg.Fields { if _, ok := fieldFilter[f.Name]; ok { fs = append(fs, f) } } } } return } ...

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

syntax,go,syntax-error

The answer is not simply "because Go doesn't need parentheses"; see that the following example is a valid Go syntax: j := 9 if (j > 0) { fmt.Println(j) } Go Spec: If statements: IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block )...

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

As I said in the comment section, this can be achieved using MultiWriter package main import ( "io" "log" "os" "os/exec" ) func main() { // Logging capability f, err := os.OpenFile("log.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatalf("Error opening file: %v", err) } defer f.Close() mwriter := io.MultiWriter(f,...

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

string,go

What about using bufio.ReadString instead of fmt.Scanln? Not 100% how Scanln works, but I am pretty sure the issue comes from a misuse of that function. Example with bufio: package main import ( "bufio" "fmt" "io/ioutil" "log" "os" "strings" ) // Document represent the document's data. type Document struct {...

Handling Custom BSON Marshaling (Golang & mgo)

json,mongodb,go,bson

Custom bson Marshalling/Unmarshalling works nearly the same way, you have to implement the Getter and Setter interfaces respectively Something like this should work : type Currency struct { value decimal.Decimal //The actual value of the currency. currencyCode string //The ISO currency code. } // GetBSON implements bson.Getter. func (c Currency)...

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

go

This is what build tags are for: A build constraint, also known as a build tag, is a line comment that begins // +build that lists the conditions under which a file should be included in the package. Constraints may appear in any kind of source file (not just Go),...

How check error codes with couchbase gocb?

go,couchbase

Can this be done? In gocbcore, error.go we have the following definition: type memdError struct { code StatusCode } // ... func (e memdError) KeyNotFound() bool { return e.code == StatusKeyNotFound } func (e memdError) KeyExists() bool { return e.code == StatusKeyExists } func (e memdError) Temporary() bool {...

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

go,blockchain

Your problem lies with Blockchainr main.go following lines: var ( dataDir = flag.String("datadir", filepath.Join(btcutil.AppDataDir("btcd", false), "data"), "BTCD: Data directory") dbType = flag.String("dbtype", "leveldb", "BTCD: Database backend") ) As you can see, if you don't specify a dbtype flag it defaults to "leveldb" so it expects the datadir param to contains...

JSON decoding in golang

json,curl,go

golang use first character of the field to declare public or private for that struct. so change username to Username

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

arrays,struct,go,initialization,custom-type

So basically given these basic types: type xchr int8 type xint int type xdob float64 type xflt float32 You want to copy the bytes (memory representation) of a value of the following struct type: type VEH1 struct { // 52 bytes total p xint // 4 bytes (READ BELOW) lat_lon_ele...

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

go

To build binaries for different platforms, I use GOX Gox is a simple, no-frills tool for Go cross compilation that behaves a lot like standard go build. Gox will parallelize builds for multiple platforms. Gox will also build the cross-compilation toolchain for you. You tell it which platforms you want...

How to keep a strong reference in Go?

arrays,go,slice

TL;DR: (summary) You just need to make a copy of the slice value. A value of slice type is a descriptor to an underlying array: slice2 := slice Now slice2 will refer to the same, shared underlying array and so it will be reachable after slice is zerored. In long:...

Golang failes to change the name of imported module

go,docker,skydns

The Go compiler doesn't replace or rewrite anything, the code is just wrong. The github.com/rcrowley/go-metrics/influxdb package was written with some other influxdb client code that no longer exists. (Looks like there are a couple github issues open about this already) If you look at the current influxdb/client package, you'll see...

Unmarshal JSON into a map in Go

json,dictionary,go

I believe that is because you have extra layer of indirection in your models. type JSONType struct { FirstSet map[string]string `json:"set1"` } Should suffice. if you specify map[string]string the object in json is recognized as that map. You created a struct to wrap it but a blob of json like...

More strict compile options in GoLang

go

This is not about the compiler being strict or not. The Go Language Specification allows calling functions and methods without using their return values. You won't see any compiler options that will stop the building process on use cases which do not violate the lang spec. What you want may...

Why does my concurrent function exit prematurely in Go?

concurrency,go

A Go program exits when main returns. In this case, your program is not waiting for the final "world" to be printed in another goroutine before exiting. The following code (playground) will ensure main never exits allowing the other goroutine to finish. package main import ( "fmt" "time" ) func...

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

go

Like @JiangYD suggested, it's easier to just use one channel: type resp struct { id string i int } func Async(url string, c chan<- resp, id string, count int) { cnt := 0 for i := 0; i < count; i++ { GetPage(url) cnt = cnt + 1 if cnt...

Serving Static Files with a HTTP 500 Status

go

Wrap http.ResponseWriter: type MyResponseWriter struct { http.ResponseWriter code int } func (m MyResponseWriter) WriteHeader(int) { m.ResponseWriter.WriteHeader(m.code) } And then (for an HTTP 500): http.ServeFile(MyResponseWriter{rw, 500}, rq, "file.name") Where rw is the "actual" http.ResponseWriter and rq is the *http.Request object....

Mail with html content shows break lines or ignores newlines

email,templates,go,mandrill

Are you sending the mail as HTML? If so, you can wrap everything in the <pre> tag. If you're not using HTML, setting this header should help: Mime-Type: text/plain Also, try changing your newlines from \n to \r\n. ...

Referencing yourself inside of a struct

struct,go

You can't refer to a value inside its own declaration. You need to initialize the value first, then you can assign the method you want to use to Handler. testAuth := &Authorization{ Username: "someusername", Password: "somepassword", } testAuth.Handler = testAuth.HandleFunc auths := Authorizations{ "test": testAuth, } ...

http.newRequest not sending post data

php,go

You're posting the data as a form in the request body without a content type. You either need to put the values in the request query: r.URL.RawQuery = data.Encode() or change the Content-Type to "application/x-www-form-urlencoded": r.Header.Add("Content-Type", "application/x-www-form-urlencoded") ...

measure execution time and stop waiting if too long in golang

go

You can't cancel a goroutine, unless you design it to be canceled. You can short circuit your timing function, by using a channel to signal the completion of the function being timed: func measureTime(expectedMs float64) (ok bool) { done := make(chan struct{}) t1 := time.Now() go func() { funcWithUnpredictiveExecutionTime() close(done)...

How do I get the submit value from the request object

html,go

Given your buttons a name attriubte and then you can differentiate between them. HTML: <form action="/save" method="POST"> <div><span>Title: </span><textarea name="title" placeholder="Link">{{printf "%s" .Title}}</textarea></div> <div> <button type="submit" value="submit1" name="submit">1</button> <button type="submit" value="submit2" name="submit">2</button> </div> </form> Go: submit := r.FormValue("submit") // will be "submit1" or "submit2" ...

Trouble retrieving Has Many using Gorm

go,go-gorm

Which version of GO and GORM are you using? I've tried on my machine and this is the log: [2015-06-17 19:02:11] [12.00ms] CREATE TABLE "podcasts" ("id" integer,"title" varchar(255),"rss_url" varchar(255),"url" varchar(255) , PRIMARY KEY ("id")) [2015-06-17 19:02:11] [1.26ms] CREATE TABLE "episodes" ("id" integer,"podcast_id" integer,"title" varchar(255),"url" varchar(255),"downloaded" bool , PRIMARY KEY ("id"))...

Golang - using/iterating through JSON parsed map

json,parsing,go

In Go, unmarshaling works only if a struct has exported fields, ie. fields that begin with a capital letter. Change your first structure to: type fileData struct{ Tn string Size int } See http://play.golang.org/p/qO3U7ZNrNs for a fixed example. Moreover, if you intend to marshal this struct back to JSON, you'll...

convert chan to non chan in golang

go,type-conversion

A chan int is a channel of int values, it is not a single int value but a source of int values (or also a target, but in your case you use it as source). So therefore you can't convert chan int to int. What you can do and probably...

Golang, how to return in func FROM another func?

go,return,func

A function or method cannot control the execution (control flow) from where it was called from. You don't even have guarantee it was called from your function, it may be called to initialize a global variable for example. That being said it is the responsibility of the caller to end...

CGO converting Xlib XEvent struct to byte array?

c,go,xlib,cgo

As mentioned in the cgo documentation: As Go doesn't have support for C's union type in the general case, C's union types are represented as a Go byte array with the same length. Another SO question: Golang CGo: converting union field to Go type or a go-nuts mailing list post...

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

go,rot13

It's not a problem with returns, but in the first case you're reading the data in before transforming it and in the second case you're transforming junk in a buffer and only then reading in the data (and simply passing what has been read from the underlying reader). While this...

goroutine channels over a for loop

json,struct,go,channels

You're printing the channels info, not the data it contains. You don't want a loop, you just want to receive then print. json := <-index json.NewEncoder(os.Stdout).Encode(json) Now I do I need to point out, that code is not going to block. If you want to keep reading until all work...

Golang ORDER BY issue with MySql

mysql,database,go

Placeholders ('?') can only be used to insert dynamic, escaped values for filter parameters (e.g. in the WHERE part), where data values should appear, not for SQL keywords, identifiers etc. You cannot use it to dynamically specify the ORDER BY OR GROUP BY values. You can still do it though,...

Declare variable with format specifier in Go

go

Yes, fmt.Sprintf does that: d := "/some/dir/%s" fmt.Sprintf(d, "hello") // Returns "/some/dir/hello" ...

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

algorithm,go

Dijkstra should pass, I just make a submission using JAVA, and it took less than a second to complete each task. As I have mentioned, each value in the matrix can go up to 10^9, your solution can encounter a number overflow problem, which can effect the running time. My...

Cannot call tests inside packages other than main

go

Try this: go test my_project/... Or if you are within your project: go test ./... ...

Different performances in Go slices resize

go,stack,benchmarking,slice

Reading your code, tests, benchmarks, and results it's easy to see that they are flawed. A full code review is beyond the scope of StackOverflow. One specific bug. // Push pushes a new element to the stack func (s *Stack) Push(elem interface{}) { if len(s.slice)+1 == cap(s.slice) { slice :=...

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

xml,go,formatting,date-formatting

Just as you'd implement json.Marshaler and json.Unmarshaler for doing this with JSON (there are many posts about that on StackOverflow and the internet); one way is to implement a custom time type that implements encoding.TextMarshaler and encoding.TextUnmarshaler. Those interfaces are used by encoding/xml when encoding items (after first checking for...

Why won't mgo unmarshall my struct properly?

mongodb,go,bson,mgo

The GetBSON method should return the value to be marshaled, not the binary data resulting from marshaling it. That's why its first result type is interface{} and not []byte.

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

pointers,dictionary,go

Why won't you just check it? emp := ExampleMapHolder{make(map[string]int)} m := emp.TheMap() m["a"] = 1 fmt.Println(emp) // Prints {map[a:1]} Playground: http://play.golang.org/p/jGZqFr97_y...