Answer the question
In order to leave comments, you need to log in
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)
}
[[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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question