찾다
백엔드 개발GolangGo에서 파일 업로드 API 구축

Building a File Upload API in Go

파일 업로드 API를 생성하는 것은 사용자가 문서, 이미지 또는 기타 미디어 파일을 제출하는 것과 관련된 많은 웹 애플리케이션의 일반적인 요구 사항입니다. 이 기사에서는 Gin 프레임워크와 함께 Go를 사용하여 안전하고 효율적인 파일 업로드 API를 구축하는 방법을 안내합니다. 프로젝트를 설정하고, 들어오는 파일을 처리하고, 안전하게 저장하여 애플리케이션이 사용자가 업로드한 콘텐츠를 안정적으로 관리할 수 있도록 하는 방법을 배우게 됩니다.

전제 조건

1.21로 이동

프로젝트 설정

Go 프로젝트 종속성을 설정합니다.

go mod init app
go get github.com/gin-gonic/gin

프로젝트 구조

├─ main.go
├─ models
│  └─ product.go
└─ public
   └─ index.html

프로젝트 파일

product.go

제품은 파일 업로드 API에서 파일 업로드를 테스트하는 데 사용되는 간단한 구조체입니다.

package models

type Product struct {
    Name string
}

main.go

파일 업로드 API를 설정하는 파일입니다. 최소한의 Go 웹 애플리케이션을 생성하고 설정합니다.

package main

import (
    "app/models"
    "io"
    "net/http"
    "os"
    "path/filepath"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"
)

func main() {
    router := gin.Default()
    uploadPath := "./public/uploads"
    os.MkdirAll(uploadPath, os.ModePerm)
    router.Static("/uploads", uploadPath)
    router.StaticFile("/", "./public/index.html")
    router.POST("/submit", func(c *gin.Context) {
        var product models.Product
        if err := c.ShouldBindWith(&product, binding.FormMultipart); err != nil {
            c.AbortWithStatusJSON(http.StatusBadRequest, err.Error())
            return
        }
        image, _ := c.FormFile("Image")
        filePath := filepath.Join(uploadPath, image.Filename)
        src, _ := image.Open()
        dst, _ := os.Create(filePath)
        io.Copy(dst, src)
        c.JSON(http.StatusOK, gin.H{"Name": product.Name, "Image": image.Filename})
    })
    router.Run()
}

  • Gin 라우터를 초기화하고 업로드 디렉토리 및 index.html에 대한 정적 파일 제공을 설정합니다.
  • 업로드된 파일을 저장하기 위한 ./public/uploads 디렉토리가 있는지 확인하세요.
  • 파일 업로드를 처리하고, 파일을 서버에 저장하고, 제품 이름과 업로드된 파일 이름을 반환하기 위해 /submit에 POST 경로를 정의합니다.
  • 들어오는 요청을 수신하기 위해 Gin 서버를 시작합니다.

index.html

이 HTML 양식은 사용자가 관련 이미지 파일과 함께 제품 이름을 업로드할 수 있도록 설계되었습니다.


    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
    <script>
        function submitForm() {
            let form = document.getElementById('form')
            let data = new FormData(form)
            fetch('submit', {
                method: 'POST',
                body: data
            }).then(res => {
                res.json().then(result => {
                    let alert = document.getElementById('alert')
                    alert.children[0].innerText = `Upload success!\nName: ${result.Name}\nImage: ${result.Image}`
                    alert.children[1].src = `/uploads/${result.Image}`
                    alert.classList.remove('d-none')
                    form.reset()
                })
            })
            return false
        }
    </script>


    <div class="container">
        <div class="row mt-3">
            <form id="form" onsubmit="return submitForm()">
                <div class="mb-3 col-12">
                    <label class="form-label" for="name">Name</label>
                    <input id="name" name="Name" class="form-control form-control-sm" required>
                </div>
                <div class="mb-3 col-12">
                    <label class="form-label" for="image">Image</label>
                    <input type="file" accept="image/*" id="image" name="Image" class="form-control form-control-sm" required>
                </div>
                </form>
</div>
                <div class="col-12">
                    <button class="btn btn-sm btn-primary">Submit</button>
                </div>
            
            <div id="alert" class="alert alert-success mt-3 d-none">
                <p></p>
                <img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172551064373054.jpg?x-oss-process=image/resize,p_40" class="lazy" id="img"    style="max-width:90%" alt="Go에서 파일 업로드 API 구축" >
            </div>
        </div>
    

위 내용은 Go에서 파일 업로드 API 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이동 중에 시작 함수에 의존하는 테스트 코드이동 중에 시작 함수에 의존하는 테스트 코드May 03, 2025 am 12:20 AM

WhentestinggocodewithInitFunctions, useExplicitSetUpFunctionsOrsParateTestOvoiddenceNInItfictionSideffects.1) useExplicitSetUpFunctoControlGlobalVariableInitialization.2) CreateSeparateTesteSpilestobySinitFunctions 및 testesten

GO의 오류 처리 방식을 다른 언어와 비교합니다GO의 오류 처리 방식을 다른 언어와 비교합니다May 03, 2025 am 12:20 AM

go'serrorhandlingreturnserrorsvalues ​​whithuseexceptions와 달리 1) Go'sMethodensuresexpliciterRorhandling, promotingrobustcodebutincreasingverbosity.2) Javaandthon'sexextionslowercodebutcodebutcodebutcanlederforlortorifneterfortorifneteriflerortorifnetrorirederiflofertorifneateRoferfortoriflogertoflortoflerortofneateRofer

효과적인 인터페이스 설계를위한 모범 사례효과적인 인터페이스 설계를위한 모범 사례May 03, 2025 am 12:18 AM

AneffectiveInterfaceingoisminimal, Clear, and Promotesloosecoupling.1) Minimizetheinterfaceforflexibilityandeasofimplementation.2) usicfacesforabStractionToswapimementationswhangingCallingCode.3) DesignStabilitySUsingInterfacestomockDep

중앙 집중식 오류 처리 전략중앙 집중식 오류 처리 전략May 03, 2025 am 12:17 AM

중앙 집중식 오류 처리는 GO 언어에서 코드의 가독성과 유지 가능성을 향상시킬 수 있습니다. 구현 방법 및 장점에는 다음이 포함됩니다. 1. 비즈니스 로직에서 별도의 오류 처리 로직 및 코드를 단순화합니다. 2. 중앙 처리로 오류 처리의 일관성을 확인하십시오. 3. 연기 및 복구를 사용하여 공황을 포착하고 처리하여 프로그램 견고성을 향상시킵니다.

GO에서 패키지 초기화를위한 시작 함수를위한 대안GO에서 패키지 초기화를위한 시작 함수를위한 대안May 03, 2025 am 12:17 AM

Ingo, alternativestoinitFunctionsincustomInitializationFenctionsandsingletons.1) CustomInitializationFunctionsallowExplicitControlover wheninInitializationOccurs, lexplodElayEdorConditionalSetUps.2) SingletEntensureOne-TimeInitializationIncOncurrent

GO 인터페이스로 어설 션 및 유형 스위치를 입력하십시오GO 인터페이스로 어설 션 및 유형 스위치를 입력하십시오May 02, 2025 am 12:20 AM

gohandlesinterfacesandtypeassertionsefectively, codeflexibleandrobustness.1) typeSertionsOncaLownallowRuntImeTypeChecking, asseengehapeInterfaceAndCircLetype.2) TypeStwitchEshandleMultipleTypesePesePesePesePesePese -pervariousShapesimplementing Gry

오류를 사용하고 오류가 발생합니다. 오류 검사는 이동 중입니다오류를 사용하고 오류가 발생합니다. 오류 검사는 이동 중입니다May 02, 2025 am 12:11 AM

GO 언어 오류 처리는 오류와 오류를 통해 더욱 유연하고 읽을 수 있습니다. 1.Errors.is는 오류가 지정된 오류와 동일한 지 확인하는 데 사용되며 오류 체인의 처리에 적합합니다. 2. 오류. 오류 유형을 확인할 수있을뿐만 아니라 오류를 특정 유형으로 변환 할 수 있으며 오류 정보 추출에 편리합니다. 이러한 기능을 사용하면 오류 처리 로직을 단순화 할 수 있지만 오류 체인의 올바른 전달에주의를 기울이고 코드 복잡성을 방지하기 위해 과도한 의존성을 피하십시오.

GO의 성능 튜닝 : 응용 프로그램 최적화GO의 성능 튜닝 : 응용 프로그램 최적화May 02, 2025 am 12:06 AM

TomakeGoApplicationSRUNFASTERONDERFISTING, 사용 프로파일 링 툴, leverageConcurrency, andManageMemoryEffice.1) usepprofforcpuandMemoryProfingToIndifyBottLenecks.2) UtizeGoroutinesandChannelStoparAllelizetAskSandimProvePercormance.3) 3)

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구