4

goでHTTP経由でバイナリデータを受信するための最良の方法は何ですか?私の場合、zipファイルをアプリケーションのRESTAPIに送信したいと思います。gowebに固有の例は素晴らしいでしょうが、net/httpも問題ありません。

4

1 に答える 1

18

リクエストボディから読むだけ

何かのようなもの

package main

import ("fmt";"net/http";"io/ioutil";"log")

func h(w http.ResponseWriter, req *http.Request) {
    buf, err := ioutil.ReadAll(req.Body)
    if err!=nil {log.Fatal("request",err)}
    fmt.Println(buf) // do whatever you want with the binary file buf
}

より合理的なアプローチは、ファイルを何らかのストリームにコピーすることです

defer req.Body.Close()
f, err := ioutil.TempFile("", "my_app_prefix")
if err!=nil {log.Fatal("cannot open temp file", err)}
defer f.Close()
io.Copy(f, req.Body)
于 2012-07-30T06:59:03.323 に答える