>  기사  >  백엔드 개발  >  Golang RESTful API를 구축하고 인증을 위해 미들웨어를 사용하는 방법은 무엇입니까?

Golang RESTful API를 구축하고 인증을 위해 미들웨어를 사용하는 방법은 무엇입니까?

WBOY
WBOY원래의
2024-06-04 14:16:56817검색

이 문서에서는 Golang RESTful API를 구축하는 방법을 설명합니다. 먼저, 필요한 라이브러리를 가져오고, 데이터 모델을 정의하고, 경로를 생성하여 RESTful API를 구축합니다. 둘째, go-chi/chigot과 go-chi/chi/middleware를 이용하여 인증을 위한 미들웨어를 생성하고 적용한다. 이 기사에서는 솔루션의 실제 적용을 보여주기 위한 실제 사례도 제공합니다.

如何构建 Golang RESTful API,并使用中间件进行身份验证?

Golang RESTful API를 구축하고 인증을 위해 미들웨어를 사용하는 방법

1. RESTful API 구축

필요한 라이브러리 가져오기:

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

데이터 모델 정의:

type Product struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Price float64 `json:"price"`
}

생성 경로:

router := mux.NewRouter()
router.HandleFunc("/products", GetProducts).Methods("GET")
router.HandleFunc("/products/{id}", GetProduct).Methods("GET")
router.HandleFunc("/products", CreateProduct).Methods("POST")
router.HandleFunc("/products/{id}", UpdateProduct).Methods("PUT")
router.HandleFunc("/products/{id}", DeleteProduct).Methods("DELETE")
控 정의 컨트롤러:

func GetProducts(w http.ResponseWriter, r *http.Request) {
    // ...
}

func GetProduct(w http.ResponseWriter, r *http.Request) {
    // ...
}

func CreateProduct(w http.ResponseWriter, r *http.Request) {
    // ...
}

func UpdateProduct(w http.ResponseWriter, r *http.Request) {
    // ...
}

func DeleteProduct(w http.ResponseWriter, r *http.Request) {
    // ...
}
e2. 신원 확인을 위해 미들웨어 사용

미들웨어 설치:

go get github.com/go-chi/chi
go get github.com/go-chi/chi/middleware

미들웨어 생성:

func AuthMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // ... 检查认证信息 ...
        if !authorized {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        // ... 继续处理请求 ...
        next.ServeHTTP(w, r)
    })
}

애플리케이션 미들웨어:

router.Use(AuthMiddleware)
E 실제 사례

예:

func main() {
    // 初始化数据库连接
    db, err := sql.Open("sqlite3", "mydb.db")
    if err != nil {
        log.Fatal(err)
    }

    // 创建路由器
    router := mux.NewRouter()

    // 定义路由并应用身份验证中间件
    router.HandleFunc("/products", GetProducts).Methods("GET").Use(AuthMiddleware)
    router.HandleFunc("/products/{id}", GetProduct).Methods("GET").Use(AuthMiddleware)
    router.HandleFunc("/products", CreateProduct).Methods("POST").Use(AuthMiddleware)
    router.HandleFunc("/products/{id}", UpdateProduct).Methods("PUT").Use(AuthMiddleware)
    router.HandleFunc("/products/{id}", DeleteProduct).Methods("DELETE").Use(AuthMiddleware)

    // 启动服务器
    http.Handle("/", router)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

위 내용은 Golang RESTful API를 구축하고 인증을 위해 미들웨어를 사용하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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