S
S
Sergey2017-08-24 01:12:16
go
Sergey, 2017-08-24 01:12:16

Question about the "bufio" package?

Can you tell me how to make it written to the database in one line

package main

import (
  "fmt"
  "net"
  "bufio"
  "time"
  "database/sql"  ///пакет для работы с БД
  _ "github.com/lib/pq" //пакет для работы с БД
)
const (
  DB_HOST		        = "127.0.0.1"
  DB_USER    	        = "postgres"
  DB_PASSWORD 	    = "postgres"
  DB_NAME     	    = "freeswitch"
)
var (
  err error
  db *sql.DB  /// для работы с запросами в БД
)
func init() {
  start := time.Now()
  fmt.Println("Демон Стартовал:",start)
}
func main() {
  // Bind на порт ОС
  listener, _ := net.Listen("tcp", ":9000")
  db_property := "host=" + DB_HOST + " user=" + DB_USER + " password=" + DB_PASSWORD + " dbname=" + DB_NAME + " sslmode=disable"
  db, err = sql.Open("postgres", db_property)
  err = db.Ping()
  defer db.Close() ///закрываем коннект к Базе данных

  for {
    // ждём пока не придёт клиент
    conn, err := listener.Accept()

    if err != nil {
      fmt.Println("Can not connect!!")
      conn.Close()
      continue
    }

    fmt.Println("Connected")

    // создаём Reader для чтения информации из сокета
    bufReader := bufio.NewReader(conn)
    fmt.Println("Start reading")
    go func(conn net.Conn) {
      //defer conn.Close()

      for {
        // побайтово читаем
        rbyte, err := bufReader.ReadByte()

        if err != nil {
          fmt.Println("Can not read!", err)
          break
        }

        fmt.Print(string(rbyte))
        data := string(rbyte)
        ip := conn.RemoteAddr().String()
        start_db := time.Now()
        _, err = db.Exec("INSERT INTO smpp (sms,state,ip,time) VALUES ($1, 'active' , $2, $3 )", data,ip,start_db)  // Метод db.Exec() применяется, когда нужно сделать однократное обращение к базе, не требующее возврата данных.
      }
    }(conn)
  }
}

In this form, it arrives at port
7812587512gsggsgsag>7812587512gsggsgsag>7812587512gsggsgsag>7812587512gsggsgsag>7812587512gsggsgsag>7812587512gsggsgsag>7812587512gsggsgsag
In the database it is written as
d244851bd4cc48e5830db6e746b9b251.PNG

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-08-24
@Kle6800

Maybe it's more convenient for you to read in lines, and not in bytes? bufio.Reader has a nice ReadString method that reads up to the specified delimiter.
line, err := bufReader.ReadString('\n')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question