Skip to content

Instantly share code, notes, and snippets.

@me2resh
Last active September 26, 2019 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save me2resh/4c8a22f43bd06bb6857c00542f59d78d to your computer and use it in GitHub Desktop.
Save me2resh/4c8a22f43bd06bb6857c00542f59d78d to your computer and use it in GitHub Desktop.
Getting Service Struct by a JSON field
// Demo link https://play.golang.org/p/J-n45Ddk_Mf
package main
import (
"encoding/json"
"fmt"
)
type ServiceTypeHelper struct {
ServiceType string
}
// The interface will have all the methods we need to inherit
type ServiceInterface interface {
Save()
}
// This function can be generated from different entities https://blog.golang.org/generate
func getServiceByType(serviceType string) ServiceInterface {
switch serviceType {
case "ServiceA":
var sa ServiceA
return &sa
case "ServiceB":
var sb ServiceB
return &sb
}
return nil
}
type ServiceA struct {}
func (A *ServiceA) Save(){
fmt.Println("Saving Service A")
}
type ServiceB struct {}
func (B *ServiceB) Save(){
fmt.Println("Saving Service B")
}
func GetService(payload string) (ServiceInterface, error) {
var rh ServiceTypeHelper
json.Unmarshal([]byte(payload), &rh)
parsedStruct := getServiceByType(rh.ServiceType)
err := json.Unmarshal([]byte(payload), &parsedStruct)
if err != nil {
fmt.Println(err)
}
return parsedStruct, nil
}
var sample1 = `{
"serviceType":"ServiceA"
}`
var sample2 = `{
"serviceType":"ServiceB"
}`
func main() {
r, _ := GetService(sample1)
r.Save()
r, _ = GetService(sample2)
r.Save()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment