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
| package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"golang.org/x/net/webdav"
)
var webDavConfig map[string]interface{}
var fs_webdav = &webdav.Handler{}
var webdav_port_string string
func init() {
ConfigData, err := os.ReadFile("config.json") // 读取文件
var settingCfg string
if err == nil {
settingCfg = string(ConfigData)
} else {
//无配置文件的情况
settingCfg = "{\"wevdav_user_name\":\"\",\"wevdav_user_psw\":\"\",\"webdav_server_port\":18123,\"wevdav_file_path\":\".\",\"list_server_path\":\"/list/\",\"list_file_path\":\".\"}"
fmt.Println("无配置文件使用默认")
fmt.Println("settingCfg", settingCfg)
}
json.Unmarshal([]byte(settingCfg), &webDavConfig) //转化到map
}
func main() {
port_float64, _ := strconv.ParseFloat(fmt.Sprintf("%f", webDavConfig["webdav_server_port"]), 64) //从interface转化到float64 再到int 再到port_str
webdav_port_string = fmt.Sprintf("%d", int(port_float64))
http.HandleFunc("/", web_dav) //启动webdav
fmt.Println("webdav url: http://localhost:" + webdav_port_string + "/ file pach:" + fmt.Sprintf("%s", webDavConfig["wevdav_file_path"]))
if webDavConfig["wevdav_user_name"] != "" {
fmt.Println("wevdav_user_name=", webDavConfig["wevdav_user_name"], ", wevdav_user_psw=", webDavConfig["wevdav_user_psw"])
}
//http.HandleFunc("/list2/", http_list1)
list_server_path := fmt.Sprintf("%s", webDavConfig["list_server_path"])
list_file_path := fmt.Sprintf("%s", webDavConfig["list_file_path"])
if list_server_path != "" {
http.Handle(list_server_path, http.StripPrefix(list_server_path, http.FileServer(http.Dir(list_file_path))))
fmt.Println("weblist url: http://localhost:" + webdav_port_string + list_server_path + " file pach:" + list_file_path)
}
http.ListenAndServe(":"+webdav_port_string, nil)
}
/* webdav */
func web_dav(w http.ResponseWriter, req *http.Request) {
if webDavConfig["wevdav_user_name"] != "" {
// 获取用户名/密码
wevdav_user_name, wevdav_user_psw, ok := req.BasicAuth()
if !ok {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
// 验证用户名/密码
if wevdav_user_name != fmt.Sprintf("%s", webDavConfig["wevdav_user_name"]) || wevdav_user_psw != fmt.Sprintf("%s", webDavConfig["wevdav_user_psw"]) {
http.Error(w, "WebDAV: need authorized!", http.StatusUnauthorized)
return
}
}
fs_webdav = &webdav.Handler{
FileSystem: webdav.Dir(fmt.Sprintf("%s", webDavConfig["wevdav_file_path"])), //路径
LockSystem: webdav.NewMemLS(),
}
fs_webdav.ServeHTTP(w, req)
}
|