duanchui1279 2014-09-09 14:45
浏览 29
已采纳

确保URI有效

I'm trying to ensure that URLs passed to my go program are valid. However, I can't seem to work out how to. I thought I could just feed it through url.Parse, but that doesn't seem to do the job.

package main

import (
    "fmt"
    "net/url"
)

func main() {
    url, err := url.Parse("http:::/not.valid/a//a??a?b=&&c#hi")
    if err != nil {
        panic(err)
    }
    fmt.Println("It's valid!", url.String())
}

playground

Is there anything along the lines of filter_var I can use?

  • 写回答

3条回答 默认 最新

  • dparivln22034 2014-09-09 15:02
    关注

    You can check that your URL has a Scheme, Host, and/or a Path.

    If you inspect the URL returned, you can see that the invalid part is inserted into the Opaque data section (so in a sense, it is valid).

    url.URL{Scheme:"http", Opaque:"::/not.valid/a//a", Host:"", Path:"", RawQuery:"?a?b=&&c", Fragment:"hi"}
    

    If you parse a URL and don't have a Scheme, Host and Path you can probably assume it's not valid. (though a host without a path is often OK, since it implies /, so you need to check for that)

    u, err := url.Parse("http:::/not.valid/a//a??a?b=&&c#hi")
    if err != nil {
        log.Fatal(err)
    }
    
    if u.Scheme == "" || u.Host == "" || u.Path == "" {
        log.Fatal("invalid URL")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?