-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcserverforpg.go
98 lines (80 loc) · 1.45 KB
/
rpcserverforpg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
"net"
"net/http"
"net/rpc"
"strings"
)
const (
host = "localhost"
port = 5432
user = "hailan"
password = ""
dbname = "hailan"
)
type RequestPG struct{
SQL string
Count int
}
type ResultPG struct{
Result string
}
type PGX struct{
}
func (c *PGX)Require(args *RequestPG,reply *ResultPG)error{
log.Println(args.SQL)
reply.Result = query(args.SQL,args.Count)
return nil
}
func query(sqlStmt string,columnCount int)string{
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
log.Println(columnCount)
sqlStatement := sqlStmt
row,_:=db.Query(sqlStatement)
result := ""
count :=0
for row.Next(){
if count>0 {
result+=","
}
var resTemp = make([]interface{},columnCount)
var res = make([]string,columnCount)
for i:=0;i<columnCount ;i++ {
resTemp[i]=&res[i]
}
for i:=0;i< len(res);i++ {
row.Scan(resTemp...)
}
tempS:=strings.Join(res,"#")
result+=tempS
log.Println(res)
count++
}
return result
}
func main(){
pgx := new(PGX)
rpc.Register(pgx)
rpc.HandleHTTP()
l,e:=net.Listen("tcp","0.0.0.0:5434")
if e!=nil {
log.Println(e)
}
http.Serve(l,nil)
//log.Println(query("select a3 from test",1))
}