/
main.go
186 lines (151 loc) · 3.67 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package main
import (
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/astaxie/beego/httplib"
"github.com/facebookgo/grace/gracehttp"
)
// Conf 配置
type Conf struct {
Port string
Hosts []string
LocalDir string
WriteHere bool
}
var configFile = "proxystaticfile.toml"
var conf *Conf
var configFileTemplate = ` # proxystaticfile
# 使用 ./proxystaticfile -c ./proxystaticfile.toml
# 默认挂载当前的的conf文件,配置文件使用 toml 格式输出
# 【情景】
# 用于代理均衡负载分布服务器的的静态文件输出,默认超时时间为30s
# 运行端口
port = "8808"
# 远程地址,在局域网中使用局域网地址;注意文件的相对路径
hosts = ["127.0.0.1","www.xxx.net/img"]
# 当前服务器端的文件所在地址
localDir = "/Users/user/Sites/img/"
# 代理的内容自动写入代理服务器
WriteHere = false
`
var defaultToml = "proxystaticfile.toml"
func init() {
if len(os.Args) > 1 && os.Args[1] == "new" {
newConfig()
os.Exit(1)
}
flag.StringVar(&configFile, "c", defaultToml, "extention eg: -c proxystaticfile.toml")
flag.Parse()
if _, err := toml.DecodeFile(configFile, &conf); err != nil {
log.Fatal("[conf]", err)
}
log.Println(conf)
}
// newConfig 写入配置文件
func newConfig() {
t, err := os.Create(defaultToml)
if err != nil {
log.Fatalln(err)
}
t.WriteString(configFileTemplate)
t.Close()
}
func main() {
http.HandleFunc("/", findFile)
log.Println("[server]:start :", conf.Port)
log.Println(conf)
err := gracehttp.Serve(&http.Server{Addr: ":" + conf.Port, Handler: nil})
// err := http.ListenAndServe(":"+conf.Port, nil)
if err != nil {
log.Fatal(err)
}
}
func findFile(w http.ResponseWriter, r *http.Request) {
url := r.URL.String()
url = strings.Trim(url, "%20")
log.Println("[geturl]:", url)
// 本地查询文件
path := filepath.Clean(path.Join(conf.LocalDir, url))
file, err := os.Open(path)
defer file.Close()
if err != nil {
log.Println("[localfile]:", err)
} else {
fileInfo, _ := file.Stat()
log.Printf("[localfile]:%s is exist.\n", fileInfo.Name())
fb, _ := ioutil.ReadFile(path)
w.Write(fb)
return
}
// 远程查询文件
pf := newProxyFile(url)
header, data, status := pf.findFile()
for k, v := range header {
for _, vv := range v {
w.Header().Add(k, vv)
}
}
w.WriteHeader(status)
w.Write(data)
}
// 代理文件请求
type proxyFile struct {
url string
hosts []string
}
// 创建新的
func newProxyFile(url string) proxyFile {
return proxyFile{
url: url,
hosts: conf.Hosts,
}
}
// findFile 查询远程文件存在,仅返回200,400的数据
func (p *proxyFile) findFile() (header http.Header, data []byte, status int) {
// chan findok int
for _, hostStep := range p.hosts {
url := "http://" + hostStep + p.url
req := httplib.Get(url).SetTimeout(time.Second*10, time.Second*10)
resp, err := req.Response()
if err != nil {
log.Println(err)
}
status = resp.StatusCode
header = resp.Header
log.Printf("[proxy][url]%s [%d]\n", url, status)
if status == 200 {
data, _ = req.Bytes()
if conf.WriteHere {
go writeFile(path.Join(conf.LocalDir, p.url), data)
}
return
}
}
status = http.StatusNotFound
data = []byte("404: File is undefined!")
return
}
// writeFile 将文件同步写入到本地文件
func writeFile(url string, b []byte) error {
dir, _ := path.Split(url)
err := os.MkdirAll(dir, 0755)
if err != nil {
log.Println("--wirteDir-->", err)
}
f, err := os.Create(url)
_, err = f.Write(b)
// err = p.req.ToFile(pf)
if err != nil {
log.Println("--wirteFile-->", err)
}
f.Close()
return err
}