>曾經想過像貝特利這樣的服務如何從冗長的URL創建簡潔,可共享的鏈接?該教程指導您使用GO,Redis和Docker構建URL縮短器。 對於開發人員來說,這是一個很好的項目,以提高他們在實際網絡開發方面的技能。
鍵學習成果
這將生成用於依賴關係管理的文件。 用您的github用戶名替換
mkdir url-shortener cd url-shortener go mod init github.com/<username>/url-shortener
>
go.mod
2。項目結構<username>
3。依賴性安裝
<code>url-shortener/ ├── handlers/ # API request handlers │ └── handlers.go ├── models/ # Data structures │ └── url.go ├── router/ # Routing configuration │ └── router.go ├── storage/ # Redis interaction logic │ └── redis-store.go ├── main.go # Application entry point ├── Dockerfile # Docker build instructions ├── docker-compose.yml # Docker Compose configuration └── go.mod # Go module file</code>
這些提供了redis交互和路由功能。
go get github.com/go-redis/redis/v8 go get github.com/gorilla/mux
在
5。 REDIS存儲配置models/url.go
package models type ShortenRequest struct { URL string `json:"url"` } type ShortenResponse struct { ShortURL string `json:"short_url"` }
此代碼使用redis處理保存和檢索URL。 FNV-1A哈希功能可確保有效的短URL生成。 storage/redis-store.go
>
// ... (RedisStore struct and methods as in original example) ...
在
中創建API邏輯:這些處理程序管理URL縮短,重定向和頂級域檢索。 handlers/handlers.go
// ... (ShortenURL, RedirectURL, GetTopDomains functions as in original example) ...
在
中定義API路由:這配置了用於縮短,重定向和檢索頂部域的路由。
router/router.go
8。應用程序入口點
// ... (SetupRouter function as in original example) ...
>中,啟動HTTP服務器:
main.go
創建A
// ... (main function as in original example) ...
10。 docker-compose.yml配置
>
Dockerfile
// ... (Dockerfile content as in original example) ...
docker-compose.yml
這會構建Docker圖像並啟動容器。
// ... (docker-compose.yml content as in original example) ...
您已經成功地建立了URL縮短服務!該項目展示了實用的GO,Redis和Docker技能。
考慮以下這些擴展:
>的實際值。 <username>
>
以上是URL使用GO縮短服務的詳細內容。更多資訊請關注PHP中文網其他相關文章!