0

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.

3
  • @jiang Unfortunately, I can't get it work... Commented Jan 28, 2016 at 6:59
  • @Vifonius Even using TrimSpace? Commented Jan 28, 2016 at 7:00
  • @jacob No, I'm on Windows. Commented Jan 28, 2016 at 7:05

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Fascinating! Thank you very much! The problem was with '\n' at the end of the string!
Yeha, debugging the object types is much less useful (as Go is statically typed) than printing the actual value with %v (or even %#v).
@Volker I just wanted to be sure that I got strings in both cases. Thank you for your comment!
@Vifonius What else could func (*bufio.Reader) ReadString(byte) (string, error) possibly return?
@Volker Undoubtedly, I should have read the docs more thoroughly. :) I was just under fresh impression of Elixir where I had to convert URL from string to char list before passing it to :httpc.request function: url = String.to_char_list(url)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.