From 4fbb5170d2e46e6a6201e33630e8404796496ef3 Mon Sep 17 00:00:00 2001 From: Sergei Fedosov Date: Fri, 2 Oct 2020 14:41:51 +0300 Subject: [PATCH] tpingd.go: do not use net/http --- tpingd.go | 56 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 21 deletions(-) diff --git a/tpingd.go b/tpingd.go index 647d5a4..9bd524e 100644 --- a/tpingd.go +++ b/tpingd.go @@ -1,11 +1,10 @@ package main -// vim: set ft=go noet ai ts=4 sw=4 sts=4: import ( "fmt" "net" + "os" "time" - "net/http" ) var result = false @@ -25,33 +24,48 @@ func mycheck() { } } -// create a handler struct -type HttpHandler struct{} +func handleConnection(conn net.Conn) { + buf := make([]byte, 1024) + bufLen, err := conn.Read(buf) -// implement `ServeHTTP` method on `HttpHandler` struct -func (h HttpHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) { - // create response binary data - data := []byte("Unreachable\n") // slice of bytes + if err == nil { + tail := string(buf[bufLen - 4 : bufLen]) - if result { - data = []byte("Reachable\n") + // ah, fuck, yea. if you check buffer with \n\r\n\r against "\n\r\n\r" you'll get always FALSE, but if check against hex values, it works + if bufLen > 4 && fmt.Sprintf("%x", tail) == "0d0a0d0a" { + if result { + conn.Write([]byte("HTTP/1.1 200 OK\nContent-Type: text/plain\nConnection: close\n\nReachable\n")) + } else { + conn.Write([]byte("HTTP/1.1 200 OK\nContent-Type: text/plain\nConnection: close\n\nUnreachable\n")) + } + + conn.Close() + } else { + conn.Write([]byte("HTTP/1.1 400 Bad Request\nContent-Type: text/plain\nConnection: close\n\nBad Request\n")) + conn.Close() + } } - - // write data to response - res.Write(data) } - func main() { - // spawn goroutine, it "backgrounds" automatically - go mycheck() - - // create a new handler - handler := HttpHandler{} - // listen and serve - e := http.ListenAndServe("127.0.0.1:9000", handler) + ln, e := net.Listen("tcp", "127.0.0.1:9000") if e != nil { fmt.Println(e) + os.Exit(1) + } + + // spawn check goroutine + go mycheck() + + for { + conn, e := ln.Accept() + + if e != nil { + // shit happens, let's try one more time + continue + } + + go handleConnection(conn) } }