英文:
How to use URL from user input in Go?
问题
我几乎完全不了解Go语言,我目前的问题是从用户输入中读取URL并将其存储到一个变量中,以便作为参数传递给http.Get()函数。
以下是代码:
package main
import (
"bufio"
"fmt"
"net/http"
"os"
"reflect"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter URL: ")
txt, _ := reader.ReadString('\n')
fmt.Println(reflect.TypeOf(txt)) // 获取对象类型
//url := fmt.Sprintf("http://%s",txt)
url := "http://google.com"
fmt.Println(reflect.TypeOf(url)) // 获取对象类型
resp, err := http.Get(url)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
} else {
fmt.Printf("%s\n", resp.Status)
}
}
这段代码运行得很好:
d:\Go\bin>get_status
Enter URL: google.com
string
string
200 OK
但是,当我取消注释代码的第16行(同时注释掉第17行):
url := fmt.Sprintf("%s",txt)
//url := "http://google.com"
以便使用用户输入的URL时,我遇到了一个问题:
d:\Go\bin>get_status
Enter URL: google.com
string
string
Get http://google.com: dial tcp: GetAddrInfoW: No such host is known.
我的代码有什么问题?请帮我解决疑惑!
更新:
添加import "strings"
,并使用url := strings.TrimSpace(fmt.Sprintf("http://%s",txt))
修复了问题。
ReadString
函数会读取输入直到第一个分隔符出现为止,返回包含分隔符在内的数据的字符串。
英文:
I am almost absolutely new to Go language and my current problem is to read URL from user input into a variable to be passed as an argument to http.Get().
The following code
package main
import (
"bufio"
"fmt"
"net/http"
"os"
"reflect"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter URL: ")
txt, _ := reader.ReadString('\n')
fmt.Println(reflect.TypeOf(txt)) // Get object type
//url := fmt.Sprintf("http://%s",txt)
url := "http://google.com"
fmt.Println(reflect.TypeOf(url)) // Get object type
resp, err := http.Get(url)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
} else {
fmt.Printf("%s\n", resp.Status)
}
}
works perfectly:
d:\Go\bin>get_status
Enter URL: google.com
string
string
200 OK
but when I uncomment line 16 of the code (while commenting out line 17)
url := fmt.Sprintf("%s",txt)
//url := "http://google.com"
to use URL from user input, I get a problem:
d:\Go\bin>get_status
Enter URL: google.com
string
string
Get http://google.com
: dial tcp: GetAddrInfoW: No such host is known.
What could be wrong with my code? Please soothe my pain!
Upd:
import "strings"
plus url := strings.TrimSpace(fmt.Sprintf("http://%s",txt))
fixed the problem.
> ReadString reads until the first occurrence of delim in the input,
> returning a string containing the data up to and including the
> delimiter.
答案1
得分: 1
好的,看起来ReadString
包括分隔符,所以你可以使用strings
包中的TrimSpace
函数。这对我来说似乎起作用了。
url = strings.TrimSpace(url)
英文:
Alright, so it appears that ReadString
includes the delimiter, so you can use TrimSpace
from the strings
package. This seemed to do the trick for me.
url = strings.TrimSpace(url)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论