Reading stdout from an exec’d process from within a golang test

I have a main.go that I would like to read its standard output from when I exec it inside one of my tests. In my app_test.go I have:

func TestShutdown(t *testing.T) { timer := time.NewTimer(4 * time.Second) cmd := exec.Command("go", "run", "cmd/testing/main.go") stdout, err := cmd.StdoutPipe() if err != nil {     log.Fatal(err) } err = cmd.Start() if err != nil {     t.Logf("Error starting the go file: %s", err) } <-timer.C  buf := new(bytes.Buffer) buf.ReadFrom(stdout) s := buf.String() t.Logf("out: %s", s) 

}

My main.go simply is:

package main  import (     "fmt" )  func main() {     fmt.Println("hello world") } 

When I run the test it only prints: out: and not the expected hello world. I have attempted to read using cmd.Stdout as well cmd.Output() with the same result. Do I need to use exec.Wait()? I cannot figure out why the standard output is not being picked up in my test. Perhaps in tests you cannot read from standard out?

Компиляция Golang DLL для 32 битных систем

В этом деле новичок. Сумел скомпилить 64 битную длл, 32 никак не выйдет, пересмотрел кучу туториалов, все не работает или я скорее всего что то не понимаю. Работаю на Win10, в VS Code.

x64 компилирую

go build -o release\returnHWID_x64.dll -buildmode=c-shared . 

Пробую выставить на x32 вот этим способом

set CC=i686-w64-mingw32-gcc CXX=i686-w64-mingw32-g++ GOOS=windows GOARCH=386 CGO_ENABLED=1 

При компиляции выбивает

# runtime/cgo exec: "i686-w64-mingw32-gcc": executable file not found in %PATH% 

Is the any workable testnet3 Bitcoin solution for creating, signing, broadcast a normal transaction using Golang?

Currently I’m trying to create, sign & broadcast bitcoin transaction using btcsuite. For start, I’ve already had testnet3 address & its associated privatekey for testing. However, hunting through the post and articles like below:-

  1. here
  2. here
  3. here

The solution proposed above its not complete, for first one, it only covers until signing (i knew the author claimed its not broadcastable unless you provide the utxo which i did if i’m right) but when tried to braodcast it failed with message

“Error validating transaction: Transaction be9b294695bfb201a5cff32af074a4bf72b073e3c9dad1969111165bf118a622 orphaned, missing reference f0c0d3b3eecf911ede996a74ceadc9366068791450c9e6bacee9ae202f3690d1.”

I have no idea what’s going on and I suspect its script is incompatible.

So, the bottom line is I just want a workable example in bitcoin testnet3 that shows “from 1 address transfer some bitcoin to other address” by showing the process of creating raw transaction, sign it with private key, turn it to raw transaction in hex format & broadcast it using something like https://live.blockcypher.com/btc/pushtx/ (BTC testnet)

currently my code is as follow:-

package main import (     "fmt"     "encoding/hex"     "bytes"     "github.com/btcsuite/btcutil"     btcchain "github.com/btcsuite/btcd/chaincfg"     "github.com/btcsuite/btcd/chaincfg/chainhash"     "github.com/btcsuite/btcd/txscript"     "github.com/btcsuite/btcd/wire" ) func txToHex(tx *wire.MsgTx) string {     buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize()))     tx.Serialize(buf)     return hex.EncodeToString(buf.Bytes()) }  func stkbtc(){   pvkey := "cNjXNxcfawzyfGUxaG94rKqayAL2n7QWioKhCkHbQsBRT7SbDyGu"   txHash := "e028b5bf030a24986a03b03b89dec037e8462ae32bc93679cb49d7c779685987"   destination := "n2kRiAkW1xr5DVy7QKVGaYiZbwpS7j23jJ"   var amount int64 = 100000000   txFee := int64(500000)    //try send btc   decodedwif,err := btcutil.DecodeWIF(pvkey)   if err != nil {     fmt.Printf("decodedwif error: %v\n",err)   }   fmt.Printf("decodedwif       : %v\n",decodedwif)    addresspubkey, _ := btcutil.NewAddressPubKey(decodedwif.PrivKey.PubKey().SerializeUncompressed(), &btcchain.TestNet3Params)   sourceTx := wire.NewMsgTx(wire.TxVersion)   sourceUtxoHash, _ := chainhash.NewHashFromStr(txHash)    sourceUtxo := wire.NewOutPoint(sourceUtxoHash, 0)    sourceTxIn := wire.NewTxIn(sourceUtxo, nil, nil)   destinationAddress, _ := btcutil.DecodeAddress(destination, &btcchain.TestNet3Params)    sourceAddress, err := btcutil.DecodeAddress(addresspubkey.EncodeAddress(), &btcchain.TestNet3Params)   if err != nil {     fmt.Printf("sourceAddress err: %v\n",err)   }    destinationPkScript, _ := txscript.PayToAddrScript(destinationAddress)    sourcePkScript, _ := txscript.PayToAddrScript(sourceAddress)   sourceTxOut := wire.NewTxOut(amount, sourcePkScript)    sourceTx.AddTxIn(sourceTxIn)   sourceTx.AddTxOut(sourceTxOut)   sourceTxHash := sourceTx.TxHash()    redeemTx := wire.NewMsgTx(wire.TxVersion)   prevOut := wire.NewOutPoint(&sourceTxHash, 0)   redeemTxIn := wire.NewTxIn(prevOut, nil, nil)   redeemTx.AddTxIn(redeemTxIn)   redeemTxOut := wire.NewTxOut((amount - txFee), destinationPkScript)   redeemTx.AddTxOut(redeemTxOut)    sigScript, err := txscript.SignatureScript(redeemTx, 0, sourceTx.TxOut[0].PkScript, txscript.SigHashAll, decodedwif.PrivKey, false)   if err != nil {     fmt.Printf("sigScript err: %v\n",err)   }   redeemTx.TxIn[0].SignatureScript = sigScript   fmt.Printf("sigScript: %v\n",hex.EncodeToString(sigScript))     //Validate signature   flags := txscript.StandardVerifyFlags   vm, err := txscript.NewEngine(sourceTx.TxOut[0].PkScript, redeemTx, 0, flags, nil, nil, amount)   if err != nil {     fmt.Printf("err != nil: %v\n",err)   }   if err := vm.Execute(); err != nil {     fmt.Printf("vm.Execute > err != nil: %v\n",err)   }    fmt.Printf("redeemTx: %v\n",txToHex(redeemTx)) }  func main(){     stkbtc() } 

the txhash was from previous transaction where i got the testnet bitcoin from faucet & nothing else..

  • Sender address: mpYGA8wRCArpGTs6aJMmZRWyUuPoZmeLJv
  • Sender public key: 02217deb8b3782236fa8214da94bd5a9338f2eeb3299c39c057fb68ada63d93df7
  • Sender private key: cNjXNxcfawzyfGUxaG94rKqayAL2n7QWioKhCkHbQsBRT7SbDyGu

  • Target address: n2kRiAkW1xr5DVy7QKVGaYiZbwpS7j23jJ

Please advice what is wrong with the code above, really appreciate it if someone can point it out.

OpenSSL SSL_connect: SSL_ERROR_SYSCALL – build/run golang app

Operating System: Ubuntu 18.04.2 LTS

Kernel: Linux 4.15.0-47-generic

Architecture: x86-64

First, I run go run main.go others package was running very well. But some problems come through… here is the result after I run the main.go app.

go: finding github.com/kr/pty v1.1.1 go: finding golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01 go: gopkg.in/check.v1@v1.0.0-20180628173108-788fd7840127: unrecognized import path "gopkg.in/check.v1" (https fetch: Get https://gopkg.in/check.v1?go-get=1: net/http: TLS handshake timeout) go: gopkg.in/sourcemap.v1@v1.0.5: unrecognized import path "gopkg.in/sourcemap.v1" (https fetch: Get https://gopkg.in/sourcemap.v1?go-get=1: net/http: TLS handshake timeout) go: gopkg.in/xmlpath.v2@v2.0.0-20150820204837-860cbeca3ebc: unrecognized import path "gopkg.in/xmlpath.v2" (https fetch: Get https://gopkg.in/xmlpath.v2?go-get=1: net/http: TLS handshake timeout) go: error loading module requirements 

I got an issue with SSL/Open SSL. I tried to get a package source from gopkg.in but this happen to me :

* Rebuilt URL to: https://gopkg.in/ *   Trying 35.196.143.184... * TCP_NODELAY set * Connected to gopkg.in (35.196.143.184) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: *   CAfile: /etc/ssl/certs/ca-certificates.crt   CApath: /etc/ssl/certs * (304) (OUT), TLS handshake, Client hello (1): * OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to gopkg.in:443 * stopped the pause stream! * Closing connection 0 curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to gopkg.in:443 

I was reading from https://stackoverflow.com/questions/31183297/ssl-connect-fails-with-ssl-error-syscall-error/31183611#31183611 but it’s kinda complicated. I can’t get it, just trying to fix it since I need a source from that site on my apps.

Имеются ли библиотеки коллекторов на Golang аналогично инструменту flow-tools?

В данный момент собираю статистику с NetFlow данным коллектором и он удобен тем, что я могу вывести отчет,использовать фильтры и прочие его плюшки, но с недавних времён в связи с загруженностью стало это все необходимо автоматизировать, соответственно возникли вопросы: 1.Имеются ли библиотеки коллекторов на подобие flow-tools в Go с аналогичным функционалом? 2.Если нет, то правильно ли будет из Go вызывать команды flow-tools ?

Golang – best practices for a Java developer

My relevant work experience is with Java (mostly web development with Dropwizard/Spring) so I can not avoid using the same practices as I do in a Java project. The project is there but I am going to copy it here:

Project

A very simple project with Gin framework which an endpoint to return a list of users based on their score.

Structure

liveops-tool -- user ---- model ------ user.go ---- service ------ userService.go ------ userDirectory.go (mock the db) -- main.go 

main.go

r.GET("/competition/users", func(c *gin.Context) {         numUsers, err := strconv.Atoi(c.DefaultQuery("numusers", "6"))         minScore, err := strconv.Atoi(c.DefaultQuery("minscore", "0"))         maxScore, err := strconv.Atoi(c.DefaultQuery("maxscore", "2000"))         fmt.Printf("numUsers: %d , minScore: %d , maxScore: %d \n", numUsers, minScore, maxScore)          if err == nil {             var res = userService.GenerateUserListByScore(numUsers, minScore, maxScore)             c.JSON(http.StatusOK, gin.H{"users": res})         } else {             c.JSON(http.StatusBadRequest, gin.H{"users": "no valid"})         }      }) 

user.go

package user  type User struct {     ID         string `json:"id"`     Name       string `json:"name"`     Country    string `json:"country"`     TotalScore int    `json:"totalScore"` } 

userService.go

package user  import (     user "liveops-tool/user/model" )  // GenerateUserListByScore returns a list of users for a tournament func GenerateUserListByScore(numUsers, minScore, maxScore int) []user.User {     return searchUsers(numUsers, minScore, maxScore) } 

userDirectory.go

package user  import (     "fmt"     userModel "liveops-tool/user/model" )  var users = []userModel.User{}  func init() {     initUsers() }  func searchUsers(numUsers, minScore, maxScore int) []userModel.User {     return filterUsersByScore(numUsers, minScore, maxScore) }  func filterUsersByScore(numUsers, minScore, maxScore int) []userModel.User {     var filteredUsers = []userModel.User{}     var countUsers = 0     if len(users) < numUsers {         numUsers = len(users)     }     for i := range users {         if users[i].TotalScore >= minScore && users[i].TotalScore <= maxScore {             filteredUsers = append(filteredUsers, users[i])             countUsers++         }          if countUsers >= numUsers {             break         }     }     return filteredUsers }  func initUsers() {     user1 := userModel.User{ID: "1", Name: "John", Country: "UK", TotalScore: 500}     user2 := userModel.User{ID: "2", Name: "Frank", Country: "ES", TotalScore: 1500}     user3 := userModel.User{ID: "3", Name: "Bob", Country: "UK", TotalScore: 2000}     user4 := userModel.User{ID: "4", Name: "Anna", Country: "FR", TotalScore: 3000}     users = append(users, user1)     users = append(users, user2)     users = append(users, user3)     users = append(users, user4)     fmt.Printf("users: %+v\n", users) } 

Questions

  • I am mocking the user list and I would like the method initUsers would not be accesible from userService. Golang doesn’t have public and private methods because the visibility depends on the package. The same for the function filterUsersByScore. How can I improve it?

  • User (model): I need to put the attributes with the first letter in uppercase to make it exportable when I return the JSON. Is it possible to have the attributes as private to access them through getters and setters and also return them in the JSON response?

Any other advice about the code is well received.

Golang extension on visual studio

When I am making the golang environment in visual studio, visual studio recommand a golang extension – “goreturns”

I just pressed install, but the output tells that I had failed to install

However, I tried the same code in terminal, it is success

But, after I had installed by terminal, when I back to my code, it still cannot detect the extension, even I had restarted the visual studio code.

Do any one knows that what is happening? Many thanks

Extracting attribute value from multiple XML nodes in golang?

I’m attempting to parse an SVG file to get all of the colors that are present in the file. SVGs are XML based and their structure can vary a bit. For example:

<svg viewBox="-80 -80 160 160">   <g stroke="black" fill="none">     <path d='...' fill='#0FF'/>     <path d='...' fill='#F0F'/>     ...   </g> </svg> 

and

<svg viewBox="0 0 100 100">   <a>     <path d="..." stroke="black" fill="red"/>     <ellipse stroke="black" fill="white" cx="50" cy="40" rx="22" ry="35"/>     <circle cx="50" cy="40" r="5" stroke="black" fill="red"/>   </a> </svg> 

and

<svg viewBox="0 0 80 120">   <rect id="background-rect" x="0%" y="0%" width="100%" height="100%" fill="#aaaaaa"/> </svg> 

Are all examples of valid SVGs. At first I attempted to create the underlying structs that would allow me to represent all of these structures but then I decided to take a more generic approach that would focus soley on the fill attribute which is all I care about:

type GenericNode struct {     XMLName xml.Name     Fill    string        `xml:"fill,attr"`     Nodes   []GenericNode `xml:",any"` }  func (s *SVGController) GetColorsFromXML() []string {     xmlFile, _ := os.Open(s.Path)     byteValue, _ := ioutil.ReadAll(xmlFile)     var svg GenericNode     xml.Unmarshal(byteValue, &svg)      // Using a map here to avoid having to worry about having     // duplicate colors in the color slice     colorMap := make(map[string]struct{})     colorMap = getSVGColors(svg, colorMap)      // Once we have a complete color map extract all the keys     // to an array and return it.     colors := make([]string, len(colorMap))     i := 0     for k := range colorMap {         colors[i] = k         i++     }     return colors }  func getSVGColors(svg GenericNode, colors map[string]struct{}) map[string]struct{} {     if svg.Fill != "" && strings.ToLower(svg.Fill) != "none" {         colors[svg.Fill] = struct{}{}     }     for _, node := range svg.Nodes {         colors = getSVGColors(node, colors)     }     return colors } 

Is this a reasonable approach to take? Am I doing anything here that should be avoided?