Last active
September 26, 2019 16:51
-
-
Save me2resh/4c8a22f43bd06bb6857c00542f59d78d to your computer and use it in GitHub Desktop.
Getting Service Struct by a JSON field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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