使用Golang可快速搭建短链接服务,通过内存map存储短码与长URL映射,生成6位随机短码,支持POST创建短链和浏览器重定向访问。

想快速搭建一个属于自己的短链接服务?用 Golang 可以很轻松地实现。下面带你一步步写一个简单的 URL 缩短服务,包含基本的生成短码、重定向和存储功能,不依赖外部数据库,适合学习和本地测试。
短链接服务的核心逻辑是:
我们使用内存 map 作为存储,用随机生成的 6 位字符串作为短码,HTTP 路由使用标准库 net/http。
新建一个项目目录,比如 url-shortener,创建 main.go。不需要额外依赖,只用 Golang 标准库。
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
"strings"
"time"
)
// 存储映射:短码 -> 原始 URL
var urlStore = make(map[string]string)
// 字符集用于生成短码
const shortChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const shortLength = 6
// 生成唯一的短码
func generateShortCode() string {
rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, shortLength)
for i := range b {
b[i] = shortChars[rand.Intn(len(shortChars))]
}
return string(b)
}
// 创建短链接
func shortenHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "只支持 POST", http.StatusMethodNotAllowed)
return
}
type request struct {
URL string `json:"url"`
}
var req request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil || req.URL == "" {
http.Error(w, "无效的请求体", http.StatusBadRequest)
return
}
// 确保 URL 以 http 开头
if !strings.HasPrefix(req.URL, "http://") && !strings.HasPrefix(req.URL, "https://") {
req.URL = "http://" + req.URL
}
// 生成短码(简单起见,不检查重复,实际应用需循环检查)
var shortCode string
for {
shortCode = generateShortCode()
if _, exists := urlStore[shortCode]; !exists {
break
}
}
urlStore[shortCode] = req.URL
// 返回短链接
result := map[string]string{
"short_url": fmt.Sprintf("http://localhost:8080/%s", shortCode),
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
}
// 重定向到原始 URL
func redirectHandler(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/")
if path == "" {
http.Error(w, "请输入短码", http.StatusBadRequest)
return
}
originalURL, exists := urlStore[path]
if !exists {
http.Error(w, "短码不存在", http.StatusNotFound)
return
}
http.Redirect(w, r, originalURL, http.StatusFound)
}
func main() {
http.HandleFunc("/shorten", shortenHandler)
http.HandleFunc("/", redirectHandler)
fmt.Println("服务启动在 http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
运行服务:
go run main.go使用 curl 创建短链接:
curl -X POST http://localhost:8080/shorten \ -H "Content-Type: application/json" \ -d '{"url": "https://example.com/very/long/path"}'返回示例:
{"short_url":"http://localhost:8080/abc123"}在浏览器访问 http://localhost:8080/abc123 就会跳转到原始页面。
基本上就这些。这个版本适合理解原理。如果要上线,可以加 Redis 持久化、自定义短码、过期时间、访问统计等功能。
以上就是跟着教程用Golang实现一个简单的URL缩短服务的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号