Created
July 20, 2023 09:54
-
-
Save bodokaiser/712178d8612a107905d9de2d751387d8 to your computer and use it in GitHub Desktop.
HTTP Server logging everything sent and received on the TCP socket.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"net" | |
"net/http" | |
) | |
type loggingConn struct { | |
net.Conn | |
} | |
func (conn loggingConn) Read(b []byte) (n int, err error) { | |
n, err = conn.Conn.Read(b) | |
if n > 0 { | |
log.Printf("Received: %q", b[:n]) | |
} | |
return | |
} | |
func (conn loggingConn) Write(b []byte) (n int, err error) { | |
n, err = conn.Conn.Write(b) | |
if n > 0 { | |
log.Printf("Sent: %q", b[:n]) | |
} | |
return | |
} | |
func loggingListener(inner net.Listener) net.Listener { | |
return &wrappedListener{inner} | |
} | |
type wrappedListener struct { | |
net.Listener | |
} | |
func (ln wrappedListener) Accept() (net.Conn, error) { | |
conn, err := ln.Listener.Accept() | |
if err != nil { | |
return nil, err | |
} | |
return loggingConn{conn}, nil | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "Hello, world!") | |
} | |
func main() { | |
ln, err := net.Listen("tcp", ":80") | |
if err != nil { | |
log.Fatal(err) | |
} | |
http.HandleFunc("/", handler) | |
log.Fatal(http.Serve(loggingListener(ln), nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment