-3

My goal is to encapsulate in one module/package.

Main package:

package main

import (
  "github.com/zenazn/goji"
  "./routes"
)

func main(){
  routes.Setup()
  goji.Serve()
}

And another package:

package routes

import "github.com/zenazn/goji"

func Setup() {
    goji.Get("/static", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "static!")
    })
}

How can I do this?

Jan Carlo Viray
  • 11,856
  • 11
  • 42
  • 63

2 Answers2

4

goji, in your example, is a package. Not a variable.

You cannot pass packages around like this.
If you look at the example on the goji github page

You simply just call goji.Get from your Init function, and goji.Serve from your main

route.go

package route
import "route"
import "github.com/zenazn/goji"
func Init(){
    goji.Get("/hello/:name", hello)
}

main.go

package main
import "github.com/zenazn/goji"
func main(){
    route.Init()
    goji.Serve()
}
David Budworth
  • 11,248
  • 1
  • 36
  • 45
3

Packages in go export constants, variables, types and functions that have uppercase letters as their name. The package itself is not something directly manipulatable by the program.

The package goji should be exporting a variable named something like goji.Goji if you want to directly access it from other packages. A better solution is to provide some functions in the package that allow you to register your functions/helpers.

You could also export a function from goji like:

func Set(s string, func(w http.ResponseWriter, r *http.Request)) { ... }

that could be used by other packages:

goji.Set("/static", myFunc)

The error you had "use of package goji without selector" is saying you can't use the name of the package without specifying which exported value you want from the package. It's expecting goji.something not goji by itself.

The function init() inside go files has special properties: see http://golang.org/ref/spec#Program_initialization_and_execution

AndrewN
  • 701
  • 3
  • 10
  • thanks. your answer gave me more insight about Go and packages. – Jan Carlo Viray Sep 13 '14 at 16:50
  • 1
    Packages get linked into your program exactly once. You can import the same package in multiple files and be assured that the variable `packageName.Var` is the same everywhere. – AndrewN Sep 13 '14 at 17:02
  • 1
    Where to define routes seems to have tripped up a few folks who moved to Go. If you want to set up routes from the same package where you define each view, call the route-setup function (`goji.Set` here) in the packages' `init()` functions. If a single package should define all your routes, it can be `main` or some other toplevel package that imports all of the packages that define views. You also might lump more into one package in Go than other langs. [Here's a general q. on package deps](http://stackoverflow.com/questions/20380333/cyclic-dependencies-and-interfaces-in-golang) if it helps. – twotwotwo Sep 13 '14 at 21:27