Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.
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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away