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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)