door_daemon_go cleanups
authorOthmar Gsenger <otti@realraum.at>
Thu, 7 Mar 2013 21:52:34 +0000 (21:52 +0000)
committerOthmar Gsenger <otti@realraum.at>
Thu, 7 Mar 2013 21:52:34 +0000 (21:52 +0000)
door_daemon_go/unix_socket_server.go

index aca60b8..a2e710a 100644 (file)
@@ -3,47 +3,51 @@ import "fmt"
 import "net"
 import "bufio"
 
+func readLineSafe(rw *bufio.ReadWriter) (string, error) {
+  wasPrefix:=false
+  var line string
+  for isPrefix:=true;isPrefix; {
+    var lineBuf []byte 
+    var err error
+    lineBuf,isPrefix,err = rw.ReadLine()
+    if err != nil {
+        return "",err
+    }
+    if isPrefix {
+      wasPrefix=true
+    } else {
+      line=string(lineBuf)
+    }
+  }
+  if wasPrefix {
+      fmt.Println("line too long")
+      fmt.Fprintf(rw,"line too long\n")
+      rw.Flush()
+      return "",nil
+  }
+  return line,nil
+}
+
+func connToReadWriter(c net.Conn) (*bufio.ReadWriter) {
+    client_r := bufio.NewReaderSize(c,14)
+    client_w := bufio.NewWriterSize(c,14)
+    return bufio.NewReadWriter(client_r,client_w)
+}
+
 func handleConnection(c net.Conn) () {
+    client:=connToReadWriter(c)
     fmt.Println("new connection")
-    var client *bufio.ReadWriter;
-    {
-      client_r := bufio.NewReaderSize(c,14)
-      client_w := bufio.NewWriterSize(c,14)
-      client = bufio.NewReadWriter(client_r,client_w)
-    }
     for {
-          wasPrefix:=false
-          var line string
-          for isPrefix:=true;isPrefix; {
-            var lineBuf []byte 
-            var err error
-            lineBuf,isPrefix,err = client.ReadLine()
-            if err != nil {
-                fmt.Printf("Readline Error: %s\n",err.Error())
-                c.Close()
-                return
-            }
-            if isPrefix {
-              wasPrefix=true
-            } else {
-              line=string(lineBuf)
-            }
-          }
-          if wasPrefix {
-              fmt.Println("line too long")
-              fmt.Fprintf(client,"line too long\n")
-              client.Flush()
-              continue
-          }
-          fmt.Printf("Received: %v\n", string(line))
-//
-//        data := buf[0:nr]
-//        fmt.Printf("Received: %v", string(data))
-//        _, err = c.Write(data)
-//        if err != nil {
-//            fmt.Println("Write: " + err.Error())
-//            return
-//        }
+         line,err:=readLineSafe(client)
+         if err != nil {
+          fmt.Println(err.Error())
+          c.Close()
+          return
+         }
+         if line == "" {
+           continue
+         }
+         fmt.Printf("Received: %v\n", string(line))
     }
 }