Irv
Irv

Reputation: 1

PHP to Go. How should I structure my projects?

I'm learning Go with PHP being my best out of my pool (my pool is a kiddie pool: HTML, CSS, PHP, JavaScript, SQL). I've never actually gotten into the big scary ones like C, C++, etc. I thought Go would be a fair start.

Let's say I have the structure:

|App
|server.go
----|Controllers
-------|main.go

In PHP including one file means you have access to things on the parent file and all previous files that have been included.(depending on a couple of things, but for the most part).

In Go, if I have this in server.go

package main

import (
    "REST/Controllers"
    "fmt"
)

type test struct {
    Number int
}

var TestVar = test{}

func main() {
    controllers.Log()
}

Is it possible to access TestVar in my Controller/main.go? I've tried but I can't seem to find how. The following code throws an undefined var error:

main.go

package controllers

import (
    "fmt"
)

func Log() {
    fmt.Printf("%q", TestVar)
}

My only other idea is to pass it down through a function, but what if I want to actually change a value in TestVar? I'm not that far into the language, so I don't know much about pointers and all of that. And if I have 10 variables, wouldn't passing 10 variables to a function every time become too much of a hassle?

Remember I'm from PHP, so pretty much all of the dirty stuff was sugarcoated for me.

Thanks for the help.

Upvotes: 0

Views: 371

Answers (2)

kostix
kostix

Reputation: 55473

Please read the following material first:

Then look at how, say, thesrc project is structured.

Try out tutorials — just google for golang+webapp+tutorials.

Upvotes: 2

Taco de Wolff
Taco de Wolff

Reputation: 1758

To expand on what @SirDarius said to not over-organize your code structure.

It is customary for Go projects to have one directory with sources. Each file is like a module and can be quite long in terms of lines. Each directory is a project, also sub-directories! They are sub-projects.

Following that thought, is Controllers a sub-project? No, it's part of the actual project. So put that in the parent directory. If you have some code that could be reused outside of this package you make a new package or a sub-package (whichever fits best).

Generally, simplify! Don't create directories to organize similar functionality, but group them by putting them into one file.

In your case, have main.go and log.go in the root directory. Unless you want to create a generalized logging package, then create a directory called log containing main.go. But this would be an independent package so it wouldn't need to get variables from another or parent package. If you seem to need that var anyways, pass it as a configuration.

Upvotes: 0

Related Questions