Skip to content

Commit

Permalink
feat: web ui support
Browse files Browse the repository at this point in the history
  • Loading branch information
xxxsen committed Jan 4, 2024
1 parent 1480165 commit 0abcf2f
Show file tree
Hide file tree
Showing 6 changed files with 217 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func main() {
handler.WithFakeS3BucketList(c.FakeS3Info.BucketList),
handler.WithEnableRefererCheck(c.RefererInfo.Enable),
handler.WithRefererList(c.RefererInfo.Referer),
handler.WithEnableWebUI(c.EnableWebUI),
)),
cgi.WithAttach(constants.KeyStorageClient, fs),
)
Expand Down
1 change: 1 addition & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type Config struct {
IOInfo IOConfig `json:"io_info"`
FakeS3Info FakeS3Config `json:"fake_s3_info"`
RefererInfo RefererConfig `json:"referer_info"`
EnableWebUI bool `json:"enable_webui"`
}

func Parse(f string) (*Config, error) {
Expand Down
7 changes: 7 additions & 0 deletions handler/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type config struct {
fakeS3Buckets []string
enableRefererCheck bool
referers []string
enableWebUI bool
}

type Option func(c *config)
Expand Down Expand Up @@ -61,3 +62,9 @@ func WithRefererList(v []string) Option {
c.referers = v
}
}

func WithEnableWebUI(v bool) Option {
return func(c *config) {
c.enableWebUI = v
}
}
9 changes: 9 additions & 0 deletions handler/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ import (
"fileserver/handler/s3"
"fileserver/proto/fileserver/fileinfo"
"fileserver/utils"
"fileserver/web"
"fmt"

"github.com/xxxsen/common/cgi"
"github.com/xxxsen/common/cgi/codec"

_ "embed"

"github.com/gin-gonic/gin"
)

Expand All @@ -37,6 +40,12 @@ func OnRegist(router *gin.Engine, opts ...Option) {
refererMiddleware := middlewares.RefererMiddleware(c.enableRefererCheck, c.referers)

router.Use(refererMiddleware)
//index
if c.enableWebUI {
indexRouter := router.Group("/")
indexRouter.GET("/", web.Index)
}

//upload
{
uploadRouter := router.Group("/upload", authMiddleware, uploadLimitMiddleware)
Expand Down
185 changes: 185 additions & 0 deletions web/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传</title>
<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}

#login-container,
#upload-container,
#result-container {
text-align: center;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
background-color: #f8f8f8;
}

#file {
margin-top: 10px;
}

hr {
border: 1px solid #ccc;
width: 90%;
margin: 20px auto;
}
</style>
</head>

<body>
<div id="login-container">
<label for="username">用户名:</label>
<input type="text" id="username" placeholder="请输入用户名">
<br><br>
<label for="password">密码:</label>
<input type="password" id="password" placeholder="请输入密码">
<br><br>
<button onclick="saveCredentials()">保存用户名密码</button>
</div>

<div id="upload-container" style="display: none">
<form action="/upload/file" method="post" enctype="multipart/form-data" id="upload-form">
<label for="file">选择文件:</label>
<br>
<input type="file" id="file" name="file" accept="*.*">
<br><br>
<input id="upload-btn" type="submit" value="上传文件">
</form>
<hr>
<div>
<label for="note">其他功能:</label>
<button onclick="resetCredentials()">重设token</button>
</div>
</div>

<div id="result-container" style="display: none;">
<div id="down-key-container" style="display: block;">
<label for="downKey">文件下载链接:</label>
<input type="text" id="downKey" readonly>
<br>
<button onclick="copyDownKey()">复制链接</button>
<button onclick="goBack()">返回</button>
</div>
</div>
<script>
// 检查本地存储中是否有保存的用户名和密码
var storedUsername = localStorage.getItem('username');
var storedPassword = localStorage.getItem('password');

if (storedUsername && storedPassword) {
// 如果有保存的用户名和密码,将其填充到输入框中
document.getElementById('username').value = storedUsername;
document.getElementById('password').value = storedPassword;
setContainerVisible('login-container', false)
setContainerVisible('upload-container', true)
}


document.getElementById('upload-form').addEventListener('submit', function (event) {
event.preventDefault();
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var uploadBtn = document.getElementById('upload-btn')
uploadBtn.value = '上传中, 请等待上传完成...'
uploadBtn.disabled = true
// 模拟服务器返回的 JSON 数据
// 在实际应用中,你应该将以下代码替换为实际的异步请求
fetch('/upload/file', {
method: 'POST',
body: new FormData(this),
headers: {
'Authorization': 'Basic ' + btoa(username + ':' + password)
},
}).then(response => {
if (!response.ok) {
alert('文件上传失败, HTTP状态码:' + response.status)
throw new Error(`invalid http status code: ${response.status}`);
}
return response.json();
}).then(data => {
// 处理服务器返回的 JSON 数据
handleResponse(data);
}).catch(error => {
console.error('发生错误:', error.message);
// 在这里可以处理HTTP错误或其他异常
}).finally(_ => {
uploadBtn.value = '上传文件'
uploadBtn.disabled = false
});
});

function handleResponse(responseData) {
if (responseData.code === 0) {
// 如果 code 为 0,表示成功
setContainerVisible('upload-container', false)
setContainerVisible('result-container', true)
document.getElementById('downKey').value = window.location.href + 'file?down_key=' + responseData.data.down_key;
} else {
// 如果 code 不为 0,表示失败
alert('文件上传失败, 业务错误码:' + responseData.code + ', 错误信息:' + responseData.message)
goBack()
}
}

function copyDownKey() {
var downKeyInput = document.getElementById('downKey');
downKeyInput.select();
document.execCommand('copy');
alert('链接已复制到剪贴板!');
}

function goBack() {
// 此处可以根据需要实现返回逻辑
setContainerVisible('result-container', false)
setContainerVisible('upload-container', true)
}
function saveCredentials() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;

// 保存用户名和密码到本地存储
localStorage.setItem('username', username);
localStorage.setItem('password', password);

alert('用户名和密码已保存!');
setContainerVisible('upload-container', true)
setContainerVisible('login-container', false)
}

function setContainerVisible(name, v) {
var ct = document.getElementById(name)
setv = 'none'
if (v) {
setv = 'block'
}
ct.style.display = setv
}

function setContainerEnabled(name, v) {
var ct = document.getElementById(name)
ct.style.enabl
}

function resetCredentials() {
setContainerVisible('upload-container', false)
setContainerVisible('login-container', true)
document.getElementById('username').value = '';
document.getElementById('password').value = '';
localStorage.removeItem('username')
localStorage.removeItem('password')
}
</script>

</body>

</html>
14 changes: 14 additions & 0 deletions web/web.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package web

import (
_ "embed"

"github.com/gin-gonic/gin"
)

//go:embed index.html
var content string

func Index(c *gin.Context) {
c.Writer.Write([]byte(content))
}

0 comments on commit 0abcf2f

Please sign in to comment.