donglvlao8367 2018-10-23 09:56
浏览 159
已采纳

golang ParseQuery url给我错误的输出

I have the following code:

func init() {
    today := time.Now()

    // If ENDPOINT is empty, It'll use this hardcoded endpoint. The ENDPOINT variable should not contain any text after "ModifiedDate gt". The actual date is currentDay-1
    if ENDPOINT == "" {
        ENDPOINT = "http://localhost:8000/Contacts/Export/?$select=Firstname,Lastname,Email,SubaccountId&$filter=EEA eq '' and ModifiedDate gt"
    }

    // Append CurrentDay-1 in YYY`enter code here`Y-MM-DDTHH:MM:SSZ format.
    // The time is NOT in UTC. It's the local time of the machine on which lambda function was running
    ENDPOINT = fmt.Sprintf("%s %s", ENDPOINT, today.AddDate(0, 0, -1).Format("2006-01-02T15:04:05Z"))

    var err error
    // parse the url
    PARSED_ENDPOINT, err = url.Parse(ENDPOINT)
    if err != nil {
        log.Fatalln("Invalid $ENDPOINT", err)
    }

    // parse the query parameters
    parsedQueryParams, err := url.ParseQuery(PARSED_ENDPOINT.RawQuery)
    if err != nil {
        log.Fatalln("error in parsing query parameters", err)
    }

    // URLEncode query parameters
    PARSED_ENDPOINT.RawQuery = parsedQueryParams.Encode()
}

When I output the URL, I get:

'http://localhost:8000/Contacts/Export/?%24filter=EEA+eq+%27%27+and+ModifiedDate+gt+2018-10-22T08%3A45%3A45Z&%24select=Email%2CFirstname%2CLastname%2CSubaccountId%2CEEA'

How do I return:

'http://localhost:8000/Contacts/Export/?$filter=EEA%20eq%20%27%27%20and%20ModifiedDate%20gt%202018-10-22T00:00:00Z&$select=Email,Firstname,Lastname,SubaccountId,EEA'

Any advice is much appreciated

  • 写回答

1条回答 默认 最新

  • dongpu1315 2018-10-23 10:21
    关注

    Golang provide url package to manage this problem and pass the query string with key values to the browser and parse it accordingly after encoding the string which will resolve special characters issue:

    package main
    
    import (
        "fmt"
        "net/url"
    )
    
    func main() {
        query := make(url.Values)
        query.Add("key", "value")
        url := &url.URL{RawQuery: query.Encode(), Host: "foo", Scheme: "http"}
        fmt.Println(url)
    }
    

    Avoid using string query and adding values using fmt package Sprintf methods.This is not a proper way to manage query strings and creating a dynamic url.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵