refactoring yo

master
Jordan Orelli 10 years ago
parent 9539eaf043
commit 24c2a2aec2

@ -98,6 +98,7 @@ func (c *Client) err(template string, args ...interface{}) {
func (c *Client) run() { func (c *Client) run() {
go c.term() go c.term()
if err := c.dial(); err != nil { if err := c.dial(); err != nil {
exit(1, "%v", err) exit(1, "%v", err)
} }

@ -3,37 +3,67 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"net" "net"
) )
func authConnection(conn net.Conn) error { func stream(r io.Reader, c chan Envelope, e chan error, done chan interface{}) {
var raw json.RawMessage defer close(done)
d := json.NewDecoder(conn) decoder := json.NewDecoder(r)
if err := d.Decode(&raw); err != nil {
return fmt.Errorf("unable to decode client request: %v", err)
}
var env Envelope var env Envelope
if err := json.Unmarshal(raw, &env); err != nil { for {
return fmt.Errorf("man, fuck all this. %v", err) err := decoder.Decode(&env)
switch err {
case io.EOF:
return
case nil:
c <- env
default:
e <- err
} }
switch env.Kind { }
case "auth": }
func handleAuthRequest(conn net.Conn, body json.RawMessage) error {
var auth Auth var auth Auth
if err := json.Unmarshal(env.Body, &auth); err != nil { if err := json.Unmarshal(body, &auth); err != nil {
return fmt.Errorf("unable to decode auth body: %v", err) return fmt.Errorf("bad auth request: %v", err)
} }
info_log.Printf("authenticated user %s", auth.Nick) info_log.Printf("authenticated user %s", auth.Nick)
}
return nil return nil
} }
func handleRequest(conn net.Conn, request Envelope) error {
switch request.Kind {
case "auth":
return handleAuthRequest(conn, request.Body)
default:
return fmt.Errorf("no such request type: %v", request.Kind)
}
}
func handleConnection(conn net.Conn) { func handleConnection(conn net.Conn) {
defer func() { defer func() {
conn.Close() conn.Close()
info_log.Printf("connection ended: %v", conn.RemoteAddr()) info_log.Printf("connection ended: %v", conn.RemoteAddr())
}() }()
info_log.Printf("connection start: %v", conn.RemoteAddr()) info_log.Printf("connection start: %v", conn.RemoteAddr())
authConnection(conn) requests := make(chan Envelope)
errors := make(chan error)
done := make(chan interface{})
go stream(conn, requests, errors, done)
for {
select {
case request := <-requests:
if err := handleRequest(conn, request); err != nil {
error_log.Printf("client error: %v", err)
}
case err := <-errors:
error_log.Printf("connection error: %v", err)
case <-done:
return
}
}
} }
func serve() { func serve() {

Loading…
Cancel
Save