This repository has been archived by the owner on Dec 3, 2018. It is now read-only.
/
main.go
82 lines (63 loc) · 2.07 KB
/
main.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
79
80
81
82
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/justinas/alice"
"log"
"net/http"
"runtime"
"static-proxy/deliver"
"static-proxy/settings"
"static-proxy/utils"
"static-proxy/viewer"
"time"
)
const (
VERSION = "0.0.2"
)
func init() {
settings.SetupOptions("config address env")
}
func main() {
settings.Setup()
err := settings.Build()
if err != nil {
log.Fatal(fmt.Errorf("Unable to load configuration, %v", err))
}
runtime.GOMAXPROCS(settings.Config.NumCPU)
printBanner(settings.Config)
fs := http.FileServer(http.Dir("./static"))
router := mux.NewRouter()
commonHandlers := alice.New(loggingHandler, recoverHandler)
// Mandatory root-based resources
serveSingle(router, "/favicon.ico", "./static/favicon.ico")
serveSingle(router, "/robots.txt", "./static/robots.txt")
router.PathPrefix("/static/").Handler(viewer.ServeStatic(http.StripPrefix("/static/", fs))).Methods("GET")
router.NotFoundHandler = http.HandlerFunc(viewer.NotFoundPage())
server := deliver.New(settings.Config.Workers)
router.Handle("/{filename:.+}", server).Methods("GET")
log.Fatal(http.ListenAndServe(settings.Config.Address+":"+settings.Config.Port, commonHandlers.Then(router)))
}
func printBanner(config *settings.Settings) {
log.Println("StaticProxy", VERSION, "("+runtime.Version()+" "+runtime.GOOS+"/"+runtime.GOARCH+")")
log.Println("- environment:", settings.AppSettings.GetString("env"))
log.Println("- numcpu: ", config.NumCPU)
log.Println("listen", config.Address+":"+config.Port)
}
func serveSingle(router *mux.Router, pattern string, filename string) {
router.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
})
}
func loggingHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
log.Printf("%s - [%s] %q %v\n", utils.GetIpFromRequest(r), r.Method, r.URL.String(), t2.Sub(t1))
}
return http.HandlerFunc(fn)
}
func recoverHandler(next http.Handler) http.Handler {
return viewer.InternalErrorPage(next)
}