728x90
반응형

echo 프레임워크로 파일 업로더 서버를 구축했다.

 

쿡북에서 단일 파일, 여러 파일을 업로드하는 예제가 있어 이를 바탕으로 쉽게 만들 수 있었다.

 

하지만 업로드를 하는 클라이언트에서 폼의 키값을 다른 것으로 하는 경우를 고려해야 했다.

 

그래서 여러 파일을 업로드하는 코드를 참고하여 입맛에 맞게 수정했다.

func upload(c echo.Context) error {
    form, err := c.MultipartForm()
    if err != nil {
        return err
    }

    for _, file := range form.File {
        // Source
        src, err := file[0].Open()
        if err != nil {
            return err
        }
        defer src.Close()

        // Destination
        dst, err := os.Create(file[0].Filename)
        if err != nil {
            return err
        }
        defer dst.Close()

        // Copy
        if _, err = io.Copy(dst, src); err != nil {
            return err
        }
    }
}

그리고 용량이 큰 파일을 업로드하는 경우에 디스크 사용량이 파일 사이즈의 2배가 늘어났다.

 

원인을 찾아보니 go에서 설정한 메모리(32 MB + 10MB)보다 큰 경우 /tmp/에 파일을 저장하고 있었다.

 

다음과 같이 하면 파일을 원하는 곳에 복사한 다음 임시 파일을 모두 제거할 수 있다.

func upload(c echo.Context) error {
    defer func() {
        form, err := ctx.MultipartForm()
	    if err != nil {
    	    return
        }
    	form.RemoveAll()
    }()
    ...
}

 

참고 문헌

  1. https://echo.labstack.com/cookbook/file-upload
  2. https://github.com/labstack/echo/blob/master/context.go#L369
  3. https://github.com/golang/go/blob/master/src/mime/multipart/formdata.go#L86
반응형
728x90
반응형

Echo로 개발하여 API로 통신하는데 Content-Type: text/plain으로 통신을 해야했다.

func(c echo.Context) (err error) {
  body := &Body{}
  if err = c.Bind(body); err != nil {
    return
  }
  return c.JSON(http.StatusOK, body)
}

위와 같이 echo.Context.Bind를 이용하여 JSON 형식을 파싱하여 사용하고 있었는데

 

Content-Type: text/plain인 경우 415 Unsupported Media Type 에러가 발생했다.

 

말 그대로 지원하지 않는 미디어 형식이라 에러가 난 것이다.

 

이를 해결하기 위해서 다음과 같이 변경하면 Content-Type에 무관하게 동작하도록 할 수 있다.

func(c echo.Context) (err error) {
  rBody := &RegisterBody{}
  if b, err := ioutil.ReadAll(c.Request().Body); err == nil {
    if err := json.Unmarshal(b, &body); err != nil {
        return
    }
  }
  return c.JSON(http.StatusOK, body)
}

 

참고 문헌

  1. https://github.com/labstack/echo/issues/156#issuecomment-124684206

반응형

'Golang' 카테고리의 다른 글

[Golang] Go의 선(The Zen of Go)  (0) 2020.06.04
[Golang] Kafka 연동 문제  (0) 2020.04.30
[Golang] Go를 사용하면서 발생했던 문제들  (0) 2020.04.23
[Golang] Java gzip migration  (0) 2020.01.30
[Golang] 410 Gone  (0) 2020.01.25

+ Recent posts