zoukankan      html  css  js  c++  java
  • golang获取URL

    在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 }
  • 相关阅读:
    HTTP/HLS/RTMP超级负载测试工具(转)
    Jmeter监控Linux服务器性能
    装饰器做缓存
    内置装饰器
    Python装饰器 计时器记录方法执行性能
    【Python】装饰器实现日志记录
    Java对关于两个地点的根据经纬度算出后排序
    JS获得当前位置信息
    百度地图插件开发使用三 及jquery function(a.b)排序等
    css用clearfix清除浮动
  • 原文地址:https://www.cnblogs.com/merrynuts/p/13157381.html
Copyright © 2011-2022 走看看