Reputation: 13
I'm writing a backend for a project, the backend receives the user data through a POST request encoded in the request body as json.
I have two structures:
struct to store user data during new account creation:
type User struct {
Guid string ``
Name string `json:"Name"`
Pass string `json:"Pass"`
Username string `json:"Username"`
Email string `json:"Email"`
Phone string `json:"Phone"`
Country string `json:"Country"`
}
struct to store signin data
type Signin struct {
Username string `json:"Username"`
Pass string `json:"Pass"`
}
and a json decoder function (to decode the data from the request body):
func extractAndAssignInfo(req *http.Request, dataStruct interface{}) interface{}{
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&dataStruct)
if err != nil {
log.Fatal(err)
}
return reflect.ValueOf(dataStruct).Interface()
}
Is there a way to have the extractAndAssignInfo()
function to return the struct?
Since the Guid is calculated using a different function, when I try to do
userdata := ExtractAndAssignInfo(req, User{})
The return value of the function gives a type of map[string]interface {}
, if I change the return type to a struct then it won't be a "general purpose" function that can decode and return the required struct.
I'm not sure if this is the best approach to solving it. I would also appreciate any other way I can reuse that same function while returning a struct.
Upvotes: 1
Views: 1521
Reputation: 120951
Use this function:
func extractAndAssignInfo(req *http.Request, v interface{}) {
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(v)
if err != nil {
log.Fatal(err)
}
}
Call it like this to decode the request to a User
:
var userData User
extractAndAssignInfo(req, &userData)
and like this to decode to a Signin
:
var signin Signin
extractAndAssignInfo(req, &signin)
Side node: It's not a good idea to exit the process on bad request data. Consider returning an error extractAndAssignInfo
instead of calling log.Fatal
.
Upvotes: 2