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.