tpingd.go: do not use net/http
This commit is contained in:
56
tpingd.go
56
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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user