I have read one excel csv file using Golang and wanted to print them to web browser as JSON Data for every GET request you make,But every time I print the JSON Data in Web browser some data gets skipped. I have double checked those data are in csv file but not getting printed in web browser. Any help you can suggest me ? Thanks in advance
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"os"
)
var csvData [][]string
var Record IRIS
var i int = 0
func init() {
csvFile, err := os.Open("IRIS.csv")
if err != nil {
fmt.Println(err)
}
reader := csv.NewReader(csvFile)
reader.FieldsPerRecord = -1
csvData, _ = reader.ReadAll()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer csvFile.Close()
}
type IRIS struct {
ID string
SepalLength string
SepalWidth string
PetalLength string
PetalWidth string
Species string
}
func main() {
router := httprouter.New()
router.GET("/stream/content/data", StreamDataHandler)
fmt.Println(http.ListenAndServe("127.0.0.1:9090", router))
}
func StreamDataHandler(res http.ResponseWriter, req *http.Request, p httprouter.Params) {
res.Header().Set("Access-Control-Allow-Origin", "*")
// read data from CSV file
Record.ID = csvData[i][0]
Record.SepalLength = csvData[i][1]
Record.SepalWidth = csvData[i][2]
Record.PetalLength = csvData[i][3]
Record.PetalWidth = csvData[i][4]
Record.Species = csvData[i][5]
jsondata, err := json.Marshal(Record) // convert to JSON
if err != nil {
fmt.Println(err)
os.Exit(1)
}
i = i + 1
fmt.Fprintf(res, string(jsondata))
return
}
OUTPUT:
{"ID":"2","SepalLength":"4.9","SepalWidth":"3","PetalLength":"1.4","PetalWidth":"0.2","Species":"setosa"}
{"ID":"6","SepalLength":"5.4","SepalWidth":"3.9","PetalLength":"1.7","PetalWidth":"0.4","Species":"setosa"}
{"ID":"7","SepalLength":"5.7","SepalWidth":"4.4","PetalLength":"1.5","PetalWidth":"0.4","Species":"setosa"}
. . .
Why this is happening ?
I actually wanted to print all the values (without skipping any) like streaming of data every 2 second from Excel CSV file
Aucun commentaire:
Enregistrer un commentaire