1. 程式人生 > >基於 xorm 的服務端框架 XGoServer

基於 xorm 的服務端框架 XGoServer

加密 iter router com mux develop 目錄 func 基礎

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

掘金: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 框架
  • 多路 gorutine 設計,增加並發性能
  • 服務端通用的輸出數據結構的整合,例如 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
    }
}

多路 gorutine 設計,增加並發性能

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)
}

就介紹這麽多了

基於 xorm 的服務端框架 XGoServer