-1

I am trying to write a small code in Go that will collect and save stats from IPFS. So my Go code will execute IPFS command and save its output in .txt file and keep updating that .txt file. I am having trouble doing that.

This is my code:

package main

import (
    "fmt"
    "io"
    "log"
    "os"
    "os/exec"
    "time"
)

func ipfsCommand() (ipfsOutput string) {
    // output and error
    out, err := exec.Command("ipfs","stats","bitswap","--human").Output()
    // if there are errors, print/log them
    if err != nil {
        log.Printf("error!")
        log.Fatal(err)
    } else {
        log.Printf("no error, printing output")
        fmt.Printf("%s", out)
    }
    return
}

func writeToFile(message string) error {
    f, err := os.Create("outputTest2_2.txt")
    if err != nil {
        return err
    }
    defer f.Close()
    l, err := io.WriteString(f, message)
    if err != nil {
        fmt.Println(err)
        f.Close()
        return err
    }
    fmt.Println(l, "bytes written successfully")

    return f.Sync()
}

func main() {
    // get current time
    currentTime := time.Now()
    fmt.Println("YYYY.MM.DD : ", currentTime.Format("2006.01.02 15:04:05"))
    writeToFile(currentTime)
    // get output from ipfs command
    msg := ipfsCommand()
    // write the output to file
    writeToFile(msg)
    fmt.Println("file written!!!")
    
/*  // write to file many times
    for i:=0;i<3;i++{
        // get output from ipfs command
        msg := ipfsCommand()
        // write the output to file
        writeToFile(msg)
    }*/
}

When the above code is run, this is the error:

# command-line-arguments
.\test2.go:49:13: cannot use currentTime (type time.Time) as type string in argument to writeToFile

Again, I want to get output from IPFS and save it to .txt file along with current time. I want to do this in loop because I want to save output from IPFS over a long period of time.

dlsniper
  • 7,188
  • 1
  • 35
  • 44
  • The error message you've included is pretty clear. What help do you need? – Jonathan Hall Jul 17 '21 at 06:08
  • yoou should read https://stackoverflow.com/a/43329318/4466350 –  Jul 17 '21 at 11:28
  • Does this answer your question? [How to execute 'top' Command output using Golang](https://stackoverflow.com/questions/40655133/how-to-execute-top-command-output-using-golang) –  Jul 17 '21 at 11:29

1 Answers1

2

I tried to fix your script as is, but it just has too many issues. Here is a rewrite, maybe you can use it as a new starting point:

package main

import (
   "os"
   "os/exec"
   "time"
)

func main() {
   f, err := os.Create("outputTest2_2.txt")
   if err != nil {
      panic(err)
   }
   defer f.Close()
   currentTime, err := time.Now().MarshalText()
   if err != nil {
      panic(err)
   }
   f.Write(append(currentTime, '\n'))
   msg, err := exec.Command("go", "env").Output()
   if err != nil {
      panic(err)
   }
   f.Write(msg)
}
Zombo
  • 1
  • 62
  • 391
  • 407