How to send raw JSON sql result?

I have query from postgres:

select json_strip_nulls(json_agg(x)) from (select * from events) x;

it return json ready one string row result something like this:

[{“id”:1,“date”:“2016-02-15”}, {“id”:2,“date”:“2016-02-15”}, {“id”:1,“date”:“2016-02-15”}]

and I need to return this from handler to client

func EventsHandler(rw http.ResponseWriter, r *http.Request) {
	 var query = `select json_strip_nulls(json_agg(x)) from (select * from events) x;`    
    db, err := sql.Open("postgres", conString)
	if err != nil {
		log.Fatal(err)
	}
    
    rows, err := db.Query(query)
    if err != nil {
        fmt.Println("select error")
        log.Fatal(err)
    }
       
  //??
}

how I could make it without struct and models?
thank you!

The following snippet should be enough:

w.Header().Set("Content-Type", "application/json")
io.WriteString(w, query)

You can check the example on docs: https://golang.org/pkg/net/http/#ResponseWriter.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.