0
package main
import (
    "encoding/json"
    "fmt"
    "/something/models"
    "os"
    "path/filepath"
    "runtime"
)

func WriteDeviceToFile(d chan *models.Device, fileName string) {

_, b, _, _ := runtime.Caller(0)
basepath := filepath.Dir(b)
filePath := basepath + "/dataFile/" + fileName

var f *os.File
var err error


f, _ = os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0600)

defer f.Close()


for device := range d {
    deviceB, err := json.Marshal(device)
    fmt.Println(string(deviceB))
    if err == nil {
        if _, err = f.WriteString(string(deviceB)); err != nil {
            panic(err)
        }
    } else {
        panic(err)
    }
}

}

func main() {
deviceChan := make(chan *models.Device)
go WriteDeviceToFile(deviceChan, "notalive.txt")
d := models.NewDevice("12346", "")
deviceChan <- d
d = models.NewDevice("abcd", "")
deviceChan <- d
close(deviceChan)
}

This only works with at least two devices sent to channel. With only one device in deviceChan, the function does not receive anything. Is the channel gone before the WriteDeviceToFile gets to it?

typing...
  • 767
  • 2
  • 9
  • 24
  • 2
    The program exits when `main` returns. Nothing prevents `main` from exiting before the files are written. – Bayta Darell Oct 06 '16 at 00:17
  • that seems to be the reason. Thanks. I kinda feel stupid now. Do you want to put that as an answer so I can accept it? – typing... Oct 06 '16 at 00:20

1 Answers1

1

The program exits when main returns. Nothing prevents main from exiting before the files are written

Bayta Darell
  • 101,448
  • 10
  • 207
  • 215