Clarification about http.Get

hi, I wrote the file net.go as below:

package main

import (
	"io"
	"net/http"
)

func indexHandler(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "Hello, world!\n")
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.ListenAndServe(":8482", nil)
}

An it is working file at the browser:

I want to call it from another GO file, so I wrote file get.go at the same folder of the first one net.go as below:

package main

import "net/http"

func main() {
	resp, err := http.Get("http://localhost:8482/")
	if err != nil {
		println("err: ", err)
	} else {
		println("resp: ", resp)
	}
}

But while running it, I got the below error:

it looks that the program executed correctly. It displays the address of the pointer in the resp variable. It looks like a windows issue? I’m not an expert here.

The response is http.Response struct. You can check the status code by checking the resp.StatusCode.

The error looks like either a windows permission problem or a go problem - your code is fine!

If you go build the executable and then run it, I’m sure it will work.

The below code worked with me:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    res, err := http.Get("http://localhost:8483")
    if err != nil {
        log.Fatal(err)
    }
    robots, err := ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", robots)
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.