You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.5 KiB
Go

10 years ago
package main
import (
"encoding/json"
"fmt"
10 years ago
"io"
10 years ago
"net"
)
type Envelope struct {
Id int `json:"id"`
Kind string `json:"kind"`
Body json.RawMessage `json:"body"`
10 years ago
}
type Bool bool
func (b Bool) Kind() string {
return "bool"
}
10 years ago
type request interface {
Kind() string
}
func wrapRequest(id int, r request) (*Envelope, error) {
b, err := json.Marshal(r)
if err != nil {
return nil, fmt.Errorf("unable to wrap request: %v", err)
}
return &Envelope{
Id: id,
Kind: r.Kind(),
Body: b,
}, nil
}
func writeRequest(w io.Writer, id int, r request) error {
10 years ago
b, err := json.Marshal(r)
if err != nil {
10 years ago
return fmt.Errorf("unable to marshal request: %v", err)
10 years ago
}
10 years ago
msg := json.RawMessage(b)
e := &Envelope{
Id: id,
10 years ago
Kind: r.Kind(),
10 years ago
Body: msg,
10 years ago
}
10 years ago
raw, err := json.Marshal(e)
if err != nil {
10 years ago
return fmt.Errorf("unable to marshal request envelope: %v", err)
10 years ago
}
10 years ago
if _, err := w.Write(raw); err != nil {
return fmt.Errorf("unable to write request: %v", err)
}
return nil
10 years ago
}
func decodeRequest(conn net.Conn) (request, error) {
d := json.NewDecoder(conn)
var env Envelope
if err := d.Decode(&env); err != nil {
return nil, fmt.Errorf("unable to decode client request: %v", err)
}
switch env.Kind {
case "auth":
10 years ago
var auth AuthRequest
10 years ago
if err := json.Unmarshal(env.Body, &auth); err != nil {
return nil, fmt.Errorf("unable to unmarshal auth request: %v", err)
}
return &auth, nil
default:
return nil, fmt.Errorf("unknown request type: %s", env.Kind)
}
}