I'm creating a rest api in golang
and making a POST
request into a table.
For this I've created a struct. Basically the vars in struct is same as the columns in table named users
.
and written a function to make a POST
request. And the code is working fine, the params while making POST request is being inserted successfully in the table.
type User struct {
ID int
Name string
Lname string
Country string
}
func insertUser(response http.ResponseWriter, request *http.Request)
{
var userDetails User
decoder := json.NewDecoder(request.Body)
err := decoder.Decode(&userDetails)
defer request.Body.Close()
if err != nil {
returnErrorResponse(response,request, httpError)
} else {
httpError.Code = http.StatusBadRequest
if userDetails.Name == "" {
httpError.Message = "first name can't be empty"
returnErrorResponse(response, request, httpError)
} else if userDetails.Lname == "" {
httpError.Message = "Last name can't be empty"
returnErrorResponse(response, request, httpError)
} else {
isInserted := insertUserInDB(userDetails)
if isInserted {
getAllUsers(response, request)
} else {
returnErrorResponse(response, request, httpError)
}
}
}
}
Here is insertUserInDB(userDetails)
definition
func insertUserInDB(userDetails User) bool {
stmt, err := db.Prepare("insert into users set Name=?, Lname=?,
Country=?")
if err != nil {
fmt.Print("helper_methods.go : 118")
fmt.Println(err)
return false
}
_, queryError := stmt.Exec(tableName, userDetails.Name,
userDetails.Lname, userDetails.Country)
if queryError != nil {
fmt.Print("helper_methods.go : 125")
fmt.Println(queryError)
return false
}
return true
}
Is there any way to write a common function to insert record in any of the table in the DB?
Can we create struct dynamically, or any other way?
Please help me out here.
Like in other languages, you can use an ORM library to do the DB translation for you, for example GORM, or you can do the translation yourself. Since you already implemented saving the data manually, see this article for how to retrieve data manually.
If you just want to write a generic method that generates/executes SQL queries by matching struct field names you can use the reflect package of go. You will have to identify the structs fields by using reflect.TypeOf()
to get the Type of your passed variable and then iterate over the StructField
that you can get by using the Field()
method on the Type. The StructField
will reveal the Name
and ValueOf()
will allow you to access the Value. Name and value can then be used to construct the query. For getting a better understanding I recommend you read some articles on reflect. Like this and this.