2012년 2월 16일 목요일

routing module을 만들자 - handler

callback을 바로 넣을 수는 없어보이고
type 에 func 을 정의하고 달면 된다.
나름 명시적이네.

역시 소스는 여기

package main

import (
  "fmt"
)

type Handler func(method string)

type Route struct {
  Method,Pattern string
}

type Routes struct {
  Routes []Route
}
func (r Routes) routeCount() int {
  return len(r.Routes)
}
func (r *Routes) addRoute(method, pattern string, handler Handler) {
  r.Routes=append(r.Routes, Route{Method:method, Pattern:pattern})
  fmt.Printf("route Count : %d\n", len(r.Routes))
  handler(method)
}
func (r *Routes) GET(pattern string, handler Handler) {
  r.addRoute("GET", pattern, handler)
}
func (r *Routes) POST(pattern string, handler Handler) {
  r.addRoute("POST", pattern, handler)
}
func (r *Routes) PUT(pattern string, handler Handler) {
  r.addRoute("PUT", pattern, handler)
}
func (r *Routes) DELETE(pattern string, handler Handler) {
  r.addRoute("DELETE", pattern, handler)
}
func handler(method string) {
  fmt.Printf("%s handler executed \n", method)
}

func main() {
  r:=new(Routes)
  r.GET("/user/:user", handler)
  r.PUT("/add/:user", handler)
  r.POST("/update/:user", handler)
  r.DELETE("/delete/:user", handler)
  for _,v:=range r.Routes {
    fmt.Printf("%s:%s\n",v.Method, v.Pattern)
  }
}


------
의도는 이게 아닌데 빨리 무엇이든 달아보고 싶었다.

route Count : 1
GET handler executed 
route Count : 2
PUT handler executed 
route Count : 3
POST handler executed 
route Count : 4
DELETE handler executed 
GET:/user/:user
PUT:/add/:user
POST:/update/:user
DELETE:/delete/:user