Ejemplo n.º 1
0
func writeValuesTofile(datatowrite *ProtobufTest.TestMessage) {

	//Retreive client information from the protobuf message
	ClientName := datatowrite.GetClientName()
	ClientDescription := datatowrite.GetDescription()
	ClientID := strconv.Itoa(int(datatowrite.GetClientId()))

	// retrieve the message items list
	items := datatowrite.GetMessageitems()
	fmt.Println("Writing value to CSV file")
	//Open file for writes, if the file does not exist then create it
	file, err := os.OpenFile("CSVValues.csv", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
	checkError(err)
	//make sure the file gets closed once the function exists
	defer file.Close()
	//Go through the list of message items, insert them into a string array then write them to the CSV file.
	writer := csv.NewWriter(file)
	for _, item := range items {
		record := []string{ClientID, ClientName, ClientDescription, strconv.Itoa(int(item.GetId())), item.GetItemName(), strconv.Itoa(int(item.GetItemValue())), strconv.Itoa(int(item.GetItemType()))}
		writer.Write(record)
		fmt.Println(record)
	}
	//flush data to the CSV file
	writer.Flush()
	fmt.Println("Finished Writing value to CSV file")
}
Ejemplo n.º 2
0
func retrieveDataFromFile(fname *string) ([]byte, error) {
	file, err := os.Open(*fname)
	checkError(err)
	defer file.Close()

	csvreader := csv.NewReader(file)
	var hdrs Headers
	hdrs, err = csvreader.Read()
	checkError(err)
	ITEMIDINDEX := hdrs.getHeaderIndex("itemid")
	ITEMNAMEINDEX := hdrs.getHeaderIndex("itemname")
	ITEMVALUEINDEX := hdrs.getHeaderIndex("itemvalue")
	ITEMTYPEINDEX := hdrs.getHeaderIndex("itemType")

	ProtoMessage := new(ProtobufTest.TestMessage)
	ProtoMessage.ClientName = proto.String(CLIENT_NAME)
	ProtoMessage.ClientId = proto.Int32(CLIENT_ID)
	ProtoMessage.Description = proto.String(CLIENT_DESCRIPTION)

	//loop through the records
	for {
		record, err := csvreader.Read()
		if err != io.EOF {
			checkError(err)
		} else {

			break
		}
		//Populate items
		testMessageItem := new(ProtobufTest.TestMessage_MsgItem)
		itemid, err := strconv.Atoi(record[ITEMIDINDEX])
		checkError(err)
		testMessageItem.Id = proto.Int32(int32(itemid))
		testMessageItem.ItemName = &record[ITEMNAMEINDEX]
		itemvalue, err := strconv.Atoi(record[ITEMVALUEINDEX])
		checkError(err)
		testMessageItem.ItemValue = proto.Int32(int32(itemvalue))
		itemtype, err := strconv.Atoi(record[ITEMTYPEINDEX])
		checkError(err)
		iType := ProtobufTest.TestMessage_ItemType(itemtype)
		testMessageItem.ItemType = &iType

		ProtoMessage.Messageitems = append(ProtoMessage.Messageitems, testMessageItem)

		fmt.Println(record)
	}

	//fmt.Println(ProtoMessage.Messageitems)
	return proto.Marshal(ProtoMessage)
}