Idiomatic organization Go Code

Note. I have seen other issues related to this topic, but none of them address the issue.

I am trying to organize Go code. I am writing a daemon and I would like to split the code logically between files.

Say I have 3 files main.go:

package main

func main() {
    GlobalFunc()

    commonFunc()

    var svr server.Server
    server.OtherFunc()
}

server.go:

package main

type Server struct {
    name string
    ip string
}

func GlobalFunc() {

}

func (s *Server) OtherFunc() {
    commonFunc()
}

and common.go:

package main

func commonFunc() {

}

I would like to be able to call GlobalFunc()how server.GlobalFunc()to show its part of the "server module". This is not possible in the above example.

I could make a subdir server, put it there server.goand change it to package server. The problem here is that I cannot share common.gobetween the main and the serverpackage. I understand why this is also not a good idea.

So, did I miss something simple and complicate the situation?

Thank!

+4
1

, . , , . , , - , , tools, misc ..

, , , server.Run(). , , , , .

:

deamon/
    main.go
    server/server.go
    somelib/somelib.go -- to be included from main and server

, , , :

deamon/
   deamon.go -- package deamon
   deamond/
       main.go -- you may include the top level package as anyone else

, Go , "" , , , , .

+2

Source: https://habr.com/ru/post/1583828/


All Articles