A few days ago I have to look at consuming API with GO from Ghost so here is what I learnt.
A very simple example of how to consume API and print it as text to console. It’s not much but it’s good to start.
1package main
2
3import (
4 "fmt"
5 "io/ioutil"
6 "log"
7 "net/http"
8 "os"
9)
10
11func main() {
12 var endpoint = "http://your-addres.domain/api/endpoint"
13
14 response, err := http.Get(endpoint)
15
16 if err != nil {
17 fmt.Print(err.Error())
18 os.Exit(1)
19 }
20
21 responseData, err := ioutil.ReadAll(response.Body)
22 if err != nil {
23 log.Fatal(err)
24 }
25 fmt.Println(string(responseData))
26}
Next, it will be good if I can return objects to use in my app instead of text. And go has to function for it called unmarshall. Unmarshalling JSON response need JSON module so I have to import "encoding/json".
Another thing I need was struct in which will be my json respone parsed. Following syntax is example for Ghost API for posts.
1type Response struct {
2 Posts []Post `json: "posts"`
3}
4
5type Post struct {
6 Id string `json: "id"`
7 Title string `json: "title"`
8 Slug string `json: "slug"`
9 Excerpt string `json: "excerpt"`
10 Html string `json: "html"`
11}
and define new variable in main function var responseObject Response
next i add unmarshall after response which will parse json string to my object syntax for it is as follows:
1json.Unmarshal(responseData, &responseObject)
Now you can go trough array of object.
1for _, post := range responseObject.Posts {
2 fmt.Println("Id:", post.Id, "with title:", post.Title, "slug:", post.Slug)
3}
Complete example is here:
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "io/ioutil"
7 "log"
8 "net/http"
9 "os"
10)
11
12type Response struct {
13 Posts []Post `json: "posts"`
14}
15
16type Post struct {
17 Id string `json: "id"`
18 Title string `json: "title"`
19 Slug string `json: "slug"`
20 Excerpt string `json: "excerpt"`
21 Html string `json: "html"`
22}
23
24func main() {
25 var endpoint = "http://your-addres.domain/api/endpoint"
26 var responseObject Response
27
28 response, err := http.Get(endpoint)
29
30 if err != nil {
31 fmt.Print(err.Error())
32 os.Exit(1)
33 }
34
35 responseData, err := ioutil.ReadAll(response.Body)
36 if err != nil {
37 log.Fatal(err)
38 }
39 // fmt.Println(string(responseData))
40
41 json.Unmarshal(responseData, &responseObject)
42
43 for _, post := range responseObject.Posts {
44 fmt.Println("Id:", post.Id, "with title:", post.Title, "slug:", post.Slug)
45 }
46}
Thank You for reading.