1

tpingd.go: do not use net/http

This commit is contained in:
Sergei Fedosov
2020-10-02 14:41:51 +03:00
parent 169f4ef309
commit 4fbb5170d2

View File

@@ -1,11 +1,10 @@
package main package main
// vim: set ft=go noet ai ts=4 sw=4 sts=4:
import ( import (
"fmt" "fmt"
"net" "net"
"os"
"time" "time"
"net/http"
) )
var result = false var result = false
@@ -25,33 +24,48 @@ func mycheck() {
} }
} }
// create a handler struct func handleConnection(conn net.Conn) {
type HttpHandler struct{} buf := make([]byte, 1024)
bufLen, err := conn.Read(buf)
// implement `ServeHTTP` method on `HttpHandler` struct if err == nil {
func (h HttpHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) { tail := string(buf[bufLen - 4 : bufLen])
// create response binary data
data := []byte("Unreachable\n") // slice of bytes
if result { // 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
data = []byte("Reachable\n") 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() { func main() {
// spawn goroutine, it "backgrounds" automatically ln, e := net.Listen("tcp", "127.0.0.1:9000")
go mycheck()
// create a new handler
handler := HttpHandler{}
// listen and serve
e := http.ListenAndServe("127.0.0.1:9000", handler)
if e != nil { if e != nil {
fmt.Println(e) 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)
} }
} }