I did an input where the user can input the "target" that should be searched via an api. I was wondering how to add the string to the end of the link.
func send() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Target: ")
target, _ := reader.ReadString('\n')
var i int
fmt.Println("Delay: ")
_, error_d := fmt.Scanf("%d", &i)
if error_d != nil {
fmt.Println(error_d)
}
delay, _ := reader.ReadString('\n')
fmt.Println("Delay: ", delay)
fmt.Println("Target: ", target)
resp, error := http.Get("https://api.ashcon.app/mojang/v2/user/"+target+"")
if error != nil {
print(error)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
print(err)
}
fmt.Print(string(body))
print(" ")
}
This gives me this error:
(0x80a8c0,0xc0000ac900)panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x40 pc=0x73f39d]
resp, error := http.Get("https://api.ashcon.app/mojang/v2/user/"+target+"")
if error != nil {
print(error)
}
defer resp.Body.Close()
You don't have any return if error != nil
then after print(error)
your function continue, trying to close resp.Body.Close()
with nil resp at the end by the defer statement
This should works:
resp, error := http.Get("https://api.ashcon.app/mojang/v2/user/"+target+"")
if error != nil {
print(error)
return
}
defer resp.Body.Close()
Some info about defer https://golang.org/ref/spec#Defer_statements:
A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.
User contributions licensed under CC BY-SA 3.0