-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
78 lines (60 loc) · 1.42 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"context"
"io"
"net"
"strings"
"time"
"unsafe"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type HTTP struct{}
func (s HTTP) Name() string {
return "http"
}
func (s HTTP) Network() string {
return "tcp"
}
func (s HTTP) Port() string {
return "80"
}
func (s HTTP) Scan(ip string, conn net.Conn) ([]byte, int64, error) {
request := []string{"GET / HTTP/1.1\r\nHost: ", ip, "\r\nConnection: close\r\n\r\n"}
get := strings.Join(request, "")
start := time.Now()
_, err := conn.Write(unsafe.Slice(unsafe.StringData(get), len(get)))
if err != nil {
return nil, 0, err
}
response := make([]byte, 17)
_, err = io.ReadFull(conn, response)
if err != nil {
return nil, 0, err
}
latency := time.Since(start).Milliseconds()
// Check if the status code is 2xx.
if response[9] != '2' {
return nil, 0, nil
}
response, err = read(conn, MAX_RESPONSE_LENGTH)
if err != nil {
return nil, 0, err
}
return response, latency, nil
}
func (s HTTP) Save(ip string, latency int64, data []byte, collection *mongo.Collection) error {
document := bson.M{
"_id": ip,
"latency": latency,
"data": *(*string)(unsafe.Pointer(&data)),
}
filter := bson.M{"_id": ip}
opts := options.Replace().SetUpsert(true)
_, err := collection.ReplaceOne(context.TODO(), filter, document, opts)
if err != nil {
return err
}
return nil
}