34
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goでmultipart/form-dataをparseする

Last updated at Posted at 2014-01-26

FormFile を使えばおk。

func handler(w http.ResponseWriter, r *http.Request) {
	file, reader, err := r.FormFile("パラメータ名")
	...
}

file にmultipart.File型でopenされたものが入ります。こいつから読み込んでやればOK
詳細は以下当たりを参照

例として、wavファイル受け取ってparseするコード書いた。wavの読み込みに使うライブラリは予めインストールしておく。

$ go get github.com/mjibson/go-dsp/wav
audioHandler.go
package main

import (
	"encoding/json"
	"net/http"
	"github.com/mjibson/go-dsp/wav"
)

type AudioInfo struct {
	Filename string
	SampleRate int
	NumChannels int
	Duration float64
}

func audiohandler(w http.ResponseWriter, r *http.Request) {
	file, reader, err := r.FormFile("audio")
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	defer file.Close()
	
	wav, werr := wav.ReadWav(file)
	if werr != nil {
		http.Error(w, werr.Error(), http.StatusInternalServerError)
		return
	}

	audio := AudioInfo{
		reader.Filename, 
		int(wav.SampleRate), 
		int(wav.NumChannels),
		float64(len(wav.Data[0]))/float64(wav.SampleRate)}

	js, jerr := json.Marshal(audio)
	if jerr != nil {
		http.Error(w, jerr.Error(), http.StatusInternalServerError)
		return		
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(js)
}

func main() {
	http.HandleFunc("/file", audiohandler)
	http.ListenAndServe(":9999", nil)
}

試す

Server

$ go run audioHandler.go

Client

$ curl -i -X POST -F 'audio=@/path/to/file.wav' localhost:9999/file

結果

HTTP/1.1 100 Continue

HTTP/1.1 200 OK
Content-Type: application/json
Date: Sun, 26 Jan 2014 15:21:20 GMT
Content-Length: 79

{"Filename":"ファイル名.wav","SampleRate":44100,"NumChannels":2,"Duration":29.0765} 

簡単ですね。C++捨ててGoerになる

34
27
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
34
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?