入門
首先為您的專案建立一個新資料夾,並使用以下命令初始化 Go 模組:
去 mod init github.com/vishaaxl/cheershare
設定項目結構
先設定一個具有以下資料夾結構的新 Go 專案:
my-otp-auth-server/ ├── cmd/ │ └── api/ │ └── main.go │ └── user.go │ └── token.go ├── internal/ │ └── data/ │ ├── models.go │ └── user.go │ └── token.go ├── docker-compose.yml ├── go.mod └── Makefile
接下來,設定 docker-compose.yml 檔案。此配置將定義您將在本教程中使用的服務(PostgreSQL 和 Redis)。
使用 Docker Compose 設定服務
我們將從配置我們的專案所需的服務開始。對於後端,我們需要以下:
Redis:我們將使用 redis:6 映像。該服務將配置安全存取密碼,公開連接埠 6379,並使用 --requirepass 標誌強制進行密碼驗證以保護 Redis 存取。
PostgreSQL:我們將使用 postgres:13 映像。該服務將定義預設使用者、密碼和資料庫,公開連接埠 5432 進行通信,並使用命名卷 (postgres_data) 保存資料以確保持久性。
可選:
- 主要後端服務:您也可以在這裡定義主要後端服務,它將與 PostgreSQL 和 Redis 互動。
// docker-compose.yml services: postgres: image: postgres:13 container_name: postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: mysecretpassword POSTGRES_DB: cheershare ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data redis: image: redis:6 container_name: redis environment: REDIS_PASSWORD: mysecretpassword ports: - "6379:6379" command: ["redis-server", "--requirepass", "mysecretpassword"] volumes: postgres_data:
主要後端服務
為了路由和處理 HTTP 請求,我們將使用 github.com/julienschmidt/httprouter 套件。若要安裝依賴項,請執行以下命令:
go get github.com/julienschmidt/httprouter
接下來,在 cmd/api/main.go 建立一個檔案並貼上以下程式碼。註釋中提供了每行的解釋:
// main.go package main import ( "fmt" "log" "net/http" "os" "time" "github.com/julienschmidt/httprouter" ) /* config struct: - Holds application-wide configuration settings such as: - `port`: The port number on which the server will listen. - `env`: The current environment (e.g., "development", "production"). */ type config struct { port int env string } /* applications struct: - Encapsulates the application's dependencies, including: - `config`: The application's configuration settings. - `logger`: A logger instance to handle log messages. */ type applications struct { config config logger *log.Logger } func main() { cfg := &config{ port: 4000, env: "development", } logger := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime) app := &applications{ config: *cfg, logger: logger, } router := httprouter.New() router.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "Welcome to the Go application!") }) /* Initialize the HTTP server - Set the server's address to listen on the specified port. - Assign the router as the handler. - Configure timeouts for idle, read, and write operations. - Set up an error logger to capture server errors. */ srv := &http.Server{ Addr: fmt.Sprintf(":%d", app.config.port), Handler: router, IdleTimeout: time.Minute, ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second, } app.logger.Printf("Starting server on port %d in %s mode", app.config.port, app.config.env) err := srv.ListenAndServe() if err != nil { app.logger.Fatalf("Could not start server: %s", err) } }
現在,您可以透過使用 go run ./cmd/api 啟動伺服器並向 http://localhost:4000 發送請求來測試您的設置,這將傳回一條歡迎訊息。接下來,我們將定義三個附加路由來實現我們的核心功能:
/send-otp:此路由將處理傳送 OTP給使用者。它將產生一個唯一的 OTP,將其儲存在 Redis 中,並將其傳遞給使用者。
/verify-otp:此路由將驗證使用者提供的 OTP。它將檢查 Redis 中儲存的值以確認使用者的身分。
/login:一旦驗證 OTP 並成功建立用戶,此路由將處理用戶登入功能。
但在繼續之前,我們需要一種方法來儲存使用者訊息,例如電話號碼及其一次性密碼,為此我們需要連接到我們之前在 docker-compose.yml 檔案中定義的服務。
定義輔助函數
在實作路由之前,讓我們先定義兩個基本的輔助函數。這些函數將處理與 Redis 和 PostgreSQL 伺服器的連接,確保我們的後端可以與這些服務互動。
修改「config」結構以儲存有關服務的資訊。 這些功能非常不言自明。
my-otp-auth-server/ ├── cmd/ │ └── api/ │ └── main.go │ └── user.go │ └── token.go ├── internal/ │ └── data/ │ ├── models.go │ └── user.go │ └── token.go ├── docker-compose.yml ├── go.mod └── Makefile
透過 docker-compose up -d 指令啟動服務後,您可以使用這些函式建立與 PostgreSQL 資料庫和 Redis 伺服器的連線。
在下一部分中,我們將開始研究之前討論過的那些路線。這就是你的 main.go 檔案現在應該的樣子。
// docker-compose.yml services: postgres: image: postgres:13 container_name: postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: mysecretpassword POSTGRES_DB: cheershare ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data redis: image: redis:6 container_name: redis environment: REDIS_PASSWORD: mysecretpassword ports: - "6379:6379" command: ["redis-server", "--requirepass", "mysecretpassword"] volumes: postgres_data:
以上是使用 Go 建置基於 OTP 的身份驗證伺服器:第 1 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Golang更適合高並發任務,而Python在靈活性上更有優勢。 1.Golang通過goroutine和channel高效處理並發。 2.Python依賴threading和asyncio,受GIL影響,但提供多種並發方式。選擇應基於具體需求。

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang和Python分別在哪些方面更易用和學習曲線更平緩? Golang更適合高並發和高性能需求,學習曲線對有C語言背景的開發者較平緩。 Python更適合數據科學和快速原型設計,學習曲線對初學者非常平緩。

Golang和C 在性能競賽中的表現各有優勢:1)Golang適合高並發和快速開發,2)C 提供更高性能和細粒度控制。選擇應基於項目需求和團隊技術棧。

Golang適合快速開發和並發編程,而C 更適合需要極致性能和底層控制的項目。 1)Golang的並發模型通過goroutine和channel簡化並發編程。 2)C 的模板編程提供泛型代碼和性能優化。 3)Golang的垃圾回收方便但可能影響性能,C 的內存管理複雜但控制精細。

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3 Linux新版
SublimeText3 Linux最新版

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器