【问题标题】:How to get rid of https if included in the input [closed]如果包含在输入中,如何摆脱 https [关闭]
【发布时间】:2021-06-03 07:50:50
【问题描述】:

我当前的代码接受称为installationDNS 的参数(第一个是URL)。目前我希望用户不要输入带有https 的URL,但如果他们确实在URL 中包含https,我该如何摆脱它?

例如,如果他们输入https://randomDNS.com,我只想要randomDNS.com 部分。

if len(args) == 0 {
    return nil, true, errors.New("must provide an installation DNS")
}
installationDNS := standardizeName(args[0])

【问题讨论】:

  • 我投票结束这个问题,因为这个问题显示没有任何尝试解决手头的问题。

标签: string validation go user-input


【解决方案1】:

您可能还想修剪http://,并删除之后的任何路径,因此只能从 url 中获取域。

net/url 包派上用场了。您可以执行以下操作:

const link = "https://randomdns.com"
u, err := url.Parse(link)
if err != nil {
    return nil, true, fmt.Errorf("error parsing url: %w", err)
}
fmt.Println("domain:", u.Hostname())

Playground

这将始终只提取 URL 的主机名部分,因此在用户输入之前是最安全的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2011-06-24
    • 1970-01-01
    相关资源
    最近更新 更多