Repository navigation
Expand file tree
/
Copy pathhttp.go
More file actions
215 lines (188 loc) · 6.22 KB
/
Copy pathhttp.go
File metadata and controls
215 lines (188 loc) · 6.22 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package main
// MIT https://github.com/erred/gitreposerver
import (
"log"
"net/http"
"smart-git/database"
"github.com/fenthope/compress"
"github.com/fenthope/record"
"github.com/infinite-iroha/touka"
)
// RunHTTP 函数启动 HTTP 服务器,处理 Git 仓库的 upload-pack 服务。
//
// 参数:
// - addr: 服务器监听地址,例如 ":8080"。
// - baseRepoDir: Git 仓库的基础目录。
//
// 返回值:
// - error: 如果服务器启动失败,则返回错误信息。
func RunHTTP(addr string, baseRepoDir string) error {
logInfo("Starting HTTP server on addr '%s'\n", addr)
r := touka.Default()
r.SetProtocols(&touka.ProtocolsConfig{
Http1: true,
Http2_Cleartext: true,
})
// 添加中间件
r.Use(record.Middleware())
r.Use(compress.Compression(compress.DefaultCompressionConfig()))
r.GET("/:user/:repo/info/refs", handleInfoRefs(baseRepoDir)) // 处理仓库引用信息请求
r.POST("/:user/:repo/git-upload-pack", serviceRPC(baseRepoDir)) // 处理 git-upload-pack 请求
r.GET("/healthz", func(c *touka.Context) {
RenderWANF(c, http.StatusOK, &APIHealthResponse{
Status: "ok",
RepoDir: cfg.Server.BaseDir,
DatabasePath: cfg.Database.Path,
GithubBase: "https://github.com",
})
})
// info获取
r.GET("/api/db/data", func(c *touka.Context) {
allData, err := database.DB.GetAllData()
if err != nil {
RenderWANFError(c, http.StatusInternalServerError, err.Error())
return
}
resp := make([]APIRepoRecord, 0, len(allData))
for _, record := range allData {
resp = append(resp, NewAPIRepoRecord(record))
}
RenderWANF(c, http.StatusOK, &APIRepoRecordList{Items: resp})
})
r.GET("/api/db/sum", func(c *touka.Context) {
allData, err := database.DB.GetAllSumData()
if err != nil {
RenderWANFError(c, http.StatusInternalServerError, err.Error())
return
}
resp := make([]APIRepoStats, 0, len(allData))
for _, record := range allData {
resp = append(resp, NewAPIRepoStats(record))
}
RenderWANF(c, http.StatusOK, &APIRepoStatsList{Items: resp})
})
// 404 路由处理
r.NoRoute(func(c *touka.Context) {
logInfo("404 Not Found, Path: %s", string(c.GetRequestURIPath())) // 使用 rc.Path() 获取路径
c.Status(http.StatusNotFound) // 发送 404 状态码
})
err := r.Run(
touka.WithAddr(addr),
touka.WithGracefulShutdownDefault(),
)
if err != nil {
logError("Error starting HTTP server: %v\n", err)
return err
}
log.Println("HTTP server stopped")
return nil
}
// httpGitUploadPack 函数处理 /git-upload-pack 请求,允许客户端推送代码到服务器。
//
// 该函数接收客户端发送的 pack 文件,并调用 Git 服务器的 upload-pack 会话来处理推送操作。
// 支持处理 gzip 压缩的请求体。
//
// 参数:
// - baseRepoDir: Git 仓库的基础目录。
//
// 返回值:
// - app.Handler: Hertz 路由处理函数。
/*
func httpGitUploadPack(c *touka.Context, baseRepoDir string) { // 使用 Hertz 的 Context 和 RequestContext
repoName := c.Param("repo") // 使用 rc.Param 获取路由参数
if repoName == "" {
logError("repoName is empty")
c.Error(errors.New("repoName is empty")) // 使用 Hertz 的 Error Handling
c.Status(http.StatusInternalServerError)
return
}
userName := c.Param("user")
dir := baseRepoDir + "/" + userName + "/" + repoName
c.SetContentType("application/x-git-upload-pack-result") // 使用 rc.SetContentType 设置 Content-Type
bodyBytes := c.Request.Body() // 使用 rc.Request.Body() 获取请求体
var bodyReader io.Reader = bytes.NewReader(bodyBytes)
if string(c.GetHeader("Content-Encoding")) == "gzip" {
gzipReader, err := gzip.NewReader(bytes.NewReader(bodyBytes))
if err != nil {
logError("Error creating gzip reader: %v, repo: %s\n", err, repoName)
c.Error(err)
_, errResp := c.WriteString(err.Error())
if errResp != nil {
logError("WriteString error: %v\n", errResp)
}
c.Status(http.StatusInternalServerError)
return
}
defer gzipReader.Close()
bodyReader = gzipReader
}
upr := packp.NewUploadPackRequest()
err := upr.Decode(bodyReader)
if err != nil {
// 尝试读取并记录请求体的前几行,以便诊断问题
bodyBuffer := new(bytes.Buffer)
tee := io.TeeReader(bytes.NewReader(bodyBytes), bodyBuffer)
firstLine := make([]byte, 200) // 读取前 200 字节
n, _ := tee.Read(firstLine)
logError("First part of upload pack request body: %s\n", string(firstLine[:n]))
logError("Error decoding upload pack request: %v, repo: %s\n", err, repoName)
c.Error(err) // 使用 Hertz 的 Error Handling
_, errResp := c.WriteString(err.Error())
if errResp != nil {
logError("WriteString error: %v\n", errResp)
}
c.Status(http.StatusInternalServerError)
return
}
ep, err := transport.NewEndpoint("/")
if err != nil {
logError("Error creating endpoint: %v, repo: %s\n", err, repoName)
c.Error(err) // 使用 Hertz 的 Error Handling
_, errResp := c.WriteString(err.Error())
if errResp != nil {
logError("WriteString error: %v\n", errResp)
}
c.Status(http.StatusInternalServerError)
return
}
bfs := osfs.New(dir)
ld := gitserver.NewFilesystemLoader(bfs, false)
svr := gitserver.NewServer(ld)
sess, err := svr.NewUploadPackSession(ep, nil)
if err != nil {
logError("Error creating upload pack session: %v, repo: %s\n", err, repoName)
c.Error(err) // 使用 Hertz 的 Error Handling
_, errResp := c.WriteString(err.Error())
if errResp != nil {
logError("WriteString error: %v\n", errResp)
}
c.Status(http.StatusInternalServerError)
return
}
res, err := sess.UploadPack(ctx, upr) // 使用 context.Context
if err != nil {
_, errResp := c.WriteString(err.Error())
if errResp != nil {
logError("WriteString error: %v\n", errResp)
}
logError("Error during upload pack: %v, repo: %s\n", err, repoName)
c.Status(http.StatusInternalServerError)
return
}
pr, pw := io.Pipe()
go func() {
defer pw.Close()
err = res.Encode(pw)
if err != nil {
logError("Error encoding upload pack result: %v, repo: %s\n", err, repoName)
_, errResp := c.WriteString(err.Error())
if errResp != nil {
logError("WriteString error: %v\n", errResp)
}
c.Status(http.StatusInternalServerError)
return
}
}()
c.SetBodyStream(pr, -1)
}
*/