You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

115 lines
2.3 KiB

package main
import (
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
)
const scriptsDir = "scripts"
func getLocalIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
continue
}
ip = ip.To4()
if ip == nil {
continue
}
return ip.String(), nil
}
return "", fmt.Errorf("no local IP address found")
}
func main() {
// 服务端口号
port := "18123"
// 确保脚本目录存在
if _, err := os.Stat(scriptsDir); os.IsNotExist(err) {
os.Mkdir(scriptsDir, os.ModePerm)
}
// 遍历脚本目录并输出文件列表
files, err := os.ReadDir(scriptsDir)
if err != nil {
log.Fatalf("无法读取脚本目录: %v", err)
}
if len(files) > 0 {
ip, err := getLocalIP()
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Local IP address:", ip)
}
fmt.Println("脚本目录下的文件有:")
for _, file := range files {
if !file.IsDir() {
fmt.Printf("// @require http://%s:%s/scripts/%s\n", ip, port, file.Name())
}
}
} else {
fmt.Println("脚本目录为空。")
}
fmt.Println("")
// 提供脚本下载
http.HandleFunc("/scripts/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
fileName := filepath.Base(r.URL.Path)
filePath := filepath.Join(scriptsDir, fileName)
// 检查文件是否存在
if _, err := os.Stat(filePath); os.IsNotExist(err) {
http.Error(w, "脚本未找到", http.StatusNotFound)
return
}
// 打开文件
file, err := os.Open(filePath)
if err != nil {
http.Error(w, "无法打开文件", http.StatusInternalServerError)
return
}
defer file.Close()
// 获取文件的修改时间
fileInfo, err := file.Stat()
if err != nil {
http.Error(w, "无法获取文件信息", http.StatusInternalServerError)
return
}
// 提供文件下载
http.ServeContent(w, r, fileName, fileInfo.ModTime(), file)
} else {
http.Error(w, "不支持的方法", http.StatusMethodNotAllowed)
}
})
// 启动服务器
fmt.Printf("服务器已启动,监听端口: %s\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}