0
0
Fork 0

initial commit for routing

This commit is contained in:
Gibheer 2014-07-22 21:27:39 +02:00
parent 2bea1df808
commit 7a5cbc3c7a
4 changed files with 89 additions and 0 deletions

10
controller/controller.go Normal file
View File

@ -0,0 +1,10 @@
package controller
import (
"github.com/gibheer/zero-blog/lib"
"github.com/gibheer/zero-blog/controller/welcome"
)
func DefineRoutes(router *lib.Router) {
router.Get("/", welcome.Welcome)
}

View File

@ -0,0 +1,11 @@
package welcome
import (
"fmt"
"github.com/gibheer/zero-blog/lib"
)
func Welcome(c *lib.Context) error {
fmt.Fprint(c.Response, "Hello World!")
return nil
}

56
lib/router.go Normal file
View File

@ -0,0 +1,56 @@
package lib
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
// Bundle all parameters into the context to make it easier to push important
// data into functions.
type Context struct {
Request *http.Request
Response http.ResponseWriter
params httprouter.Params
}
// the func type for internal routes
type ContextFunc func(*Context) error
type Router struct {
router *httprouter.Router
}
func NewRouter() *Router {
return &Router{httprouter.New()}
}
func (r *Router) Get(path string, target ContextFunc) {
r.addRoute("GET", path, target)
}
func (r *Router) Post(path string, target ContextFunc) {
r.addRoute("POST", path, target)
}
func (r *Router) Put(path string, target ContextFunc) {
r.addRoute("PUT", path, target)
}
func (r *Router) Delete(path string, target ContextFunc) {
r.addRoute("DELETE", path, target)
}
func (r *Router) addRoute(method, path string, target ContextFunc) {
r.router.Handle(method, path, func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
log.Println("Handling Request for ", path)
if err := target(&Context{r, w, p}); err != nil {
log.Fatal(err)
}
})
}
func (r *Router) Start() {
log.Print("Starting to listen for incoming requests ...")
log.Fatal(http.ListenAndServe(":9292", r.router))
}

12
main.go Normal file
View File

@ -0,0 +1,12 @@
package main
import (
"github.com/gibheer/zero-blog/lib"
"github.com/gibheer/zero-blog/controller"
)
func main() {
router := lib.NewRouter()
controller.DefineRoutes(router)
router.Start()
}