37

短连接跳转的原理

 5 years ago
source link: https://www.tuicool.com/articles/7NjQFjR
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

日常中常用短链接来节省字符长度,如中国移动的活动短信: fUN3QbE.jpg!web 那么它的实现原理很简单: 就是302跳转 通过对传进来的url生成一个短的编码,然后使这个编码与这个url在数据库中一一对应,然后通过访问对外公开的api中如: https://t.cn/+生成的短链接,然后取到这个生成的短链接去数据库中查询对应的url,重定向302返回浏览器即可。这里我们不关心加密之类算法,数据存储的过程,只看短链接如何实现跳转的过程

下面是代码演示:

package main

import (
	"net/http"
)

func OpenOrigin(w http.ResponseWriter, r *http.Request) {
	// 截取传入的段路径
	path := r.URL.Path[len("/jump/"):]
       // http.StatusFound 就是302
	if path == "clylia" {
		// 重定向到原网址,使用clylia和https://www.baidu.com对应
		http.Redirect(w, r, "https://www.baidu.com", http.StatusFound)
	} else if path == "golang" {
		// 重定向到原网址,使用golang和https://studygolang.com对应
		http.Redirect(w, r, "https://studygolang.com", http.StatusFound)
	} else {
                w.Write([]byte("I don't konw what to do."))
        }
}

func main() {
	http.HandleFunc("/jump/", OpenOrigin)
	http.ListenAndServe(":5000", nil)
}

这里我们启动了一个http server,通过访问http://127.0.0.1:5000/jump/clylia,来实现跳转的过程 启动服务,我们在浏览器中访问http://127.0.0.1:5000/jump/clylia时,浏览器会跳转到https://www.baidu.com这里,输入http://127.0.0.1:5000/jump/golang时就是访问https://studygolang.com,那么短链接的原理就是这样了,谢谢


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK