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

想快速搭建一个属于自己的短链接服务?用 Golang 可以很轻松地实现。下面带你一步步写一个简单的 URL 缩短服务,包含基本的生成短码、重定向和存储功能,不依赖外部数据库,适合学习和本地测试。
1. 基本功能设计
短链接服务的核心逻辑是:
- 接收一个长 URL,生成一个唯一的短码(比如 6 位字符串)
- 将短码和原始 URL 存储映射关系
- 通过短码访问时,重定向到原始 URL
我们使用内存 map 作为存储,用随机生成的 6 位字符串作为短码,HTTP 路由使用标准库 net/http。
2. 项目结构和依赖
新建一个项目目录,比如 url-shortener,创建 main.go。不需要额外依赖,只用 Golang 标准库。
立即学习“go语言免费学习笔记(深入)”;
3. 实现代码
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)
}
4. 使用方法
运行服务:
使用 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 持久化、自定义短码、过期时间、访问统计等功能。










