Browse Source

Added DebugLevel to filter irelevant output and did some code style cleanup.

Eliezer Croitoru 6 months ago
parent
commit
60787d6a59
5 changed files with 56 additions and 47 deletions
  1. 3 2
      bridge.go
  2. 15 15
      mux.go
  3. 3 3
      request.go
  4. 4 3
      response.go
  5. 31 24
      server.go

+ 3 - 2
bridge.go

@@ -55,7 +55,7 @@ func (w *bridgedRespWriter) WriteHeader(code int) {
 	w.irw.WriteHeader(200, resp, true)
 }
 
-// Create an http.ResponseWriter that encapsulates its response in an ICAP response.
+// NewBridgedResponseWriter Create an http.ResponseWriter that encapsulates its response in an ICAP response.
 func NewBridgedResponseWriter(w ResponseWriter) http.ResponseWriter {
 	rw := new(bridgedRespWriter)
 	rw.header = make(http.Header)
@@ -64,12 +64,13 @@ func NewBridgedResponseWriter(w ResponseWriter) http.ResponseWriter {
 	return rw
 }
 
-// Pass use the local HTTP server to generate a response for an ICAP request.
+// ServeLocally Pass use the local HTTP server to generate a response for an ICAP request.
 func ServeLocally(w ResponseWriter, req *Request) {
 	brw := NewBridgedResponseWriter(w)
 	http.DefaultServeMux.ServeHTTP(brw, req.Request)
 }
 
+// ServeLocallyFromHandler ---
 func ServeLocallyFromHandler(w ResponseWriter, req *Request, mux http.Handler) {
 	brw := NewBridgedResponseWriter(w)
 	mux.ServeHTTP(brw, req.Request)

+ 15 - 15
mux.go

@@ -15,7 +15,7 @@ import (
 // It matches the URL of each incoming request against a list of registered
 // patterns and calls the handler for the pattern that
 // most closely matches the URL.
-// 
+//
 // For more details, see the documentation for http.ServeMux
 type ServeMux struct {
 	m map[string]Handler
@@ -149,14 +149,14 @@ func (rh *redirectHandler) ServeICAP(w ResponseWriter, r *Request) {
 // RedirectHandler returns a request handler that redirects
 // each request it receives to the given url using the given
 // status code.
-func RedirectHandler(url_ string, code int) Handler {
-	return &redirectHandler{url_, code}
+func RedirectHandler(redirectURL string, code int) Handler {
+	return &redirectHandler{redirectURL, code}
 }
 
 // Redirect replies to the request with a redirect to url,
 // which may be a path relative to the request path.
-func Redirect(w ResponseWriter, r *Request, url_ string, code int) {
-	if u, err := url.Parse(url_); err == nil {
+func Redirect(w ResponseWriter, r *Request, redirectURL string, code int) {
+	if u, err := url.Parse(redirectURL); err == nil {
 		// If url was relative, make absolute by
 		// combining with request path.
 		// The browser would probably do this for us,
@@ -167,27 +167,27 @@ func Redirect(w ResponseWriter, r *Request, url_ string, code int) {
 		}
 		if u.Scheme == "" {
 			// no leading icap://server
-			if url_ == "" || url_[0] != '/' {
+			if redirectURL == "" || redirectURL[0] != '/' {
 				// make relative path absolute
 				olddir, _ := path.Split(oldpath)
-				url_ = olddir + url_
+				redirectURL = olddir + redirectURL
 			}
 
 			var query string
-			if i := strings.Index(url_, "?"); i != -1 {
-				url_, query = url_[:i], url_[i:]
+			if i := strings.Index(redirectURL, "?"); i != -1 {
+				redirectURL, query = redirectURL[:i], redirectURL[i:]
 			}
 
 			// clean up but preserve trailing slash
-			trailing := url_[len(url_)-1] == '/'
-			url_ = path.Clean(url_)
-			if trailing && url_[len(url_)-1] != '/' {
-				url_ += "/"
+			trailing := redirectURL[len(redirectURL)-1] == '/'
+			redirectURL = path.Clean(redirectURL)
+			if trailing && redirectURL[len(redirectURL)-1] != '/' {
+				redirectURL += "/"
 			}
-			url_ += query
+			redirectURL += query
 		}
 	}
 
-	w.Header().Set("Location", url_)
+	w.Header().Set("Location", redirectURL)
 	w.WriteHeader(code, nil, false)
 }

+ 3 - 3
request.go

@@ -167,7 +167,7 @@ func ReadRequest(b *bufio.ReadWriter) (req *Request, err error) {
 
 	// Construct the http.Request.
 	if rawReqHdr != nil {
-		invalidUrlEscapeFixed := false
+		invalidURLEscapeFixed := false
 		req.Request, err = http.ReadRequest(bufio.NewReader(bytes.NewBuffer(rawReqHdr)))
 		if err != nil && strings.Contains(err.Error(), "invalid URL escape") {
 			//Fix the request url
@@ -184,9 +184,9 @@ func ReadRequest(b *bufio.ReadWriter) (req *Request, err error) {
 			if err != nil {
 				return req, fmt.Errorf("error while parsing HTTP request: %v", err)
 			}
-			invalidUrlEscapeFixed = true
+			invalidURLEscapeFixed = true
 		}
-		if err != nil && !invalidUrlEscapeFixed {
+		if err != nil && !invalidURLEscapeFixed {
 			return req, fmt.Errorf("error while parsing HTTP request: %v", err)
 		}
 

+ 4 - 3
response.go

@@ -19,6 +19,7 @@ import (
 	"time"
 )
 
+// ResponseWriter ---
 type ResponseWriter interface {
 	// Header returns the header map that will be sent by WriteHeader.
 	// Changing the header after a call to WriteHeader (or Write) has
@@ -29,7 +30,7 @@ type ResponseWriter interface {
 	// If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK, nil)
 	// before writing the data.
 	Write([]byte) (int, error)
-	
+
 	// Write raw data to the connection.
 	WriteRaw(string)
 
@@ -45,7 +46,7 @@ type respWriter struct {
 	req         *Request       // the request that is being responded to
 	header      http.Header    // the ICAP header to write for the response
 	wroteHeader bool           // true if the headers have already been written
-	wroteRaw    bool	   // true if raw data was written to the connection
+	wroteRaw    bool           // true if raw data was written to the connection
 	cw          io.WriteCloser // the chunked writer used to write the body
 }
 
@@ -206,7 +207,7 @@ func httpResponseHeader(resp *http.Response) (hdr []byte, err error) {
 		proto = "HTTP/1.1"
 	}
 	fmt.Fprintf(buf, "%s %d %s\r\n", proto, resp.StatusCode, text)
-	if _, xIcap206Exists:= resp.Header["X-Icap-206"] ; xIcap206Exists {
+	if _, xIcap206Exists := resp.Header["X-Icap-206"]; xIcap206Exists {
 		resp.Header.Write(buf)
 	} else {
 		resp.Header.WriteSubset(buf, map[string]bool{

+ 31 - 24
server.go

@@ -20,7 +20,7 @@ import (
 	"time"
 )
 
-// Objects implementing the Handler interface can be registered
+// Handler Objects implementing the Handler interface can be registered
 // to serve ICAP requests.
 //
 // ServeICAP should write reply headers and data to the ResponseWriter
@@ -94,7 +94,7 @@ func (c *conn) close() {
 }
 
 // Serve a new connection.
-func (c *conn) serve() {
+func (c *conn) serve(debugLevel int) {
 	defer func() {
 		err := recover()
 		if err == nil {
@@ -112,12 +112,13 @@ func (c *conn) serve() {
 	// In a case of parsing error there should be an option to handle a dummy request to not fail the whole service.
 
 	if err != nil {
-		log.Println("error while reading request:", err)
-		log.Println("error while reading request:", w)
-		log.Println("error while reading request:", w.conn)
-		log.Println("error while reading request:", w.req)
-		log.Println("error while reading request:", w.header)
-
+		if debugLevel > 0 {
+			log.Println("error while reading request:", err)
+			log.Println("error while reading request:", w)
+			log.Println("error while reading request:", w.conn)
+			log.Println("error while reading request:", w.req)
+			log.Println("error while reading request:", w.header)
+		}
 		//		c.rwc.Close()
 		//		return
 		if w == nil {
@@ -131,6 +132,7 @@ func (c *conn) serve() {
 		w.req.URL, _ = url.ParseRequestURI("icap://localhost/")
 		w.req.Header = textproto.MIMEHeader{
 			"Connection": {"close"},
+			// "Error:":     {err.Error()},
 		}
 	}
 
@@ -146,6 +148,7 @@ type Server struct {
 	Handler      Handler // handler to invoke
 	ReadTimeout  time.Duration
 	WriteTimeout time.Duration
+	DebugLevel   int
 }
 
 // ListenAndServe listens on the TCP network address srv.Addr and then
@@ -156,14 +159,15 @@ func (srv *Server) ListenAndServe() error {
 	if addr == "" {
 		addr = ":1344"
 	}
-	l, e := net.Listen("tcp", addr)
-	if e != nil {
-		return e
+	l, err := net.Listen("tcp", addr)
+	if err != nil {
+		return err
 	}
 	return srv.Serve(l)
 }
 
-func (srv *Server) ListenAndServeTls(cert, key string) error {
+// ListenAndServeTLS ---
+func (srv *Server) ListenAndServeTLS(cert, key string) error {
 
 	cer, err := tls.LoadX509KeyPair(cert, key)
 	if err != nil {
@@ -175,9 +179,9 @@ func (srv *Server) ListenAndServeTls(cert, key string) error {
 	}
 
 	config := &tls.Config{Certificates: []tls.Certificate{cer}}
-	l, e := tls.Listen("tcp", addr, config)
-	if e != nil {
-		return e
+	l, err := tls.Listen("tcp", addr, config)
+	if err != nil {
+		return err
 	}
 	return srv.Serve(l)
 }
@@ -193,13 +197,13 @@ func (srv *Server) Serve(l net.Listener) error {
 	}
 
 	for {
-		rw, e := l.Accept()
-		if e != nil {
-			if ne, ok := e.(net.Error); ok && ne.Temporary() {
-				log.Printf("icap: Accept error: %v", e)
+		rw, err := l.Accept()
+		if err != nil {
+			if ne, ok := err.(net.Error); ok && ne.Temporary() {
+				log.Printf("icap: Accept error: %v", err)
 				continue
 			}
-			return e
+			return err
 		}
 		if srv.ReadTimeout != 0 {
 			rw.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
@@ -211,9 +215,10 @@ func (srv *Server) Serve(l net.Listener) error {
 		if err != nil {
 			continue
 		}
-		go c.serve()
+		go c.serve(srv.DebugLevel)
 	}
-	panic("not reached")
+	// The next line is only there to see one specific edge case whichc should never happen.
+	panic("Shuold never be reached")
 }
 
 // Serve accepts incoming ICAP connections on the listener l,
@@ -231,7 +236,9 @@ func ListenAndServe(addr string, handler Handler) error {
 	server := &Server{Addr: addr, Handler: handler}
 	return server.ListenAndServe()
 }
-func ListenAndServeTls(addr, cert, key string, handler Handler) error {
+
+// ListenAndServeTLS --
+func ListenAndServeTLS(addr, cert, key string, handler Handler) error {
 	server := &Server{Addr: addr, Handler: handler}
-	return server.ListenAndServeTls(cert, key)
+	return server.ListenAndServeTLS(cert, key)
 }