dongtong5242 2016-08-28 09:18
浏览 67
已采纳

Golang MVC结构

I searched many sites and I saw a lot of sources in GitHub and I haven't found a solution.

I created an MVC website pattern in Golang:

  • app
    • controllers
    • models
    • lib (All the features class/functions)
    • middleware
    • router.go
  • resources
    • views
  • main.go

My question is: How to inject config to have everywhere settings and other implemented class that will always be needed (like load speed single page).

One more thing(additionally): Can anyone recommend me a good material or transcribe MVC tricks idea works MVC with Golang (General useful information).

  • 写回答

1条回答 默认 最新

  • dougutuo9879 2016-08-28 14:25
    关注

    You can have one file called for example MainController where you can make functions for accessing database, sessions, config files and so on. All you have to do really from there is to say something like this for example (inherit stuff from some other controller):

    //MyController.go
    type App struct {
        MainController
    }
    
    func (c Application) MyControllerFunc() returnTypeHere(http.Response for example) {
    
        //c.getDatabaseName is function from MainController that reads information from some plain text file or json file or similar
        someInfoFromConfigFile = c.getDatabaseName()
        var str []string
        str = append(str,  someInfoFromConfigFile)
    
        //RenderJson is function that render http response as json (Content type plain/json)
        return c.RenderJson(str)
    }
    

    But if you need mvc I suggest that you use some framework (Revel for example). I am using it all the time. It gives you that basic mvc functionality if you like and all other stuff is really up to you. You keep you business logic in some helpers, models in models file etc.

    You can check Revel main controller structure here: https://github.com/revel/revel/blob/master/controller.go

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵