how can i properly vendor github.com/docker/docker? - api

here my main.go
package cmd
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
func main() {
cli, err := client.NewClientWithOpts(client.WithVersion("1.38"))
if err != nil {
panic(err)
}
networks, err := cli.NetworkList(context.Background(), types.NetworkListOptions{})
if err != nil {
panic(err)
}
fmt.Println(networks)
}
i tried to run dep init but vendor folder ended up with an older version of docker/docker because the newest tag is 17.05 tried to pin the actual commit but that did not work either
i give a shot to go mod vendor but that also rely on git tags
Strangely enough docker/docker is an alias to moby/moby and docker/engine.
Anyone could explain me and give example how can i successfully use vendoring with docker API?

[[constraint]]
name = "github.com/docker/docker"
branch = "master"
[[override]]
name = "github.com/docker/distribution"
branch = "master"
Actually this two entries helped solve the dependency issue in Gopkg.toml, then running dep ensure

Related

Tarantool broadcast call

I have cluster with several replicasets. I want to call some stored function on all nodes without calculate bucket_id, and after to map results. How should I do it?
You can use module cartridge.rpc function get_candidates for getting all nodes with some role, which you want to call and after to use module cartridge.pool function map_call for calling your function and mapping results. This function available from 1.2.0-17 version of cartridge. So your code could be like this:
local cartridge = require('cartridge')
local nodes = cartridge.rpc_get_candidates('my_role_name', { leaders_only = true, healthy_only = true })
local pool = require('cartridge.pool')
local results, err = pool.map_call('_G.my_function_name', { func_args }, { uri_list = nodes, timeout = 10 })
if (err ~= nil) then
#your error handling#
end
All function response will be saved to results variable and mapped for every URI. All errors will be saved to err variable as map with keys: line, class_name, err, file, suberrors, str
Another proposal.
If you use vshard and want to perform map-reduce over storages:
local replicaset, err = vshard.router.routeall()
for _, replica in pairs(replicaset) do
local _, err = replica:callrw('function', { args })
if err ~= nil then
return nil, err
end
end

Write datas from Stripe API in a CSV file in golang

I am trying to retrieve Stripe datas and parse them into a CSV file.
Here is my code:
package main
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/invoice"
"fmt"
"os"
"encoding/csv"
)
func main() {
stripe.Key = "" // I can't share the API key
params := &stripe.InvoiceListParams{}
params.Filters.AddFilter("limit", "", "3")
params.Filters.AddFilter("status", "", "paid")
i := invoice.List(params)
// Create a CSV file
csvdatafile, err := os.Create("./mycsvfile.csv")
if err != nil {
fmt.Println(err)
}
defer csvdatafile.Close()
// Write Unmarshaled json data to CSV file
w := csv.NewWriter(csvdatafile)
//Column title
var header []string
header = append(header, "ID")
w.Write(header)
for i.Next() {
in := i.Invoice()
fmt.Printf(in.ID) // It is working
w.Write(in) // It is not working
}
w.Flush()
fmt.Println("Appending succed")
}
When I am running my program with go run *.go I obtain the following error:
./main.go:35:10: cannot use in (type *stripe.Invoice) as type []string in argument to w.Write
I think I am not far from the solution.
I just need to understand how to write correctly in the CSV file thank's to w.Write() command.
According to the doc, the Write function is:
func (w *Writer) Write(record []string) error
That is, it is expecting you to pass a slice of strings representing a line of CSV data with each string being a slice. So, if you have only one field, you have to pass a string slice of 1:
w.Write([]string{in.ID})

Tables not getting created in Postgresql using Gorm

I am trying to create a table from a struct using the following code. It had initially worked by hard coding the credentials to test. Once changing to env vars, I wanted to test that the tables and schemas would get created as expected.
So far I have tried:
Removing the tables from the db, running "go run main.go".
Result: Established connection successfully to the db, but tables do not get created.
Deleting the database, recreating the database using psql "CREATE DATABASE" command, and running "go run main.go"
Result: Established connection successfully to the db, but tables do not get created.
Use AutoMigrate, but was not able to successfully create the tables.
Debug: When I run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been coding for many years, still in the learning process.
Below are 2 files, main.go and api.go (opens db)
MAIN.GO
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/handlers"
"gitlab......"
_ "gitlab....."
)
var err error
func main() {
api := controllers.API{}
// Using env vars from a config file
api.Initialize("user=%s password=%s dbname=%s port=%s sslmode=disable")
// BIND TO A PORT AND PASS OUR ROUTER IN
log.Fatal(http.ListenAndServe(":8000", handlers.CORS()(api.Router)))
if err != nil {
panic(err.Error())
}
// Models
type Application struct {
ID string `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
Name string `json:"name"`
Ci string `json:"ci"`
// CREATE TABLES AND SCHEMA IF TABLES DO NOT EXIST
if !api.Database.HasTable(&Application{}) {
api.Database.CreateTable(&Application{})
}
API.GO
func (api *API) Initialize(opts string) {
// Initialize DB
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s port=%s sslmode=disable",
config.DB_USER, config.DB_PASSWORD, config.DB_NAME, config.PORT)
api.Database, err = gorm.Open("postgres", dbinfo)
if err != nil {
log.Print("failed to connect to the database")
log.Fatal(err)
}
fmt.Println("Connection established")
log.Printf("Postgres started at %s PORT", config.PORT)
}
I have already created the database, and am able to establish a connection to the database. Just can not get the tables created.
Ideas?

Go Database Connector: go-sql-driver works, everything else "unknown driver, forgotten import?"

When I try to use database/sql in this way it compiles and works:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
But if I try to use postgres specific connectors it doesn't even compile:
import(
"database/sql"
_ "github.com/lib/pq"
)
import(
"database/sql"
_ "github.com/jbarham/gopgsqldriver"
)
both fail with the error
sql: unknown driver "mysql" (forgotten import?)
I have done go get for both of these packages, and am really not sure why it is not compiling
Are you doing
db, err := sql.Open("mysql",
later on? When you import "github.com/lib/pq" for example, it registers itself by calling sql.Register, and then in the source of sql.Open you have:
func Open(driverName, dataSourceName string) (*DB, error) {
driversMu.RLock()
driveri, ok := drivers[driverName]
driversMu.RUnlock()
if !ok {
return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
}
}
So, since you are no longer importing mysql, you need to change sql.Open to use the pq driver (or whichever one you end up picking).

How to test the passing of arguments in Golang?

package main
import (
"flag"
"fmt"
)
func main() {
passArguments()
}
func passArguments() string {
username := flag.String("user", "root", "Username for this server")
flag.Parse()
fmt.Printf("Your username is %q.", *username)
usernameToString := *username
return usernameToString
}
Passing an argument to the compiled code:
./args -user=bla
results in:
Your username is "bla"
the username that has been passed is displayed.
Aim: in order to prevent that the code needs to be build and run manually every time to test the code the aim is to write a test that is able to test the passing of arguments.
Attempt
Running the following test:
package main
import (
"os"
"testing"
)
func TestArgs(t *testing.T) {
expected := "bla"
os.Args = []string{"-user=bla"}
actual := passArguments()
if actual != expected {
t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual)
}
}
results in:
Your username is "root".Your username is "root".--- FAIL: TestArgs (0.00s)
args_test.go:15: Test failed, expected: 'bla', got: 'root'
FAIL
coverage: 87.5% of statements
FAIL tool 0.008s
Problem
It looks like that the os.Args = []string{"-user=bla is not able to pass this argument to the function as the outcome is root instead of bla
Per my comment, the very first value in os.Args is a (path to) executable itself, so os.Args = []string{"cmd", "-user=bla"} should fix your issue. You can take a look at flag test from the standard package where they're doing something similar.
Also, as os.Args is a "global variable", it might be a good idea to keep the state from before the test and restore it after. Similarly to the linked test:
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
This might be useful where other tests are, for example, examining the real arguments passed when evoking go test.
This is old enough but still searched out, while it seems out dated.
Because Go 1.13 changed sth.
I find this change helpful, putting flag.*() in init() and flag.Parse() in Test*()
-args cannot take -<test-args>=<val> after it, but only <test-args>, otherwise the test-args will be taken as go test's command line parameter, instead of your Test*'s