In my database, each row corresponds to a struct
type datum struct{
Id *string `json:"task_id"`
Status *string `json:"status"`
AccountId *string `json:"account_id"`
.... // many more fields, all of pointer types
}
On the webpage, the user can query on several fields of datum (say account_id
and status
). The server will return all data that satisfy the query with a projection of the fields (say Id
, account_id
and status
).
Right now, I wrote a HTTP handler to
Extract the query as a datum object from the request:
body, err := ioutil.ReadAll(r.Body)
condition := datum{}
err = json.Unmarshal(body, &condition)
Use the partially filled datum object to query the database, only the non-nil fields translate to SELECT ... WHERE ..=..
. The query result is saved in query_result []datum
Write the query_result
into json object for reply:
reply := map[string]interface{}{
"reply": query_result,
}
data, err := json.Marshal(reply)
The problem is that in the reply many of the fields are nil, but I still send them, which is wasteful. On the other hand, I don't want to change the datum struct to include omitempty
tag because in the database a value entry has all fields non-nil.
- In this case, shall I define a new struct just for the reply? Is there a way to define this new struct using
datum
struct, instead of hard code one? - Is there a better design for this query feature?