登录
首页 >  Golang >  Go问答

Golang使用unicode关键字获取数据错误

来源:stackoverflow

时间:2024-04-17 21:15:37 450浏览 收藏

大家好,我们又见面了啊~本文《Golang使用unicode关键字获取数据错误》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我有一个调用 twitter api 的函数。如果输入包含带有非 ascii 字符的关键字 (q=éxito),则 api 会以 401 进行响应:

https://api.twitter.com/1.1/search/tweets.json?q=éxito&count=100&result_type=recent&include_entities=true

但 url 中包含全 ascii 字符,则响应 w/ok:

https://api.twitter.com/1.1/search/tweets.json?q=teampixel&count=100&result_type=recent&include_entities=true

func GetJson(url string, target interface{}) error {
    e := godotenv.Load()
    if e != nil {
        fmt.Print(e)
    }
    println(url)
    config := oauth1.NewConfig(os.Getenv("API_KEY"), os.Getenv("API_SECRET_KEY"))
    token := oauth1.NewToken(os.Getenv("ACCESS_TOKEN"), os.Getenv("ACCESS_TOKEN_SECRET"))
    // httpClient will automatically authorize http.Request's
    httpClient := config.Client(oauth1.NoContext, token)

    resp, e := httpClient.Get(url)
    const errorDelay = 30
    if e != nil {
        fmt.Println("Connection Issue")
        time.Sleep(errorDelay * time.Second)
        return GetJson(url, target)
    }
    defer resp.Body.Close()
    if resp.StatusCode == 429 {
        fmt.Println("\nThrotteling")
        time.Sleep(errorDelay * time.Second)
        return GetJson(url, target)
    }

    if resp.StatusCode == 404 {
        fmt.Println("Could not find", url)
        return errors.New("not found")
    }
    fmt.Printf("Results: %v\n", resp.StatusCode)

    return json.NewDecoder(resp.Body).Decode(target)
}

解决方案


使用 url.parse()

package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {
    _url := "https://abbreviated-path?q=%c3%a9xito&count=..."
    u, err := url.parse(_url)
    if err != nil {
        log.fatal(err)
    }
    fmt.println(u.string())
}

似乎可以解决问题:

https://abbreviated-path?q=%C3%A9xito&count=...

以上就是《Golang使用unicode关键字获取数据错误》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>