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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀