Created
July 5, 2012 19:23
-
-
Save ninnemana/3055867 to your computer and use it in GitHub Desktop.
Testing out the encoding/csv package in golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/csv" | |
"net/http" | |
"html/template" | |
"fmt" | |
"strconv" | |
) | |
type Price struct{ | |
partID string | |
custPartID string | |
listPrice string | |
overridePrice string | |
salePrice string | |
} | |
func home(w http.ResponseWriter, r *http.Request){ | |
displayTemplate("home", "index.html", w, nil) | |
} | |
func upload(w http.ResponseWriter, r *http.Request){ | |
file, _, err := r.FormFile("file") | |
if err != nil{ | |
fmt.Println("line 18: ", err) | |
} else { | |
reader := csv.NewReader(file) | |
lines, err := reader.ReadAll() | |
if err != nil{ | |
fmt.Println("Error reading all lines: %v", err) | |
} | |
prices := make([]Price, len(lines)) | |
for i, line := range lines { | |
_, err := strconv.ParseInt(line[0], 2, 64) | |
if err == nil{ // Make sure we're not hitting the header row | |
price := Price{ | |
partID: line[0], | |
custPartID: line[1], | |
listPrice: line[2], | |
overridePrice: line[3], | |
salePrice: line[4], | |
} | |
prices[i-1] = price | |
}else{ | |
fmt.Println(err) | |
} | |
} | |
fmt.Println(prices) | |
} | |
} | |
func main(){ | |
http.HandleFunc("/", home) | |
http.HandleFunc("/upload", upload) | |
http.ListenAndServe(":8080", nil) | |
} | |
func displayTemplate(name string, filename string, w http.ResponseWriter, x interface{}){ | |
t, err := template.New(name).ParseFiles(filename) | |
err = t.ExecuteTemplate(w, filename, x) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head></head> | |
<body> | |
<form method="post" enctype="multipart/form-data" action="/upload"> | |
<input type="file" name="file" /> | |
<input type="submit" value="Upload" /> | |
</form> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment