diff options
author | clsr <clsr@clsr.net> | 2017-08-30 14:56:11 +0200 |
---|---|---|
committer | clsr <clsr@clsr.net> | 2017-08-30 14:56:11 +0200 |
commit | ee431f1e85a8ee7d3c6e069c8858c671da1c2acd (patch) | |
tree | 2094c57eefe84efe65c57ef17dceb8215baeccaf | |
parent | 9ca364d8753a5f2c7529c5b3dd7178bfd51effc6 (diff) | |
download | cnp-go-ee431f1e85a8ee7d3c6e069c8858c671da1c2acd.tar.gz cnp-go-ee431f1e85a8ee7d3c6e069c8858c671da1c2acd.zip |
Unify error handling and clean request paths in serverv0.1.3
-rw-r--r-- | server.go | 48 |
1 files changed, 21 insertions, 27 deletions
@@ -91,7 +91,9 @@ func (srv *Server) sendError(conn net.Conn, req *Request, err Error) { if e2 != nil { srv.logError(e2) } - srv.logAccess(&responseWriter{addr: conn.RemoteAddr()}, req, er.Intent(), l) + if req != nil { + srv.logAccess(&responseWriter{addr: conn.RemoteAddr()}, req, er.Intent(), l) + } } // HandleConn reads a CNP request from conn and runs a handler to respond. @@ -99,13 +101,19 @@ func (srv *Server) HandleConn(conn net.Conn) { var rw *responseWriter var req *Request - defer func() { - /*_, err := io.Copy(ioutil.Discard, req.Body) - if err != nil { - srv.ErrorLog.Print(err) - }*/ + resp, _ := NewResponse(IntentOK, nil) + rw = &responseWriter{ + w: conn, + resp: resp, + addr: conn.RemoteAddr(), + } + + if srv.Handler == nil { + panic(errors.New("cnp.Server.Handler is nil")) + } - if rw != nil && rw.headerWritten { + defer func() { + if req != nil && rw.headerWritten { srv.logAccess(rw, req, rw.resp.Header.Intent, rw.n) } @@ -119,40 +127,26 @@ func (srv *Server) HandleConn(conn net.Conn) { if req != nil { req.Close() } + conn.Close() }() req, err := ParseRequest(conn) if err != nil { - if e, ok := err.(Error); ok { - resp, _ := NewResponse(IntentError, nil) - resp.SetParam("reason", e.CNPError()) - resp.Write(conn) - return - } panic(err) } + req.SetPath(Clean(req.Path())) req.Body = io.LimitReader(req.Body, req.Length()) if srv.Validate { - err = req.Validate() if err != nil { - srv.sendError(conn, req, err.(Error)) - return + panic(err) } } - if srv.Handler != nil { - resp, _ := NewResponse(IntentOK, nil) - rw = &responseWriter{ - w: conn, - resp: resp, - addr: conn.RemoteAddr(), - } - srv.Handler.ServeCNP(rw, req) - if !rw.headerWritten { - rw.WriteHeader() - } + srv.Handler.ServeCNP(rw, req) + if !rw.headerWritten { + rw.WriteHeader() } } |