Generic Get Rest function

Hi,

Problem. I have a rest service with a huge number of endpoints and I’ve been re-using code again and again.

How can I write a generic GET function, present it with the required object Type and have the function unmarshal the response and return the result as the correct Type

I really don’t know how to do this atm, but I would certainly be prepared to spend time trying to figure it out, if someone could give me a pointer to get started.

Thanks

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"encoding/json"
)

var Client *http.Client

type Car struct {
	Name string
	Colour string
	EngineSize int
}

type Fruit struct {
	Name string
	Calories int
	Seedless bool
}

func Main() {
	car := Car{}

	url := "/blah/blah/cars"
	respJson, err := getIt(url, &car)
	fmt.Println(respJson.Colour)

	url = "/blah/blah/fruits"
	fruit := Fruit{}
	respJson, err = getIt(url, &fruit)
	fmt.Println(respJson.Seedless)
}

func getIt(urlStr string, i interface{}) (interface{}, error) {
		req, _ := http.NewRequest("GET", urlStr, nil)
		req.Header.Add("Accept", "application/json")

		resp, err := Client.Do(req)
		if err != nil {
			return nil, fmt.Errorf("er......")
		}
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, fmt.Errorf("er......")
		}
		err = json.Unmarshal(body, &i)
		if err != nil {
			return nil, fmt.Errorf("can't unmarshal response......")
		}
		return  &i , nil
}

I have tried to do this by creating an API with some success. I have asked for some feedback here, but I did not get any response. Read more about my attempt here.

@mje . Thanks I’ll take a look

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