duanpa2143
duanpa2143
2016-01-28 06:12

如何在Go中使用来自用户输入的URL?

已采纳

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('
')
    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
", 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条回答

  • duanqiechui2378 duanqiechui2378 5年前

    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)
    
    点赞 评论 复制链接分享

相关推荐