Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dev001hajipro
Forked from yomusu/csvblob.go
Last active June 28, 2018 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev001hajipro/e33b5847068b57cfbe2972527ce5748e to your computer and use it in GitHub Desktop.
Save dev001hajipro/e33b5847068b57cfbe2972527ce5748e to your computer and use it in GitHub Desktop.
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