I recently got interested in Go and wrote a database server which uses a binary tree for data storage for fun. As I have no prior experience in Go, I'd like to gather a bit feedback on my code and would like to know how I can improve/optimize it.
File: BinaryTree.go
package BinaryTree
//import "fmt"
type SearchTree struct {
value *int
left, right *SearchTree
}
func (r SearchTree) getNode(i int) *SearchTree {
if r.value != nil && *r.value == i {
return &r
}
if r.left != nil {
ref := r.left.getNode(i)
if ref != nil {
return ref
}
}
if r.right != nil {
ref := r.right.getNode(i)
if ref != nil {
return ref
}
}
return nil
}
func (r SearchTree) Contains(n int) bool {
node := r.getNode(n)
return node != nil
}
func (r *SearchTree) Add(n int) {
pointer := r
for {
if pointer.value == nil {
pointer.value = &n
return
}
if *pointer.value == n {
return
} else if *pointer.value < n {
if pointer.left != nil {
pointer = pointer.left
} else {
pointer.left = &SearchTree{&n, nil, nil}
return
}
} else {
if pointer.right != nil {
pointer = pointer.right
} else {
pointer.right = &SearchTree{&n, nil, nil}
return
}
}
}
}
File: server.go
package main
import (
"fmt"
"net"
"log"
"BinaryTree"
"strconv"
)
var data BinaryTree.SearchTree
func generateAddr() *net.TCPAddr {
addr, err := net.ResolveTCPAddr("tcp", "localhost:19800")
if err != nil {
log.Fatal(err)
}
return addr
}
func handleConnection(con net.Conn) {
fmt.Println("handling connection")
buffer := make([]byte, 256)
for {
numBytes, err := con.Read(buffer)
if err != nil {
con.Close()
return
}
cmdTxt := string(buffer[:numBytes])
n, err := strconv.Atoi(cmdTxt[1:numBytes])
if err == nil {
fmt.Println(n)
switch (cmdTxt[0]) {
case 'g':
if data.Contains(n) {
con.Write([]byte{6})
} else {
con.Write([]byte{25})
}
case 's':
data.Add(n)
con.Write([]byte{6})
}
}
}
}
func startServer() {
ln, err := net.ListenTCP("tcp", generateAddr())
if err != nil {
log.Fatal(err)
}
for {
fmt.Println("wait for connection")
conn, err := ln.Accept()
if err == nil {
go handleConnection(conn)
}
}
}
func main() {
startServer()
}