この記事では、Golang RESTful API を構築する方法について説明します。まず、必要なライブラリをインポートし、データ モデルを定義し、ルートを作成して、RESTful API を構築します。次に、go-chi/chigot と go-chi/chi/middleware を使用して認証用のミドルウェアを作成して適用します。この記事ではさらに、ソリューションの実際の応用例を示す実際的な事例も示しています。

Golang RESTful API を構築し、認証にミドルウェアを使用する方法
1. RESTful API を構築する
必要なライブラリをインポートします:
1 2 3 4 5 6 7 8 | import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
|
ログイン後にコピー
データ モデルを定義します:
1 2 3 4 5 | type Product struct {
ID int `json: "id" `
Name string `json: "name" `
Price float64 `json: "price" `
}
|
ログイン後にコピー
ルート:
1 2 3 4 5 6 | 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" )
|
ログイン後にコピー
制御 定義コントローラー:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <strong>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) {
}</strong>
|
ログイン後にコピー
e2. 本人確認にミドルウェアを使用する
ミドルウェアのインストール:
1 2 | <strong>go get github.com/go-chi/chi
go get github.com/go-chi/chi/middleware</strong>
|
ログイン後にコピー
ミドルウェアの作成:
1 2 3 4 5 6 7 8 9 10 11 | <strong>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)
})
}</strong>
|
ログイン後にコピー
アプリケーション ミドルウェア:
1 | <strong>router.Use(AuthMiddleware)</strong>
|
ログイン後にコピー
E 実用的なケース
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <strong>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))
}</strong>
|
ログイン後にコピー
以上がGolang RESTful API を構築し、認証にミドルウェアを使用するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。