基于 xorm 的服务端框架 XGoServer

简介: 作者:林冠宏 / 指尖下的幽灵 掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8 博客:http://www.cnblogs.com/linguanh/ GitHub : https://github.

作者:林冠宏 / 指尖下的幽灵

掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8

博客:http://www.cnblogs.com/linguanh/

GitHub : https://github.com/af913337456/

腾讯云专栏: https://cloud.tencent.com/developer/user/1148436/activities


开源地址:https://github.com/af913337456/XGoServer

你可以使用它

  • 简单快速搭建自己的服务端
  • 高级模块拓展,例如 jwt,token模块。数据加密传输等

具备的

  • 日志模块,alecthomas/log4go
  • 路由模块,gorilla/mux
  • 硬存储 / 软存储 采用 xorm 框架
  • 服务端通用的输出数据结构的整合,例如 json
如果你想直接输出一条 json 给客户端,这样子
func main()  {
    router := new (mux.Router)
    router.HandleFunc("/",test2).Methods("GET")
    core.HttpListen(router) 
}
func test2(w http.ResponseWriter,r *http.Request)  {
    // 非常简单的例子, 操作放在内部 , 可以使用 request 来获取自己的参数,再直接组织输出
    core.HandlerMapWithOutputJson(w, func() map[string]interface{} {
        m :=  map[string]interface{}{}
        m["msg"] = "blow me a kiss"
        return m
    })
}
// 结果 : {"msg":"blow me a kiss"}
与数据库交互
func test3(w http.ResponseWriter,r *http.Request)  {
    core.HandlerMapWithOutputJson(w, func() map[string]interface{} {
        // 插入一条评论
        item := &model.Comment{
            Id  :util.NewId(),         // 评论 id
            UserId  :"123456",             // 评论人 id
            Name    :"LinGuanHong",        // 评论人名称
            Content :"hello word",         // 评论内容
        }
        affect,_ := core.Engine.Insert(item)  // 执行插入,传入 struct 引用
        m :=  map[string]interface{}{}
        if affect > 0 {
            m["ret"] = "insert success"
            comments := make([]model.Comment, 0)
            core.Engine.Find(&comments)   // select 出来,获取所有评论输出
            m["msg"] = comments
        }else{
            m["ret"] = "insert failed"
        }
        return m
    })
}

输出的结果是:
{
  "msg": [
    {
      "id": "1kubpgh9pprrucy11e456fyytw",
      "UserId": "123456",
      "name": "LinGuanHong",
      "content": "hello word"
    }
  ],
  "ret": "insert success"
}

使用流程

目录如下

---- config
---- core
---- model
---- threeLibs
---- util
---- server.go

1 在 config 放置配置文件

  • 服务端配置 json 文件 -- server.json,
  • 日志配置文件 -- log.json 例如下面的,他们都会在运行程序后会自动解析和读取

2 threeLibs 目录放置了依赖的第三方库,例如 xorm,不需要你再去 go get

3 model 放置数据实体 struct

{
  "Host": "127.0.0.1",
  "Port": ":8884",
  "FilePort":":8885",
  "DbName":"lgh",
  "DbUser":"root",
  "DbPw":"123456",
  "DbPort":"3306"
}
{
  "EnableConsole": true,
  "ConsoleLevel": "DEBUG",
  "EnableFile": true,
  "FileLevel": "INFO",
  "FileFormat": "",
  "FileLocation": ""
}

从一个最基础的例子开始:

func main()  {
    router := new (mux.Router)
    router.HandleFunc("/",test).Methods("GET")
    /** 在下面添加你的路由 */
    /** add your routine func below */ 
    core.HttpListen(router)  // 简单的 http 监听,当然也提供了 https
}
func test(w http.ResponseWriter,r *http.Request)  {
    fmt.Fprintf(w,"======= hello world! =======")
}
// http 监听
func HttpListen(router *mux.Router)  {
    SimpleInit()  // 此处自动初始化 ---------- ①
    url := config.ServerConfig.Host+config.ServerConfig.Port
    util.LogInfo("服务启动于 : "+url)
    err := http.ListenAndServe(url,router)
    if err !=nil {
        util.LogInfo("http error ===> : "+err.Error())
        return
    }
}
// 绑定配置 json 的信息 以及 初始化 xorm mysql数据库引擎
func SimpleInit() bool {
    if config.BindServerConfig() {
        fmt.Println("BindServerConfig ==================> success")
        config.ConfigureLog(&config.LogConfig)
        CreateDefaultMysqlEngine(
            "mysql",
            config.ServerConfig.DbUser,
            config.ServerConfig.DbPw,
            config.ServerConfig.DbName)
        return true
    }else{
        fmt.Println("BindServerConfig ===> failed")
        return false
    }
}

服务端通用的输出数据结构的整合函数

type FinalResult struct {
    Data interface{}
}

type RetChannel chan FinalResult

func HandlerStruct(handle func() interface{}) *interface{} {
    RetChannel := make(RetChannel, 1)
    go func() {
        result := FinalResult{}
        data := handle()
        result.Data = &data
        RetChannel <- result
        close(RetChannel)
    }()
    ret := <-RetChannel
    return ret.Data.(*interface{})
}

func HandlerMap(handle func() map[string]interface{}) *map[string]interface{} {
    RetChannel := make(RetChannel, 1)
    go func() {
        result := FinalResult{}
        data := handle()
        result.Data = &data
        RetChannel <- result
        close(RetChannel)
    }()
    ret := <-RetChannel
    return ret.Data.(*map[string]interface{})
}

func HandlerStructWithOutputJson(w http.ResponseWriter,handle func() interface{})  {
    RetChannel := make(RetChannel, 1)
    go func() {
        result := FinalResult{}
        data := handle()
        result.Data = &data
        RetChannel <- result
        close(RetChannel)
    }()
    ret := <-RetChannel
    mapRet := ret.Data.(*interface{})
    util.RenderJson(w,mapRet)
}

func HandlerMapWithOutputJson(w http.ResponseWriter,handle func() map[string]interface{}){
    RetChannel := make(RetChannel, 1)
    go func() {
        result := FinalResult{}
        data := handle()
        result.Data = &data
        RetChannel <- result
        close(RetChannel)
    }()
    ret := <-RetChannel
    mapRet := ret.Data.(*map[string]interface{})
    util.RenderJson(w,mapRet)
}

就介绍这么多了

如果您认为这篇文章还不错或者有所收获,您可以通过扫描一下下面的支付宝二维码 打赏我一杯咖啡【物质支持】,也可以点击右下角的【推荐】按钮【精神支持】,因为这两种支持都是我继续写作,分享的最大动力

、
img_12e3f54d4d0f70f0eb14f20548e3d781.png
目录
相关文章
|
9天前
|
域名解析 人工智能 Linux
|
19天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
17716 63
|
17天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
3天前
|
人工智能 安全 网络安全
|
7天前
|
云安全 数据采集 人工智能
|
8天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1399 5
|
14天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2446 8
|
19天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
3971 22
|
21天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是DeepSeek AI开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、跑命令、处理表格、联网搜索等操作。免费开源,兼容Windows/macOS/Linux,提供桌面端与网页端,可灵活安装插件扩展能力。

热门文章

最新文章