package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
	"net/http"
)

func main() {
	server := newCrispyServer()
	http.Handle("/", server)
	log.Printf("Serving on :9799 with %+v\n", server)
	log.Fatal(http.ListenAndServe(":9799", nil))
}

type crispyServer struct {
	logstasher *log.Logger
}

func newCrispyServer() *crispyServer {
	return &crispyServer{
		logstasher: newLogstashLogger(),
	}
}

func (me *crispyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/DIE" && r.Method == "POST" {
		me.logstasher.Fatal("OH GOSH")
	}

	j, err := json.Marshal(r)
	if err == nil {
		me.logstasher.Println(string(j))
	}
}

func newLogstashLogger() *log.Logger {
	return log.New(&logstashWriter{}, "", 0)
}

type logstashWriter struct{}

func (me *logstashWriter) Write(b []byte) (int, error) {
	conn, err := net.Dial("tcp", ":55784")
	if err == nil {
		defer conn.Close()
		fmt.Fprintf(conn, string(b))
	} else {
		fmt.Printf(string(b))
	}
	return 0, nil
}