write a crud operations to get a list of ads in go

To implement CRUD operations in Go, we need to first create a new struct that represents our Ad model:

main.go
type Ad struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
    Text  string `json:"text"`
}
111 chars
6 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.go
import (
    "database/sql"
    "log"

    _ "github.com/lib/pq"
)

func dbConnect() *sql.DB {
    db, err := sql.Open("postgres", "postgres://user:password@localhost/ads_db?sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }
    return db
}

var db = dbConnect()

const (
    selectAllQuery = "SELECT id, title, text FROM ads ORDER BY id DESC"
)
362 chars
21 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.go
func getAllAds() ([]Ad, error) {
    rows, err := db.Query(selectAllQuery)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    var ads []Ad
    for rows.Next() {
        var ad Ad
        if err := rows.Scan(&ad.ID, &ad.Title, &ad.Text); err != nil {
            return nil, err
        }
        ads = append(ads, ad)
    }
    if err := rows.Err(); err != nil {
        return nil, err
    }

    return ads, nil
}
443 chars
22 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.go
import (
    "net/http"
)

func handleGetAllAds(w http.ResponseWriter, r *http.Request) {
    ads, err := getAllAds()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(ads)
}
319 chars
15 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.go
import (
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    r.HandleFunc("/ads", handleGetAllAds).Methods("GET")

    log.Fatal(http.ListenAndServe(":8080", r))
}
188 chars
12 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