LoginSignup
4
4

More than 5 years have passed since last update.

GoでcsvアップロードするAPIを作ってcURLで動作確認する

Last updated at Posted at 2019-03-03
sample.go
package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "net/http"
    "strings"

    "github.com/gorilla/mux"
)

type Entry struct {
    Initial string
    Fruit   string
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/upload", uploadFile).Methods("POST")
    http.ListenAndServe(":8000", r)
}

func uploadFile(w http.ResponseWriter, r *http.Request) {
    // multipart/form-dataを読み込むためにFormFileを利用
    // 引数 "file" は任意の名前
    // 返り値の型は multipart.File, *multipart.FileHeader, error
    file, _, err := r.FormFile("file")

    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
    }
    defer file.Close()

    reader := csv.NewReader(file)
    for {
        line, err := reader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
        }
        output := strings.Join(line[:], " for ") + "\n"
        fmt.Fprintf(w, output)
    }
}

サーバを立ち上げる

$ go run sample.go

別ターミナルで動作確認

$ touch sample.csv
$ echo 'A,Apple' > sample.csv
$ echo 'B,Banana' >> sample.csv

# cURL の option F でファイルアップロードができる
$ curl -X POST -F "file=@sample.csv" localhost:8000/upload
A for Apple
B for Banana
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4