I am searching for most efficient solution, there are a lot of ways to read data from socket and decode json. I obviously should use json.Encoder and json.Decoder, because they are suitable for streaming nature of socket, but I have specific rule to prevent socket flooding, I must close connection if there is a single message > than 5 Kb. My message structure is JSON RPC.
In the following example I can check length and apply policy:
connbuf := bufio.NewReader(conn)
msg, err := connbuf.ReadBytes('
')
if len(msg) > 5 * 1024 {
conn.Close()
}
...
var req JSONRequest
err = json.Unmarshal(message, &req)
...
But if client pushes megabytes of data without delimiter, this data will be in application, in msg variable already before server will disconnect client. Pretty vulnerable.
Second example uses Decoder, there is no chance to check size at all.
dec = json.NewDecoder(conn)
for {
var req JSONRequest
if err := dec.Decode(&req); err == io.EOF {
break
} else if err != nil {
log.Println(err.Error())
return err
}
...
}
What is the best approach you can suggest to me? Thanks.