[go] net/http 패키지를 사용한 파일 업로드 및 다운로드 처리
이번 글에서는 Go 언어의 net/http
패키지를 사용하여 파일을 업로드하고 다운로드하는 방법에 대해 알아보겠습니다.
파일 업로드 처리
1. HTML 폼 작성
<!DOCTYPE html>
<html>
<head>
<title>파일 업로드</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="업로드">
</form>
</body>
</html>
2. 서버 측 핸들러 구현
package main
import (
"fmt"
"net/http"
)
func uploadFile(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(10 << 20) // 최대 10MB 크기의 파일 처리
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println("파일 업로드 오류:", err)
return
}
defer file.Close()
fmt.Fprintf(w, "파일 이름: %v", handler.Filename)
}
3. 서버 시작
func main() {
http.HandleFunc("/upload", uploadFile)
http.ListenAndServe(":8080", nil)
}
파일 다운로드 처리
서버 측 핸들러 구현
func downloadFile(w http.ResponseWriter, r *http.Request) {
filePath := "./files/example.txt"
w.Header().Set("Content-Disposition", "attachment; filename=example.txt")
w.Header().Set("Content-Type", "application/octet-stream")
http.ServeFile(w, r, filePath)
}
서버 시작
func main() {
http.HandleFunc("/download", downloadFile)
http.ListenAndServe(":8080", nil)
}
이제 파일 업로드 및 다운로드를 처리하는 데 필요한 코드를 구현했습니다. 필요에 따라 코드를 수정하여 세부적인 요구사항을 충족시킬 수 있습니다.
더 자세한 내용은 공식 문서를 참고하세요: net/http - Go 언어