Files
bl/common/data/xml/talk/talk.go

90 lines
2.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package xml
import (
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/ECUST-XX/xml" // 注意需确保该xml库与示例中使用的一致
)
func getxml() ([]byte, error) {
// 读取整个文件内容,返回字节切片和错误
content, err := ReadHTTPFile("http://127.0.0.1:8080/assets/talk_count.xml")
if err != nil {
// 处理错误(文件不存在、权限问题等)
log.Fatalf("无法读取文件: %v", err)
}
return content, nil
}
// TalkCount 根节点,对应<talk_count>标签
// 注意xml.Name需指定命名空间与XML中的xmlns保持一致
type TalkCount struct {
XMLName xml.Name `xml:"nieo.seer.org.talk-count talk_count"`
Entries []Entry `xml:"entry"` // 包含所有entry节点
}
// Entry 单个条目配置,对应<entry>标签
type Entry struct {
ID int `xml:"id,attr"` // 条目ID
ItemID int `xml:"item_id,attr"` // 物品ID
ItemMinCount int `xml:"item_min_count,attr"` // 物品最小数量
ItemMaxCount int `xml:"item_max_count,attr"` // 物品最大数量
Desc string `xml:"desc,attr"` // 描述信息
Count int `xml:"count,attr"` // 计数
Policy string `xml:"policy,attr,omitempty"` // 策略可选如week
}
// 复用示例中的ReadHTTPFile函数读取远程文件
func ReadHTTPFile(url string) ([]byte, error) {
client := &http.Client{
Timeout: 30 * time.Second,
}
resp, err := client.Get(url)
if err != nil {
return nil, fmt.Errorf("请求失败: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("请求返回非成功状态码: %d", resp.StatusCode)
}
content, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取内容失败: %w", err)
}
return content, nil
}
// 获取XML内容可根据实际URL修改
func getTalkCountXML() ([]byte, error) {
// 注意此处URL需替换为实际的talk_count.xml文件地址
content, err := ReadHTTPFile("http://127.0.0.1:8080/assets/talk_count.xml")
if err != nil {
log.Fatalf("无法读取文件: %v", err)
}
return content, nil
}
// 解析XML到结构体
func getTalkCount() TalkCount {
var talkCount TalkCount
content, _ := getTalkCountXML()
// 解析XML时需注意命名空间匹配
if err := xml.Unmarshal(content, &talkCount); err != nil {
log.Fatalf("XML解析失败: %v", err)
}
return talkCount
}
// 全局配置变量,用于存储解析后的结果
var TalkCountConfig = getTalkCount()