-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathload_balancer.go
More file actions
48 lines (40 loc) · 900 Bytes
/
load_balancer.go
File metadata and controls
48 lines (40 loc) · 900 Bytes
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
package main
import (
"fmt"
"io"
"net/http"
"sync"
)
type Loadbalancer struct {
servers []ServerURI
currentServer int
mux *sync.RWMutex
protocol Algo
}
func (lb *Loadbalancer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
lb.mux.Lock()
defer lb.mux.Unlock()
var res *http.Response
switch method := r.Method; method {
case http.MethodGet:
res, _ = http.Get(fmt.Sprintf("%s%s", lb.servers[lb.currentServer].Uri, r.URL.Path))
case http.MethodPost:
res, _ = http.Post(
fmt.Sprintf("%s%s", lb.servers[lb.currentServer].Uri, r.URL.Path),
"",
r.Body,
)
default:
panic(fmt.Errorf("method %s not supported", method))
}
defer lb.next()
io.Copy(w, res.Body)
}
func (lb *Loadbalancer) next() {
if lb.protocol == 0 {
lb.roundRobin()
}
}
func (lb *Loadbalancer) roundRobin() {
lb.currentServer = (lb.currentServer + 1) % len(lb.servers)
}