S
S
Sergey2017-08-27 21:17:52
go
Sergey, 2017-08-27 21:17:52

Doesn't process POST INSERT request to database?

Doesn't process POST request returns an error

package main

import (
  "fmt"
  "database/sql"
  _ "github.com/go-sql-driver/mysql"
  "net/http"
  "github.com/julienschmidt/httprouter"
  "encoding/json"
)
var(
username string
db *sql.DB
err error
)
//PanicOnErr panics on error
func PanicOnErr(err error) {
  if err != nil {
    panic(err)
  }
}
////чтобы нормально отдавать JSON ответ
type Record struct {
  Name  string `json:"name"`
}
func insert_user(name string) (sql.Result, error) {
  return db.Exec("INSERT INTO directory (username, domain_id,cache) VALUES ($1,1,0)",
    name)
}
func addRecord(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  var rec Record
  err := json.NewDecoder(r.Body).Decode(&rec)
  if err != nil || rec.Name == ""  {
    w.WriteHeader(400)
    return
  }
  if _, err := insert_user(rec.Name); err != nil {
    w.WriteHeader(500)
    return
  }
  w.WriteHeader(201)
}
func main() {
  // Create the database handle, confirm driver is present
  db, _ = sql.Open("mysql", "root:[email protected](127.0.0.1:3306)/freeswitch")
  defer db.Close()
  // Connect and check the server version
  var version string
  db.QueryRow("SELECT VERSION()").Scan(&version)
  fmt.Println("Connected to:", version)
  // проверяем что подключение реально произошло ( делаем запрос )
  err = db.Ping()
  PanicOnErr(err) ///проверяю коннект
  defer db.Close()
  rows, err := db.Query("SELECT username FROM directory WHERE id = '1'")
  PanicOnErr(err)
  for rows.Next() {
    var username string
    err = rows.Scan(&username)
    PanicOnErr(err)
    fmt.Println("rows.Next USERNAME: ", username)
  }
  rows.Close()
  router := httprouter.New()
  go router.POST("/api/user", addRecord)
  http.ListenAndServe(":8090", router)
}

At the same time I receive
[[email protected] ~]# curl -i http://localhost:8090/api/user   -d '{"name":"5874"}'
HTTP/1.1 500 Internal Server Error
Date: Sun, 27 Aug 2017 18:10:14 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8

But at the same time, there is a connection to the database and I receive data
5758ddef2250461c998284b1a4fc6513.PNG

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
S
Sergey, 2017-08-27
@Kle6800

Error in syntax so correct
row := db.QueryRow("SELECT id FROM directory WHERE id = ?", id)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question