package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" ) func newQuery(w http.ResponseWriter, req *http.Request) { body, err := ioutil.ReadAll(req.Body) if err != nil { panic(err) } log.Println(string(body)) var query Query err = json.Unmarshal(body, &query) if err != nil { panic(err) } tx, err := db.Begin() if err != nil { log.Fatal(err) } defer tx.Rollback() stmt, err := tx.Prepare("INSERT INTO queries (startdate, enddate, location, description, contactperson, contactno, email, status, questiondate) VALUES" + "( $1, $2, $3, $4, $5, $6, $7, $8, $9);") if err != nil { log.Fatal(err) } defer stmt.Close() // danger! for i := 0; i < 1; i++ { _, err = stmt.Exec(query.Startdate, query.Enddate, query.Location, query.Description, query.Contactperson, query.Contactno, query.Email, query.Status, query.Questiondate) if err != nil { log.Fatal(err) } } err = tx.Commit() if err != nil { log.Fatal(err) } } func getQueryList(w http.ResponseWriter, r *http.Request) { enableCors(&w) queryList := []Query{} stmt, err := db.Prepare("SELECT * FROM queries ORDER BY questiondate DESC") if err != nil { http.Error(w, "błąd zapisu danych", 500) return } defer stmt.Close() rows, err := stmt.Query() if err != nil { http.Error(w, "błąd zapisu danych", 500) return } defer rows.Close() for rows.Next() { query := Query{} err = rows.Scan( &query.Id, &query.Startdate, &query.Enddate, &query.Location, &query.Description, &query.Contactperson, &query.Contactno, &query.Email, &query.Status, &query.Questiondate, ) if err != nil { http.Error(w, "błąd zapisu danych", 500) return } queryList = append(queryList, query) } if err = rows.Err(); err != nil { http.Error(w, "błąd danych", 500) return } out, err := json.Marshal(queryList) if err != nil { http.Error(w, err.Error(), 500) return } fmt.Fprint(w, string(out)) }