Instantly share code, notes, and snippets.

@dev001hajipro /main.go forked from yomusu/csvblob.go
Last active Jun 28, 2018

Embed
What would you like to do?
Go appengine : csv upload(blob) & parse. 2018/06/28 change import to "context" and "google.golang.org/appengine/*"
package main
import (
"context"
"html/template"
"io"
"net/http"
"encoding/csv"
"strings"
"google.golang.org/appengine"
"google.golang.org/appengine/blobstore"
"google.golang.org/appengine/log"
)
func serveError(ctx context.Context, w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "text/plain")
io.WriteString(w, "Internal Server Error")
log.Errorf(ctx, "%v", err)
}
var rootTemplate = template.Must(template.New("root").Parse(rootTemplateHTML))
const rootTemplateHTML = `
<html><body>
<form action="{{.}}" method="POST" enctype="multipart/form-data">
Upload CSV File: <input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form></body></html>
`
func handleRoot(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
uploadURL, err := blobstore.UploadURL(ctx, "/upload", nil)
if err != nil {
serveError(ctx, w, err)
return
}
w.Header().Set("Content-Type", "text/html")
err = rootTemplate.Execute(w, uploadURL)
if err != nil {
log.Errorf(ctx, "%v", err)
}
}
func handleServe(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
bkey := appengine.BlobKey(r.FormValue("blobKey"))
w.Header().Set("Content-Type", "text/plain")
// Blobを取得
out := blobstore.NewReader(c, bkey)
// csv解析
data := csv.NewReader(out)
// csv全出力
cols, err := data.Read()
// 最初の読み込みでエラーが出るなら、Blobは存在しないってよ
if err != nil {
http.Error(w, "blob file doesn't exist", http.StatusNotFound)
return
}
for err == nil {
w.Write([]byte(strings.Join(cols, ",")))
cols, err = data.Read()
}
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
blobs, _, err := blobstore.ParseUpload(r)
if err != nil {
serveError(ctx, w, err)
return
}
file := blobs["file"]
if len(file) == 0 {
log.Errorf(ctx, "no file uploaded")
http.Redirect(w, r, "/", http.StatusFound)
return
}
http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound)
}
func main() {
http.HandleFunc("/", handleRoot)
http.HandleFunc("/serve/", handleServe)
http.HandleFunc("/upload", handleUpload)
appengine.Main()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment