首页 > 技术文章 > golang获取URL

merrynuts 原文

在golang中的http.Request对象中的所有属性,没有可以直接获取完整URL的方法。但可以通过host和请求地址进行拼接。具体方法是在Request.Host中获取hostname,Request.RequestURI获取相应的请求地址。

对于协议的判断,如区分http还是https协议,一开始尝试通过r.Proto属性判断,但是发现该属性不管是http,还是https都是返回HTTP/1.1,又寻找了下发现TLS属性,在https协议下有对应值,在http下为nil。
主要技术点:
1.通过r.TLS是否为nil判断scheme是http或https:
r.TLS == nil ---> http
r.TLS != nil ---> https
2.通过r.Proto获取http版本号,例如:HTTP/1.1
3.通过r.Host获取地址及端口号,例如:localhost:9090或127.0.0.1:8000
4.通过r.RequestURI获取目录及参数,例如:/index?id=2

完整代码:

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "log"
 6     "net/http"
 7     "strings"
 8 )
 9 
10 func index(w http.ResponseWriter, r *http.Request) {
11     fmt.Println("--------------------")
12     fmt.Println(r.Proto)
13     // output:HTTP/1.1
14     fmt.Println(r.TLS)
15     // output: <nil>
16     fmt.Println(r.Host)
17     // output: localhost:9090
18     fmt.Println(r.RequestURI)
19     // output: /index?id=1
20 
21     scheme := "http://"
22     if r.TLS != nil {
23         scheme = "https://"
24     }
25     fmt.Println(strings.Join([]string{scheme, r.Host, r.RequestURI}, ""))
26     // output: http://localhost:9090/index?id=1
27 }
28 
29 func GetURL(r *http.Request)(Url string) {
30     scheme := "http://"
31     if r.TLS != nil {
32         scheme = "https://"
33     }
34     return strings.Join([]string{scheme, r.Host, r.RequestURI}, "")
35 }
36 
37 func main() {
38     http.HandleFunc("/index", index)
39 
40     err := http.ListenAndServe(":9090", nil)
41     if err != nil {
42         log.Fatal("ListenAndServe: ", err)
43     }
44 }

推荐阅读