-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathorigin_server.go
More file actions
43 lines (37 loc) · 982 Bytes
/
origin_server.go
File metadata and controls
43 lines (37 loc) · 982 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
package main
import (
"fmt"
"log"
"net/http"
"sync"
"time"
"os"
)
type OriginServer struct{
address string
load int
mu sync.Mutex
}
func (origin *OriginServer) handler(w http.ResponseWriter, r *http.Request){
fmt.Printf("Serving file from origin %s for %s\n", origin.address, r.URL.Path)
// increase load on the current origin
origin.mu.Lock()
origin.load++
fmt.Printf("Current load on origin %s: %d\n", origin.address, origin.load)
origin.mu.Unlock()
// simulate latency
time.Sleep(1 * time.Second)
// serving files from static folder
filePath := "./static" + r.URL.Path
if _, err := os.Stat(filePath); err == nil {
http.ServeFile(w, r, filePath)
} else {
http.Error(w, "File not found", http.StatusNotFound)
}
}
func (origin *OriginServer) start(){
mux := http.NewServeMux()
mux.HandleFunc("/", origin.handler)
fmt.Println("Running origin server on", origin.address)
log.Fatal(http.ListenAndServe(origin.address, mux))
}