Golang Web Mvc Framework
Let us create a simple mvc project, show how goku work.
The project’s directory structure is like this:
.
├── app.go
└── gokudemo
├── config.go
├── controllers
│ └── home.go
├── model
├── routes.go
├── static
│ ├── css
│ ├── img
│ └── js
└── views
├── home
│ └── index.html
└── shared
└── layout.html
You can find this example in here.
An URL request like “http://www.abc.com/home/index” will map to home
controller’s index
action.
This was rewrite by the routes:
var Routes []*goku.Route = []*goku.Route{
&goku.Route{
Name: "static",
IsStatic: true,
Pattern: "/public/(.*)",
},
&goku.Route{
Name: "default",
Pattern: "/{controller}/{action}",
Default: map[string]string{"controller": "home", "action": "index"},
},
}
The static
route set IsStatic
to true, mean that if the url matched this route, will process the request as static file.
The default
route mean that the url /user/info
, will map to user
controller’s info
action, and the url /
will map to home
controller’s index
action, because this is the default value.
We register the routes to goku server by this way (app.go) :
func main() {
rt := &goku.RouteTable{Routes: gokudemo.Routes}
middlewares := []goku.Middlewarer{}
s := goku.CreateServer(rt, middlewares, gokudemo.Config)
log.Fatal(s.ListenAndServe())
}
Add a controller like this code(controllers/home.go):
package controllers
import (
"github.com/QLeelulu/goku"
)
// home controller
var _ = goku.Controller("home").
// index action
Get("index", func (ctx *goku.HttpContext) goku.ActionResulter {
ctx.ViewData["Message"] = "Hello World"
return ctx.View(nil)
})
This code register a home
controller, with a action named index
for http GET
methed, and add a viewdate Message
can be use in the view.
If the controllers register in the other packages, we must import it:
import _ "gokudemo/gokudemo/controllers"
we just import it but ignore it by _
.
In the home
controller’s index
action, we render view by return ctx.View(nil)
. This will find the view template file by the location /views/home/index.html
. And the default layout template is in /views/shared/layout.html
.
the layout.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Goku Demo</title>
</head>
<body>
<h1>Goku Demo</h1>
{{ template "body" . }}
</body>
</html>
the /views/home/index.html:
{{define "body"}}
{{.Data.Message}}
{{end}}
We get the data pass from the action in view by { {.Data.Message} }
.
$ go run app.go
2012/11/23 23:06:51 Server start on :8080
2012/11/23 23:07:13 D 200 GET /
2012/11/23 23:07:13 N 404 GET /favicon.ico
Now you can open a web-browser with the URL http://127.0.0.1:8080
to see what happen.