本文整理匯總了Golang中github.com/app-kit/go-appkit.Registry類的典型用法代碼示例。如果您正苦於以下問題:Golang Registry類的具體用法?Golang Registry怎麽用?Golang Registry使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Registry類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: getIndexTpl
func getIndexTpl(registry kit.Registry) ([]byte, apperror.Error) {
if path := registry.Config().UString("frontend.indexTpl"); path != "" {
f, err := os.Open(path)
if err != nil {
return nil, apperror.Wrap(err, "index_tpl_open_error",
fmt.Sprintf("The index template at %v could not be opened", path))
}
tpl, err := ioutil.ReadAll(f)
if err != nil {
return nil, apperror.Wrap(err, "index_tpl_read_error",
fmt.Sprintf("Could not read index template at %v", path))
}
return tpl, nil
}
tpl := `
<html>
<body>
<h1>Go Appkit</h1>
<p>Welcome to your new appkit server.</p>
<p>
Find instructions on how to set up your app at <a href="http://github.com/app-kit/go-appkit">Github</a>
</p>
</body>
</html>
`
return []byte(tpl), nil
}
示例2: HandleFind
func HandleFind(registry kit.Registry, request kit.Request) (kit.Response, bool) {
collection := request.GetContext().MustString("collection")
res := registry.Resource(collection)
if res == nil || !res.IsPublic() {
err := &apperror.Err{
Code: "unknown_resource",
Message: fmt.Sprintf("The resource '%v' does not exist", collection),
}
return kit.NewErrorResponse(err), false
}
response, err := Find(res, request)
if err != nil {
response = kit.NewErrorResponse(err)
}
// If response contains a count and the request a "perPage" param, add a total_pages param
// to meta.
perPage, err2 := request.GetContext().Int("per_page")
meta := response.GetMeta()
if meta != nil && err2 == nil {
count, ok := meta["count"]
if ok {
meta["total_pages"] = math.Ceil(float64(count.(int)) / float64(perPage))
}
}
return response, false
}
示例3: notFoundHandler
func notFoundHandler(registry kit.Registry, r kit.Request) (kit.Response, bool) {
httpRequest := r.GetHttpRequest()
apiPrefix := "/" + registry.Config().UString("api.prefix", "api")
isApiRequest := strings.HasPrefix(httpRequest.URL.Path, apiPrefix)
// Try to render the page on the server, if enabled.
if !isApiRequest {
renderEnabled := registry.Config().UBool("serverRenderer.enabled", false)
noRender := strings.Contains(httpRequest.URL.String(), "no-server-render")
if renderEnabled && !noRender {
return serverRenderer(registry, r), false
}
}
// For non-api requests, render the default template.
if !isApiRequest {
tpl, err := getIndexTpl(registry)
if err != nil {
return kit.NewErrorResponse(err), false
}
return &kit.AppResponse{
RawData: tpl,
}, false
}
// For api requests, render the api not found error.
return &kit.AppResponse{
Error: &apperror.Err{
Code: "not_found",
Message: "This api route does not exist",
},
}, false
}
示例4: NewService
func NewService(debug bool, registry kit.Registry) *Service {
return &Service{
debug: debug,
registry: registry,
defaultBackend: registry.DefaultBackend(),
resources: make(map[string]kit.Resource),
}
}
示例5: HandleDelete
func HandleDelete(registry kit.Registry, request kit.Request) (kit.Response, bool) {
collection := request.GetContext().MustString("collection")
id := request.GetContext().MustString("id")
res := registry.Resource(collection)
if res == nil || !res.IsPublic() {
resp := kit.NewErrorResponse("unknown_resource", fmt.Sprintf("The resource '%v' does not exist", collection))
return resp, false
}
return res.ApiDelete(id, request), false
}
示例6: AuthenticationMiddleware
func AuthenticationMiddleware(registry kit.Registry, r kit.Request) (kit.Response, bool) {
// Handle authentication.
httpRequest := r.GetHttpRequest()
userService := registry.UserService()
if userService == nil {
return nil, false
}
authHeader := httpRequest.Header.Get("Authentication")
if authHeader == "" {
return nil, false
}
// Check for basic auth.
if strings.HasPrefix(authHeader, "Basic ") {
str := authHeader[6:]
data, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return kit.NewErrorResponse("invalid_basic_auth"), false
} else {
parts := strings.Split(string(data), ":")
if len(parts) == 2 {
userIdentifier := parts[0]
pw := parts[1]
user, err := userService.AuthenticateUser(userIdentifier, "password", map[string]interface{}{"password": pw})
if err != nil {
return kit.NewErrorResponse(err), false
}
r.SetUser(user)
return nil, false
}
}
}
// Check for auth token.
if authHeader != "" {
token := authHeader
user, session, err := userService.VerifySession(token)
if err == nil {
r.SetUser(user)
r.SetSession(session)
return nil, false
} else {
return kit.NewErrorResponse(err), false
}
}
return nil, false
}
示例7: ServerErrorMiddleware
func ServerErrorMiddleware(registry kit.Registry, r kit.Request, response kit.Response) (kit.Response, bool) {
err := response.GetError()
if err == nil {
return nil, false
}
status := 500
// If the error is an apperror, and it contains a status,
// set it as the http status of the response.
if apperr, ok := err.(apperror.Error); ok {
if apperr.GetStatus() != 0 {
status = apperr.GetStatus()
}
}
response.SetHttpStatus(status)
if response.GetRawData() != nil || response.GetRawDataReader() != nil {
return nil, false
}
httpRequest := r.GetHttpRequest()
apiPrefix := "/" + registry.Config().UString("api.prefix", "api")
isApiRequest := strings.HasPrefix(httpRequest.URL.Path, apiPrefix)
if isApiRequest {
return nil, false
}
data := map[string]interface{}{"errors": []error{response.GetError()}}
tpl := defaultErrorTpl()
tplPath := registry.Config().UString("frontend.errorTemplate")
if tplPath != "" {
t, err := template.ParseFiles(tplPath)
if err != nil {
registry.Logger().Fatalf("Could not parse error template at '%v': %v", tplPath, err)
} else {
tpl = t
}
}
var buffer *bytes.Buffer
if err := tpl.Execute(buffer, data); err != nil {
registry.Logger().Fatalf("Could not render error template: %v\n", err)
response.SetRawData([]byte("Server error"))
} else {
response.SetRawData(buffer.Bytes())
}
return nil, false
}
示例8: processRequest
func processRequest(registry kit.Registry, request kit.Request, handler kit.RequestHandler) (kit.Response, bool) {
var response kit.Response
// Run before middlewares.
for _, middleware := range registry.HttpFrontend().BeforeMiddlewares() {
var skip bool
response, skip = middleware(registry, request)
if skip {
return nil, true
} else if response != nil {
break
}
}
// Only run the handler if no middleware provided a response.
if response == nil {
skip := false
response, skip = handler(registry, request)
if skip {
return nil, true
}
}
if response.GetHttpStatus() == 0 {
// Note: error handler middleware will set proper http status for error responses.
response.SetHttpStatus(200)
}
// Run after request middlewares.
// Note: error responses are converted with the serverErrrorMiddleware middleware.
// Note: serializing the response into the proper format is done with the SerializeResponseMiddleware.
for _, middleware := range registry.HttpFrontend().AfterMiddlewares() {
resp, skip := middleware(registry, request, response)
if skip {
return nil, true
} else if resp != nil {
response = resp
}
}
return response, false
}
示例9: New
func New(registry kit.Registry) *Frontend {
conf := registry.Config()
f := &Frontend{
registry: registry,
debug: conf.UBool("frontends.wamp.debug", false),
beforeMiddlewares: make([]kit.RequestHandler, 0),
afterMiddlewares: make([]kit.AfterRequestMiddleware, 0),
sessions: make(map[uint]kit.Session),
}
f.RegisterBeforeMiddleware(frontends.RequestTraceMiddleware)
f.RegisterBeforeMiddleware(UnserializerMiddleware)
f.RegisterAfterMiddleware(frontends.SerializeResponseMiddleware)
f.RegisterAfterMiddleware(frontends.RequestTraceAfterMiddleware)
f.RegisterAfterMiddleware(frontends.RequestLoggerMiddleware)
return f
}
示例10: Update
func Update(registry kit.Registry, request kit.Request) (kit.Response, apperror.Error) {
collection := request.GetContext().MustString("collection")
res := registry.Resource(collection)
if res == nil || !res.IsPublic() {
return nil, &apperror.Err{
Code: "unknown_resource",
Message: fmt.Sprintf("The resource '%v' does not exist", collection),
}
}
model, ok := request.GetData().(kit.Model)
if !ok {
return nil, apperror.New("invalid_data_no_model", "Node model data in request.")
}
response := res.ApiUpdate(model, request)
return response, nil
}
示例11: UnserializeRequestMiddleware
func UnserializeRequestMiddleware(registry kit.Registry, request kit.Request) (kit.Response, bool) {
// Try to parse json in body. Ignore error since body might not contain json.
contentType := request.GetHttpRequest().Header.Get("Content-Type")
if strings.Contains(contentType, "json") {
// Only read the HTTP body automatically for json content type requests,
// since some handlers might need to read it themselfes (see the files package resource).
if err := request.ReadHttpBody(); err != nil {
return kit.NewErrorResponse(err, "http_body_read_error"), false
} else {
if request.GetRawData() != nil {
if err := request.ParseJsonData(); err != nil {
return kit.NewErrorResponse(err, "invalid_json_body", true), false
}
if request.GetData() != nil {
// Successfully parsed json body.
// Now try to unserialize.
// Determine serializer.
serializer := registry.DefaultSerializer()
// Check if a custom serializer was specified.
if name := request.GetContext().String("request-serializer"); name != "" {
serializer = registry.Serializer(name)
}
if serializer == nil {
return kit.NewErrorResponse("unknown_serializer", fmt.Sprintf("The specified request serializer does not exist")), false
} else {
if err := request.Unserialize(serializer); err != nil {
return kit.NewErrorResponse(err, "request_unserialize_error", true), false
}
}
}
}
}
}
return nil, false
}
示例12: SerializeResponseMiddleware
func SerializeResponseMiddleware(registry kit.Registry, request kit.Request, response kit.Response) (kit.Response, bool) {
// Try to serialize the reponse data.
// Determine serializer.
serializer := registry.DefaultSerializer()
// Check if a custom serializer was specified.
if name := request.GetContext().String("response-serializer"); name != "" {
serializer = registry.Serializer(name)
if serializer == nil {
errResp := kit.NewErrorResponse("unknown_response_serializer", true)
data, _ := serializer.MustSerializeResponse(errResp)
errResp.SetData(data)
return errResp, false
}
}
// Set format in metadata.
meta := response.GetMeta()
if meta == nil {
meta = make(map[string]interface{})
}
meta["format"] = serializer.Name()
response.SetMeta(meta)
data, err := serializer.MustSerializeResponse(response)
if err != nil {
registry.Logger().Errorf("Response serialization error: %v (%+v)", err, response)
}
response.SetData(data)
return nil, false
}
示例13: RequestLoggerMiddleware
func RequestLoggerMiddleware(registry kit.Registry, r kit.Request, response kit.Response) (kit.Response, bool) {
// Calculate time taken.
rawStarted, ok1 := r.GetContext().Get("startTime")
rawFinished, ok2 := r.GetContext().Get("endTime")
timeTaken := int64(-1)
if ok1 && ok2 {
started := rawStarted.(time.Time)
finished := rawFinished.(time.Time)
timeTaken = int64(finished.Sub(started) / time.Millisecond)
}
// Log the request.
method := r.GetHttpMethod()
path := r.GetPath()
if response.GetError() != nil {
registry.Logger().WithFields(logrus.Fields{
"frontend": r.GetFrontend(),
"action": "request",
"method": method,
"path": path,
"status": response.GetHttpStatus(),
"err": response.GetError(),
"milliseconds": timeTaken,
}).Errorf("%v: %v - %v - %v", response.GetHttpStatus(), method, path, response.GetError())
} else {
registry.Logger().WithFields(logrus.Fields{
"frontend": r.GetFrontend(),
"action": "request",
"method": method,
"path": path,
"status": response.GetHttpStatus(),
"milliseconds": timeTaken,
}).Debugf("%v: %v - %v", response.GetHttpStatus(), method, path)
}
return nil, false
}
示例14: UnserializerMiddleware
func UnserializerMiddleware(registry kit.Registry, request kit.Request) (kit.Response, bool) {
serializer := registry.DefaultSerializer()
// Try to find custom serializer.
data, ok := request.GetData().(map[string]interface{})
if ok {
name, ok := data["request_serializer"].(string)
if ok {
s := registry.Serializer(name)
if s == nil {
resp := kit.NewErrorResponse("unknown_request_serializer", fmt.Sprintf("The given request serializer %v does not exist", name))
return resp, false
} else {
serializer = s
}
}
}
if err := serializer.UnserializeRequest(request.GetData(), request); err != nil {
return kit.NewErrorResponse(err), false
}
return nil, false
}
示例15: Create
func Create(registry kit.Registry, request kit.Request) (kit.Response, apperror.Error) {
collection := request.GetContext().MustString("collection")
res := registry.Resource(collection)
if res == nil || !res.IsPublic() {
return nil, &apperror.Err{
Code: "unknown_resource",
Message: fmt.Sprintf("The resource '%v' does not exist", collection),
}
}
fmt.Printf("data: %v | %+v\n\n", nil, request.GetData())
model, ok := request.GetData().(kit.Model)
if !ok {
return nil, apperror.New("invalid_data_no_model", "No model data in request.")
}
response := res.ApiCreate(model, request)
if response.GetError() == nil {
response.SetHttpStatus(201)
}
return response, nil
}