添加配置文件功能

This commit is contained in:
Kakune55 2023-12-21 09:22:22 +08:00
parent 4dde2ba1ab
commit d701f59a4e
3 changed files with 114 additions and 65 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
/data
user.json

44
config/load.go Normal file
View File

@ -0,0 +1,44 @@
package config
import (
"encoding/json"
"os"
)
type User struct {
Listen string `json:"listen"`
}
func ReadConfig(filePath string) (User, error) {
// 检查文件是否存在
if _, err := os.Stat(filePath); os.IsNotExist(err) {
// 文件不存在创建一个新的JSON文件
user := User{Listen: ":9090"}
data, err := json.Marshal(user)
if err != nil {
return User{}, err
}
err = os.WriteFile(filePath, data, 0644)
if err != nil {
return User{}, err
}
}
// 读取文件内容
data, err := os.ReadFile(filePath)
if err != nil {
return User{}, err
}
// 解析JSON数据
var user User
err = json.Unmarshal(data, &user)
if err != nil {
return User{}, err
}
return user, nil
}
//如何调用
//---------------------------------------
// filePath := "user.json"
// // 读取配置文件
// user, err := ReadConfig(filePath)
// if err != nil {
// fmt.Println("读取配置文件失败:", err)
// }

14
main.go
View File

@ -1,6 +1,7 @@
package main
import (
"Pixel/config"
"Pixel/database"
"crypto/md5"
"encoding/json"
@ -20,7 +21,6 @@ import (
"github.com/disintegration/imaging"
)
func init() {
const appinfo string = `
@ -61,8 +61,14 @@ func init() {
fmt.Println("数据库初始化完成")
}
func main() {
filePath := "user.json"
// 读取配置文件
config, err := config.ReadConfig(filePath)
if err != nil {
fmt.Println("读取配置文件失败:", err)
}
http.HandleFunc("/info", showimg)
http.HandleFunc("/info/list", showlist) //
http.HandleFunc("/upload", upload) //上传图片
@ -72,7 +78,7 @@ func main() {
http.HandleFunc("/img/del", deleteImagesHandler) //删除相应图片
http.HandleFunc("/login", login) //登录页
fmt.Println("Web服务器已启动")
err := http.ListenAndServe(":9090", nil) //设置监听的端口
err = http.ListenAndServe(config.Listen, nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
@ -95,7 +101,6 @@ func showlist(w http.ResponseWriter, r *http.Request) {
t.Execute(w, "Hello")
}
// 处理/upload 逻辑
func upload(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // 获取请求的方法
@ -153,7 +158,6 @@ func upload(w http.ResponseWriter, r *http.Request) {
}
}
func RandomString(n int) string {
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
bytes := make([]byte, n)