Skip to content

Instantly share code, notes, and snippets.

@kasey
Created August 6, 2021 22:19
Show Gist options
  • Save kasey/53777d99064e729d862e55ff406f0c31 to your computer and use it in GitHub Desktop.
Save kasey/53777d99064e729d862e55ff406f0c31 to your computer and use it in GitHub Desktop.
http-logger.go
package main
import (
"bytes"
"compress/gzip"
"encoding/base64"
"io"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type ReqDumper struct {
writer io.Writer
}
func (rd *ReqDumper) ServeHTTP(w http.ResponseWriter, req *http.Request) {
buf := bytes.NewBuffer(nil)
err := req.Write(buf)
if err != nil {
log.Fatal(err)
}
encoded := make([]byte, base64.StdEncoding.EncodedLen(len(buf.Bytes())))
base64.StdEncoding.Encode(encoded, buf.Bytes())
encoded = append(encoded, []byte("\n")...)
log.Print(string(buf.String()))
log.Print(string(encoded))
_, err = rd.writer.Write(encoded)
if err != nil {
log.Fatal(err)
}
}
func main() {
out, err := os.OpenFile("request-log.gz", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
if err != nil {
log.Fatal(err)
}
gzout := gzip.NewWriter(out)
cleanup := func() {
gzout.Close()
out.Close()
}
rd := &ReqDumper{writer: gzout}
s := &http.Server{
Addr: ":8082",
Handler: rd,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
cleanup()
os.Exit(0)
}()
s.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment