Carson Wright
Carson Wright

Reputation: 323

Having trouble getting a string out of my pgx query using row_to_json in sql in golang

Is there a way to get back a string from a pgx query if you use row_to_json etc. to format the returned rows as json text?

func handler(w http.ResponseWriter, r *http.Request) {
    rows, err := DB.Query("select row_to_json(rows) as data from (select * from userinfo) rows;")

    w.Header().Set("Content-Type", "application/json")
    w.Write(rows)
}

Upvotes: 1

Views: 2080

Answers (1)

Adam
Adam

Reputation: 3288

Ok, here's what I did. I ended up using QueryRow instead of Query because I'm only expecting one json result. I then use row.Scan() to get the result into a string and then w.Write([]byte(result)) to write the resulting string to the response.

If you have multiple rows in your result, you might need to handle the result differently. Possibly this might help?

func handler(w http.ResponseWriter, r *http.Request) {
    var result string
    err := postgresConn.QueryRow(`My SQL Query`).Scan(&result)
    switch {
    case err == sql.ErrNoRows:
        log.Printf("No user with that ID.")
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{}"))
    case err != nil:
        log.Println(err)
        w.WriteHeader(http.StatusInternalServerError)
    default:
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(result))
    }
}

Upvotes: 1

Related Questions