-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
109 lines (96 loc) · 2.7 KB
/
server.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
package main
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"wd-reader/go/book"
"wd-reader/go/constant"
"wd-reader/go/log"
)
const (
HttpPort = ":10050"
)
// Server struct
type Server struct {
ctx context.Context
}
// NewServer creates a new Server application struct
func NewServer() *Server {
return &Server{}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *Server) startup(ctx context.Context) {
a.ctx = ctx
// 定义处理函数
//handler := func(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintf(w, "Hello, World!")
//}
dir := book.GetAppPath()
join := filepath.Join(dir, constant.BOOK_PATH)
fmt.Println("资源目录", join)
//fileServer := http.FileServer(http.Dir(join))
// 自定义文件服务器处理函数
fileServer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 获取请求的文件路径
filePath := filepath.Join(join, r.URL.Path)
// 检查文件是否存在
_, err := os.Stat(filePath)
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
// 打开文件
file, err := os.Open(filePath)
if err != nil {
http.Error(w, "Error opening file", http.StatusInternalServerError)
return
}
defer file.Close()
// 获取文件后缀
ext := filepath.Ext(filePath)
// 对于.txt 文件设置 Content-Type 为 text/plain; charset=utf-8
// 缓存一天
w.Header().Set("Cache-Control", "public, max-age=5184000")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
if ext == ".txt" {
// 解决乱码的问题
charset := book.GetFileCharset(filePath)
w.Header().Set("Content-Type", "text/plain; charset="+charset)
}
reader := bufio.NewReader(file)
// 读取文件内容
content, err := io.ReadAll(reader)
if err != nil {
http.Error(w, "Error reading file", http.StatusInternalServerError)
return
}
// 处理文件编码问题,假设文件可能是 ANSI 编码,将其转换为 UTF-8
//if ext == ".txt" {
// utf8Content, err := convertToUTF8(content)
// if err == nil {
// content = utf8Content
// }
//}
// 输出文件内容
_, _ = w.Write(content)
})
// 注册处理函数
http.Handle("/", fileServer)
go func() {
// 监听端口 8080
err := http.ListenAndServe(HttpPort, nil)
fmt.Println("资源服务启动成功 url:", "http://localhost:10050")
if err != nil {
log.GetLogger().Info("文件服务启动异常" + err.Error())
fmt.Println("Error starting HTTP server:", err)
}
}()
}