-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
75 lines (60 loc) · 1.6 KB
/
server.go
File metadata and controls
75 lines (60 loc) · 1.6 KB
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
package main
import (
"context"
"fmt"
"net"
"net/http"
"os"
"time"
log "github.com/sirupsen/logrus"
)
var port = 80
var ServerId = "1"
var chunks = []string{}
func chunkHandler(w http.ResponseWriter, r *http.Request) {
conn := GetConn(r)
log.Infof("RemoteAddr: %s", conn.RemoteAddr().String())
log.Infof("LocalAddr: %s", conn.LocalAddr().String())
flusher, ok := w.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
for _, s := range chunks {
log.Info(fmt.Sprintf("S: %s", s))
fmt.Fprint(w, s)
flusher.Flush() // Trigger "chunked" encoding and send a chunk...
time.Sleep(50 * time.Millisecond)
}
}
func getChunks() []string {
chunks := []string{}
chunks = append(chunks, "Hello, ServerId: "+ServerId+"!")
chunks = append(chunks, "<--! chunk -->")
return chunks
}
type contextKey struct {
key string
}
var ConnContextKey = &contextKey{"http-conn"}
func SaveConnInContext(ctx context.Context, c net.Conn) context.Context {
return context.WithValue(ctx, ConnContextKey, c)
}
func GetConn(r *http.Request) net.Conn {
return r.Context().Value(ConnContextKey).(net.Conn)
}
func main() {
EnvServerId := os.Getenv("SERVER_ID")
if EnvServerId != "" {
ServerId = EnvServerId
}
log.Info(fmt.Sprintf("Server started. port: %d, ServerId: %s", port, ServerId))
chunks = getChunks()
http.HandleFunc("/", chunkHandler)
server := http.Server{
Addr: fmt.Sprintf(":%d", port),
ConnContext: SaveConnInContext,
}
server.ListenAndServe()
}