As stated in the title, i am not getting any errors, but it is also not printing after i submit the CSV.
fmt.Fprint(w, “Here is options”, options)
HTLML template i am using:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Car Project</title>
</head>
<body>
<h1>Please upload your inventory CSV</h1>
<form action="/uploadCSV" method="post">
<input type="file" id="myFile" name="filename">
<input type="submit">
</form>
</body>
</html>
Go code:
package main
import (
"encoding/csv"
"fmt"
"log"
"net/http"
"text/template"
)
var tpl *template.Template
var options []carInvSchema
type carInvSchema struct {
Id string
Make string
Model string
Description string
Mileage string
Price string
Term string
}
func init() {
tpl = template.Must(template.ParseGlob("templates/*"))
}
func main() {
http.HandleFunc("/", index)
// http.HandleFunc("/uploadCSV", parsedCSV)
http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodPost {
//processing form submisson
//opening file
file, _, err := req.FormFile("filename")
if err != nil {
http.Error(w, "Unable to upload file", http.StatusInternalServerError)
}
defer file.Close()
//reading file
rdr := csv.NewReader(file)
rows, err := rdr.ReadAll()
if err != nil {
log.Fatalln(err)
}
options = make([]carInvSchema, 0, len(rows))
//ranging over the rows
for i, row := range rows {
if i == 0 {
continue
}
id := row[0]
make := row[1]
model := row[2]
description := row[3]
mileage := row[4]
price := row[5]
term := row[6]
options = append(options, carInvSchema{
Id: id,
Make: make,
Model: model,
Description: description,
Mileage: mileage,
Price: price,
Term: term,
})
}
}
err := tpl.ExecuteTemplate(w, "index.gohtml", nil)
if err != nil {
log.Fatal("Unable to execute template")
}
}
// func parsedCSV(w http.ResponseWriter, req *http.Request) {
// w.Header().Set("Content-Type", "text/html; charset=utf-8")
// err := tpl.ExecuteTemplate(w, "parseddata.gohtml", options)
// if err != nil {
// log.Fatal("Unable to execute template")
// }
// }