Skip to content

Commit

Permalink
feat: 添加http文件服务器功能,增加配置文件
Browse files Browse the repository at this point in the history
  • Loading branch information
meowrain committed Jun 16, 2024
1 parent 4818dd3 commit 9f23a82
Show file tree
Hide file tree
Showing 11 changed files with 195 additions and 15 deletions.
22 changes: 17 additions & 5 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"flag"
"fmt"
"localsend_cli/internal/config"
"localsend_cli/internal/discovery"
"localsend_cli/internal/handlers"
"localsend_cli/internal/pkg/server"
Expand All @@ -24,11 +25,22 @@ func main() {

// 启动HTTP服务器
httpServer := server.New()
httpServer.HandleFunc("/api/localsend/v2/prepare-upload", handlers.PrepareReceive)
httpServer.HandleFunc("/api/localsend/v2/upload", handlers.ReceiveHandler)
httpServer.HandleFunc("/send", handlers.SendHandler) // 上传处理程序
httpServer.HandleFunc("/receive", handlers.NormalReceiveHandler) // 下载处理程序
httpServer.Handle("/", http.FileServer(http.Dir("static")))
if config.ConfigData.Functions.HttpFileServer {

//如果启用http文件服务器,启用下面的路由
httpServer.HandleFunc("/", handlers.IndexFileHandler)
httpServer.HandleFunc("/uploads/", handlers.FileServerHandler)
httpServer.Handle("/static/", http.FileServer(http.Dir(".")))
}
/*发送接收部分*/
if config.ConfigData.Functions.LocalSendServer {

httpServer.HandleFunc("/api/localsend/v2/prepare-upload", handlers.PrepareReceive)
httpServer.HandleFunc("/api/localsend/v2/upload", handlers.ReceiveHandler)
httpServer.HandleFunc("/send", handlers.SendHandler) // 上传处理程序
httpServer.HandleFunc("/receive", handlers.NormalReceiveHandler) // 下载处理程序

}
go func() {
log.Println("Server started at :53317")
if err := http.ListenAndServe(":53317", httpServer); err != nil {
Expand Down
5 changes: 5 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: "Server"

functions:
http_file_server: false
local_send_server: true
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ require (
golang.org/x/net v0.26.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.21.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
40 changes: 33 additions & 7 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
package config

var Names = []string{
"Alpha", "Bravo", "Charlie", "Delta", "Echo",
"Foxtrot", "Golf", "Hotel", "India", "Juliett",
"Kilo", "Lima", "Mike", "November", "Oscar",
"Papa", "Quebec", "Romeo", "Sierra", "Tango",
"Uniform", "Victor", "Whiskey", "X-ray", "Yankee", "Zulu",
import (
"io"
"log"
"os"

"gopkg.in/yaml.v2"
)

type Config struct {
NameOfDevice string `yaml:"name"`
Functions struct {
HttpFileServer bool `yaml:"http_file_server"`
LocalSendServer bool `yaml:"local_send_server"`
} `yaml:"functions"`
}

var NameOfDevice string = "Server"
var ConfigData Config

func init() {
configFile, err := os.Open("config.yaml")
if err != nil {
log.Fatalf("Error opening config file: %v", err)
}
defer configFile.Close()

bytes, err := io.ReadAll(configFile)
if err != nil {
log.Fatalf("Error reading config file: %v", err)
}

err = yaml.Unmarshal(bytes, &ConfigData)
if err != nil {
log.Fatalf("Error parsing config file: %v", err)
}
}
2 changes: 1 addition & 1 deletion internal/discovery/shared/shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
var DiscoveredDevices = make(map[string]BroadcastMessage)
var Mu sync.Mutex
var Messsage BroadcastMessage = BroadcastMessage{
Alias: config.NameOfDevice,
Alias: config.ConfigData.NameOfDevice,
Version: "2.0",
DeviceModel: utils.CheckOSType(),
DeviceType: "desktop",
Expand Down
61 changes: 61 additions & 0 deletions internal/handlers/fileServer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package handlers

import (
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
)

const uploadDir = "./uploads"

func GetFilesFromDir(dir string) ([]os.DirEntry, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
return entries, nil
}

func FileServerHandler(w http.ResponseWriter, r *http.Request) {
file := strings.TrimPrefix(r.URL.Path, "/uploads/")
http.ServeFile(w, r, filepath.Join(uploadDir, file))
}

func IndexFileHandler(w http.ResponseWriter, r *http.Request) {
dirPath := filepath.Join(uploadDir, strings.TrimPrefix(r.URL.Path, "/uploads/"))

info, err := os.Stat(dirPath)
if os.IsNotExist(err) {
http.NotFound(w, r)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

if info.IsDir() {
files, err := GetFilesFromDir(dirPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

tmpl := template.Must(template.ParseFiles("templates/cloudstorage.html"))
data := struct {
Path string
Files []os.DirEntry
}{
Path: r.URL.Path,
Files: files,
}

err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
http.ServeFile(w, r, dirPath)
}
}
2 changes: 0 additions & 2 deletions internal/handlers/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import (
"path/filepath"
)

const uploadDir = "uploads"

// SendHandler 处理文件上传请求
func SendHandler(w http.ResponseWriter, r *http.Request) {
// 解析multipart/form-data
Expand Down
48 changes: 48 additions & 0 deletions static/css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
background-color: #fff;
padding: 20px 40px;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
width: 80%;
max-width: 700px;
box-sizing: border-box;
}
h1 {
color: #333;
text-align: center;
margin-bottom: 30px;
font-size: 2em;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
margin: 10px 0;
padding: 10px;
border-radius: 5px;
transition: background-color 0.3s, transform 0.3s;
}
li:hover {
background-color: #f1f1f1;
transform: scale(1.02);
}
a {
text-decoration: none;
color: #007BFF;
font-weight: bold;
}
a:hover {
text-decoration: underline;
}
25 changes: 25 additions & 0 deletions templates/cloudstorage.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Uploads</title>
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Uploads</h1>
<ul>
{{range .Files}}
<li>
{{if .IsDir}}
<a href="{{$.Path}}{{.Name}}/">{{.Name}}/</a>
{{else}}
<a href="{{$.Path}}{{.Name}}">{{.Name}}</a>
{{end}}
</li>
{{end}}
</ul>
</div>
</body>
</html>
1 change: 1 addition & 0 deletions static/index.html → templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ <h1 class="text-4xl font-bold mb-4">Welcome to localsend_cli</h1>
<a href="#" class="bg-blue-500 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-600">Get Started</a>
<a href="#" class="bg-gray-500 text-white px-6 py-3 rounded-lg font-semibold hover:bg-gray-600">Documentation</a>
</div>

</div>
</div>
</body>
Expand Down

0 comments on commit 9f23a82

Please sign in to comment.