implementable controller working + HTTP response writing

This commit is contained in:
Adrien Marquès 2018-06-01 11:07:34 +02:00
parent ca05b7ff29
commit 364481d3f3
3 changed files with 22 additions and 13 deletions

View File

@ -5,7 +5,8 @@ import (
"sync"
)
type Controller func(map[string]interface{}) *Response
type Arguments map[string]interface{}
type Controller func(map[string]interface{}, *Response) Response
type Response struct {
data map[string]interface{}

View File

@ -93,10 +93,10 @@ func FetchFormData(req *http.Request) map[string]interface{} {
// LoadController tries to load a controller from its uri
// checks for its given method ('Get', 'Post', 'Put', or 'Delete')
func (i *Request) LoadController(method string) (implement.Controller, error) {
func (i *Request) LoadController(method string) (func(implement.Arguments, *implement.Response) implement.Response, error) {
/* (1) Build controller path */
path := fmt.Sprintf("%si.so", i.Path)
path := fmt.Sprintf("./controllers/%si.so", strings.Join(i.Path, "/"))
/* (2) Format url */
tmp := []byte(strings.ToLower(method))
@ -104,7 +104,6 @@ func (i *Request) LoadController(method string) (implement.Controller, error) {
method = string(tmp)
fmt.Printf("method is '%s'\n", method)
return nil, nil
/* (2) Try to load plugin */
p, err2 := plugin.Open(path)
@ -119,10 +118,11 @@ func (i *Request) LoadController(method string) (implement.Controller, error) {
}
/* (4) Check signature */
callable, validSignature := m.(implement.Controller)
callable, validSignature := m.(func(implement.Arguments, *implement.Response) implement.Response)
if !validSignature {
return nil, fmt.Errorf("Invalid signature for method %s", method)
}
fmt.Printf("callable is %v\n", callable)
return callable, nil

View File

@ -1,9 +1,11 @@
package gfw
import (
"encoding/json"
"fmt"
"git.xdrm.io/xdrm-brackets/gfw/config"
"git.xdrm.io/xdrm-brackets/gfw/err"
"git.xdrm.io/xdrm-brackets/gfw/implement"
"git.xdrm.io/xdrm-brackets/gfw/request"
"log"
"net/http"
@ -121,15 +123,21 @@ func (s *Server) route(res http.ResponseWriter, httpReq *http.Request) {
/* (6) Execute and get response
---------------------------------------------------------*/
resp := callable(parameters)
if resp != nil {
fmt.Printf("-- OUT --\n")
for name, value := range resp.Dump() {
fmt.Printf(" $%s = %v\n", name, value)
}
eJSON, _ := resp.Err.MarshalJSON()
fmt.Printf("-- ERR --\n%s\n", eJSON)
/* (1) Execute */
responseBarebone := implement.NewResponse()
response := callable(parameters, responseBarebone)
/* (2) Build JSON response */
formattedResponse := response.Dump()
formattedResponse["error"] = response.Err.Code
formattedResponse["reason"] = response.Err.Reason
if response.Err.Arguments != nil && len(response.Err.Arguments) > 0 {
formattedResponse["args"] = response.Err.Arguments
}
jsonResponse, _ := json.Marshal(formattedResponse)
res.Header().Add("Content-Type", "application/json")
res.Write(jsonResponse)
return
}