// Init func (app *Application) Init(path string) { // Load config file r := map[string]string{"{WorkingDir}": console.WorkingDir} console.NewConfig(path).Replace(r).Parse(app) // Default Listen if app.Listen == "" { app.Listen = ":80" } // Default module if app.Modules == nil { app.Modules = make(map[string]Module) } // Default host if app.Hosts == nil { app.Hosts = make(map[string]Host) } if _, ok := app.Hosts["Public"]; !ok { app.Hosts["Public"] = Host{Path: "/", Root: console.WorkingDir + "/public"} } // Module property for k, v := range app.Modules { // app.Modules[k].Listen = app.Listen // cannot assign to p.Modules[k].Listen v.Name = k if v.Listen == "" { v.Listen = app.Listen } // db.Connections if v.DB.Follow != "" { v.DB = app.Modules[v.DB.Follow].DB } if v.DB.DSN != "" { db.Servers[v.DB.Name] = &v.DB } app.Modules[k] = v } // Host property for k, v := range app.Hosts { v.Name = k if v.Listen == "" { v.Listen = app.Listen } app.Hosts[k] = v } //log.Printf("%#v\n", app) console.Dump(app) //log.Printf("%#v\n", controllers) console.Dump(controllers) }
//Every request run this function func NewHandler(fn ActionLoadFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { defer func() { if r := recover(); r != nil { log.Printf(r.(string)) http.Error(w, r.(string), http.StatusOK) } }() req := NewRequest(r) fmt.Print("\n\n") console.Dump(req) cm, ok := controllers[req.Module] if !ok { panic(fmt.Sprintf("Controller [%s] not found\n", req.Module)) } controller, ok := cm[req.Controller+"Controller"] if !ok { panic(fmt.Sprintf("Controller [%s::%s] not found\n", req.Module, req.Controller)) } //Invoke Load() if fn != nil { if inited := fn(req); inited.Data.(int) < 0 { panic(fmt.Sprintf("Load falure: %s\n", inited.Err)) } } rq := controller.Elem().FieldByName("Request") rq.Set(reflect.ValueOf(req)) method := req.Action //action action := controller.MethodByName(method) if action.IsValid() == false { panic(fmt.Sprintf("Method [%s] not found\n", method)) } log.Printf("Method [%s] found\n", method) typ := action.Type() numIn := typ.NumIn() if len(req.args) < numIn { panic(fmt.Sprintf("Method [%s]'s in arguments wrong\n", method)) } // Arguments in := make([]reflect.Value, numIn) for i := 0; i < numIn; i++ { actionIn := typ.In(i) kind := actionIn.Kind() v, err := parameterConversion(req.args[i], kind) if err != nil { panic(fmt.Sprintf("%s paramters error, string convert to %s failed: %s\n", method, kind, req.args[i])) } in[i] = v req.Args[actionIn.Name()] = v } // Run... ret := action.Call(in) // JSON Marshal v, err := json.Marshal(ret[0].Interface()) if err != nil { panic(fmt.Sprintf("json.Marshal: %v\n", err)) } // Render _, err = w.Write(v) if err != nil { panic(fmt.Sprintf("ResponseWriter.Write: %v\n", err)) } } }