0

I am a beginner to Golang. Can you help me with call of function. Here is an example:

package main

import (
    "fmt"
    "net/http"
)

type Info struct {
    Name string  `json:"name"`
    Year float64 `json:"year,string"`
}

func (b *Base) GetInfo() (Info, error) {
    var resp Info
    path := "example.com"

    return resp, http.Get(path)
}

func main() {
    test, err := Base.GetInfo()
    fmt.Println(test, err)

}

Output:

{Name Bob Year 10}

How I can get only "Bob" ?

And If my response contains more objects example

{Name Bob Year 10}{Name Jane Year 2}.

How I can get only names? Didnt understand how to decode it or call.

jschroedl
  • 4,916
  • 3
  • 31
  • 46
frostrock
  • 789
  • 1
  • 5
  • 11
  • [Take the Go Tour](https://tour.golang.org/welcome/1). And also this `return resp, http.Get(path)` is never gonna compile. – mkopriva Apr 13 '18 at 15:58

1 Answers1

0

Use . parameter to get name from resp like

func main() {
    test, err := Base.GetInfo()
    fmt.Println(test.Name, err)
}

But if there are multiple fields. Then you should save them in array of struct Info as:

func (b *Base) GetInfo() ([]Info, error) {
    var resp []Info
    path := "example.com"
    return resp, http.Get(path)
}

func main() {
    test, err := Base.GetInfo()
    fmt.Println(test[0].Name, err)
}
Himanshu
  • 12,071
  • 7
  • 46
  • 61
  • Shouldn't it be `test.Name` rather than `test.name`? I mean, the struct `Info` has a `Name` field not `name` field. – Megidd Apr 13 '18 at 23:34