To implement CRUD operations in Go, we need to first create a new struct that represents our Ad model:
main.go111 chars6 lines
We'll also need to create a database connection and define the necessary SQL queries. Here's an example for a PostgreSQL connection:
main.go362 chars21 lines
With the database connection and queries set up, we can begin implementing the CRUD operations. For getting a list of all ads, we'll define a function getAllAds()
:
main.go443 chars22 lines
Here, we query the database using selectAllQuery
and scan the results into an array of Ad
structs. If an error occurs at any point, we return nil
and the error to the calling function.
To expose this functionality as a REST API, we can define a new HTTP handler:
main.go319 chars15 lines
Here, we call getAllAds()
and encode the results as JSON to return to the client.
We can then register this handler with our router and start listening for HTTP requests:
main.go188 chars12 lines
Now, navigating to http://localhost:8080/ads
in a web browser or making a GET request to that URL using a tool like cURL or Postman will return a list of all ads in our database as a JSON array.
gistlibby LogSnag