-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrouter.go
More file actions
48 lines (39 loc) · 962 Bytes
/
router.go
File metadata and controls
48 lines (39 loc) · 962 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"
"net/http"
"log"
"sync/atomic"
"io"
)
type Router struct{
nodes []*CacheServer
counter uint32
}
func NewRouter(nodes []*CacheServer) *Router{
return &Router{
nodes: nodes,
}
}
func (router *Router) getNextNode() * CacheServer{
idx := atomic.AddUint32(&router.counter, 1)%uint32(len(router.nodes))
return router.nodes[idx]
}
func (router *Router) handler(w http.ResponseWriter, r *http.Request){
node := router.getNextNode()
fmt.Printf("Routing request (%s) to CDN: %s\n", r.URL.Path, node.address)
resp, err := http.Get("http://" + node.address + r.URL.Path)
if err != nil{
http.Error(w, "CDN Node error", http.StatusBadGateway)
return
}
defer resp.Body.Close()
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
func (router *Router) start(){
mux := http.NewServeMux()
mux.HandleFunc("/", router.handler)
fmt.Println("Router running on :8000")
log.Fatal(http.ListenAndServe(":8000", mux))
}