在Go语言中,使用JSON编码时无法获取正确的数据。

huangapple go评论135阅读模式
英文:

Not getting proper data using json encoding for a structure in go language

问题

//package cluster
package main

import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"math/rand"
"net"
"os"
"strconv"
"time"
//"bytes"
)

const (
BROADCAST = -1
)

var outbox, inbox chan *Envelope
var pids [10]int
var ips [10]string

type Envelope struct {
Pid int
MsgId int64
Msg interface{}
}

type Server interface {
Pid() int
Peers() []int
Outbox() chan *Envelope
Inbox() chan *Envelope
}

/*
func (envelope Envelope) Pid() int {
return envelope.MsgId
}
*/
var server Envelope

func (envelope Envelope) Peers() []int {
return nil //pids
}

func (envelope Envelope) Outbox() chan *Envelope {
return outbox
}

func (envelope Envelope) Inbox() chan *Envelope {
return inbox
}

func server_() {
// listen on a port
ln, err := net.Listen("tcp", ":9999")
//time.Sleep(time.Second * 2)
if err != nil {
fmt.Println(err)
return
}
for {
c, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
} else {
fmt.Println("handle")
go handleServerConnection(c)
}
}
}

func handleServerConnection(c net.Conn) {
// receive the message
var msg Envelope
var b []byte
// for{
c.Read(b)
/*
if b == nil{
continue
}else{
break
}
*/
// }

  1. fmt.Println(b)
  2. err := json.Unmarshal(b, &msg)
  3. if err != nil { //ERORR !!!!
  4. fmt.Println(err)
  5. } else {
  6. fmt.Println("Received : %+v", msg)
  7. }
  8. c.Close()

}

func client() {
// connect to the server
for msg := range outbox {
c, err := net.Dial("tcp", "127.0.0.1:9999")
if err != nil {
fmt.Println(err)
return
}

  1. if err != nil {
  2. fmt.Println("error encoding the response to a join request")
  3. fmt.Println(err)
  4. }
  5. b, _ := json.Marshal(msg)
  6. fmt.Printf("the json: %s\n", b)
  7. c.Write(b)
  8. c.Close()
  9. }
  10. time.Sleep(time.Second * 2)

}

func New(myPid int, ConFile string) Envelope {
inbox = make(chan *Envelope, 100)
outbox = make(chan *Envelope, 100)
file, err := os.Open(ConFile)
if err != nil {
fmt.Println("Error:", err)
}
defer file.Close()
reader := csv.NewReader(file)

  1. i := 0
  2. j := 0
  3. for {
  4. record, err := reader.Read()
  5. if err == io.EOF {
  6. break
  7. } else if err != nil {
  8. fmt.Println("Error:", err)
  9. }
  10. x, _ := strconv.Atoi(record[0])
  11. pids[i] = x
  12. i++
  13. ips[j] = record[1]
  14. j++
  15. }
  16. fmt.Println("\n", ips)
  17. fmt.Println("\n", pids)
  18. MsgId := rand.Int63n(0x10000000)
  19. server = Envelope{Pid: myPid, MsgId: MsgId, Msg: "Hello World :)"}
  20. go server_()
  21. go client()
  22. var input string
  23. fmt.Println("\n\nPress enter ---\n\n")
  24. fmt.Scanln(&input)
  25. return server

}

func main() {
//for i := 1; i < 10; i++ {
server := New(12, "config.txt")

  1. server.Outbox() <- &Envelope{Pid: BROADCAST, MsgId: server.MsgId, Msg: "hello there"}
  2. select {
  3. case envelope := <-server.Inbox():
  4. fmt.Printf("Received msg from %d: '%s'\n", envelope.Pid, envelope.Msg)
  5. case <-time.After(2 * time.Second):
  6. println("Waited and waited. Ab thak gaya\n")
  7. }
  8. //fmt.Println(server.Pid, server.MsgId, server.Msg )
  9. //}

}

英文:
  1. //package cluster
  2. package main
  3. import (
  4. &quot;encoding/csv&quot;
  5. &quot;encoding/json&quot;
  6. &quot;fmt&quot;
  7. &quot;io&quot;
  8. &quot;math/rand&quot;
  9. &quot;net&quot;
  10. &quot;os&quot;
  11. &quot;strconv&quot;
  12. &quot;time&quot;
  13. //&quot;bytes&quot;
  14. )
  15. const (
  16. BROADCAST = -1
  17. )
  18. var outbox, inbox chan *Envelope
  19. var pids [10]int
  20. var ips [10]string
  21. type Envelope struct {
  22. Pid int
  23. MsgId int64
  24. Msg interface{}
  25. }
  26. type Server interface {
  27. Pid() int
  28. Peers() []int
  29. Outbox() chan *Envelope
  30. Inbox() chan *Envelope
  31. }
  32. /*
  33. func (envelope Envelope) Pid() int {
  34. return envelope.MsgId
  35. }
  36. */
  37. var server Envelope
  38. func (envelope Envelope) Peers() []int {
  39. return nil //pids
  40. }
  41. func (envelope Envelope) Outbox() chan *Envelope {
  42. return outbox
  43. }
  44. func (envelope Envelope) Inbox() chan *Envelope {
  45. return inbox
  46. }
  47. func server_() {
  48. // listen on a port
  49. ln, err := net.Listen(&quot;tcp&quot;, &quot;:9999&quot;)
  50. //time.Sleep(time.Second * 2)
  51. if err != nil {
  52. fmt.Println(err)
  53. return
  54. }
  55. for {
  56. c, err := ln.Accept()
  57. if err != nil {
  58. fmt.Println(err)
  59. continue
  60. } else {
  61. fmt.Println(&quot;handle&quot;)
  62. go handleServerConnection(c)
  63. }
  64. }
  65. }
  66. func handleServerConnection(c net.Conn) {
  67. // receive the message
  68. var msg Envelope
  69. var b []byte
  70. // for{
  71. c.Read(b)
  72. /*
  73. if b == nil{
  74. continue
  75. }else{
  76. break
  77. }
  78. */
  79. // }
  80. fmt.Println(b)
  81. err := json.Unmarshal(b, &amp;msg)
  82. if err != nil { //ERORR !!!!
  83. fmt.Println(err)
  84. } else {
  85. fmt.Println(&quot;Received : %+v&quot;, msg)
  86. }
  87. c.Close()
  88. }
  89. func client() {
  90. // connect to the server
  91. for msg := range outbox {
  92. c, err := net.Dial(&quot;tcp&quot;, &quot;127.0.0.1:9999&quot;)
  93. if err != nil {
  94. fmt.Println(err)
  95. return
  96. }
  97. if err != nil {
  98. fmt.Println(&quot;error encoding the response to a join request&quot;)
  99. fmt.Println(err)
  100. }
  101. b, _ := json.Marshal(msg)
  102. fmt.Printf(&quot;the json: %s\n&quot;, b)
  103. c.Write(b)
  104. c.Close()
  105. }
  106. time.Sleep(time.Second * 2)
  107. }
  108. func New(myPid int, ConFile string) Envelope {
  109. inbox = make(chan *Envelope, 100)
  110. outbox = make(chan *Envelope, 100)
  111. file, err := os.Open(ConFile)
  112. if err != nil {
  113. fmt.Println(&quot;Error:&quot;, err)
  114. }
  115. defer file.Close()
  116. reader := csv.NewReader(file)
  117. i := 0
  118. j := 0
  119. for {
  120. record, err := reader.Read()
  121. if err == io.EOF {
  122. break
  123. } else if err != nil {
  124. fmt.Println(&quot;Error:&quot;, err)
  125. }
  126. x, _ := strconv.Atoi(record[0])
  127. pids[i] = x
  128. i++
  129. ips[j] = record[1]
  130. j++
  131. }
  132. fmt.Println(&quot;\n&quot;, ips)
  133. fmt.Println(&quot;\n&quot;, pids)
  134. MsgId := rand.Int63n(0x10000000)
  135. server = Envelope{Pid: myPid, MsgId: MsgId, Msg: &quot;Hello World :)&quot;}
  136. go server_()
  137. go client()
  138. var input string
  139. fmt.Println(&quot;\n\nPress enter ---\n\n&quot;)
  140. fmt.Scanln(&amp;input)
  141. return server
  142. }
  143. func main() {
  144. //for i := 1; i &lt;= 10; i++ {
  145. server := New(12, &quot;config.txt&quot;)
  146. server.Outbox() &lt;- &amp;Envelope{Pid: BROADCAST, MsgId: server.MsgId, Msg: &quot;hello there&quot;}
  147. select {
  148. case envelope := &lt;-server.Inbox():
  149. fmt.Printf(&quot;Received msg from %d: &#39;%s&#39;\n&quot;, envelope.Pid, envelope.Msg)
  150. case &lt;-time.After(2 * time.Second):
  151. println(&quot;Waited and waited. Ab thak gaya\n&quot;)
  152. }
  153. //fmt.Println(server.Pid, server.MsgId, server.Msg )
  154. //}
  155. }

From client function I am trying to send some data but unable to receive data in handleServerConnection()

my program is written in go language
help me out

I have referred most of the examples given in the book and stack overflow

i am getting an empty object in handleconnection function

答案1

得分: 0

你能分享一下你尝试解码的json的示例吗?我怀疑这是一个注释问题。大多数json都是小写的,因为它符合JavaScript的语法。

例如,我怀疑你的json看起来像这样:

  1. {"pid":"0", "msgId":"500", "msg":"this is the message"}

如果是这种情况,那么你的结构体需要像这样添加注释:

  1. type Envelope struct {
  2. Pid int `json:"pid"`
  3. MsgId int64 `json:"msgId"`
  4. Msg interface{} `json:"msg"`
  5. }

再次强调,没有示例的情况下,我只是猜测这可能是你的问题。

英文:

Can you share an example of the json you are trying to decode? I suspect that it is an annotations issue. Most json is lowercase due to the javascript syntax.

For instance, I suspect your json looks like this:

  1. {&quot;pid&quot;:&quot;0&quot;, &quot;msgId&quot;:&quot;500&quot;, &quot;msg&quot;:&quot;this is the message&quot;}

If that is the case, then you need annotations on your struct like this:

  1. type Envelope struct {
  2. Pid int `json:&quot;pid&quot;`
  3. MsgId int64 `json:&quot;msgId&quot;`
  4. Msg interface{} `json:&quot;msg&quot;`
  5. }

Again, without an example, I'm only guessing that this is your problem.

huangapple
  • 本文由 发表于 2014年1月27日 13:22:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/21373558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定