tpingd.go: do not use net/http
This commit is contained in:
52
tpingd.go
52
tpingd.go
@@ -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
|
|
||||||
|
|
||||||
|
// 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 {
|
if result {
|
||||||
data = []byte("Reachable\n")
|
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"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// write data to response
|
conn.Close()
|
||||||
res.Write(data)
|
} else {
|
||||||
|
conn.Write([]byte("HTTP/1.1 400 Bad Request\nContent-Type: text/plain\nConnection: close\n\nBad Request\n"))
|
||||||
|
conn.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user