Home > Backend Development > Golang > Invalid node type panic when implementing plugin for KrakenD

Invalid node type panic when implementing plugin for KrakenD

WBOY
Release: 2024-02-09 10:21:09
forward
1071 people have browsed it

为 KrakenD 实现插件时无效的节点类型恐慌

#php editor Baicao today introduces to you a common problem in the development of KrakenD plug-ins: "Invalid node type panic when implementing plug-ins for KrakenD". KrakenD is a fast, high-performance API gateway that provides rich functionality and a flexible plug-in system. However, when developing a KrakenD plug-in, you sometimes encounter the problem of invalid node types, which may cause the plug-in to fail to function properly. In this article, we will explore the causes of this problem and solutions to help developers overcome this panic.

Question content

I am developing a plugin without redirection. I'm using krakend-ce 2.2.1 (using golang 1.19) and I'm panicking:

gw_krakend_1  | [krakend] 2023/03/15 - 21:09:06.675 ? debug no_redirect_plugin: request received https://127.0.0.1:8443/abc
gw_krakend_1  | [krakend] 2023/03/15 - 21:09:06.689 ? debug no_redirect_plugin: redirect detected https://127.0.0.1:8443/abc
gw_krakend_1  | [krakend] 2023/03/15 - 21:09:06.689 ? debug status code 302
gw_krakend_1  | 2023/03/15 21:09:06 http: panic serving [::1]:54778: invalid node type
gw_krakend_1  | goroutine 84 [running]:
gw_krakend_1  | net/http.(*conn).serve.func1()
gw_krakend_1  |         /usr/local/go/src/net/http/server.go:1854 +0xbf
gw_krakend_1  | panic({0x28cbb60, 0x34b5810})
gw_krakend_1  |         /usr/local/go/src/runtime/panic.go:890 +0x263
gw_krakend_1  | github.com/gin-gonic/gin.(*node).findcaseinsensitivepathrec(0x0?, {0xc0016ac2ec?, 0x0?}, {0xc0010fe800?, 0xc0016ac2ed?, 0xc000ced928?}, {0x0, 0x0, 0x0, 0x0}, ...)
gw_krakend_1  |         /go/pkg/mod/github.com/gin-gonic/[email protected]/tree.go:862 +0xa9d
gw_krakend_1  | github.com/gin-gonic/gin.(*node).findcaseinsensitivepath(0xc0016ac2ec?, {0xc0016ac2ec, 0x5}, 0x30?)
gw_krakend_1  |         /go/pkg/mod/github.com/gin-gonic/[email protected]/tree.go:669 +0x9c
gw_krakend_1  | github.com/gin-gonic/gin.redirectfixedpath(0xc000664300, 0xc0016ac2ec?, 0x60?)
gw_krakend_1  |         /go/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:684 +0x5b
gw_krakend_1  | github.com/gin-gonic/gin.(*engine).handlehttprequest(0xc000602b60, 0xc000664300)
Copy after login

Looks similar to it https://github.com/gin-gonic/gin/issues/2959, but the version of gin has been upgraded on the previous version of krakend. It would be weird if they were really capital letters, it works perfectly without the plugin. I also trimmed the last / (it was added at some point for some reason)

BTW, I'm using the same version of krakend to compile the plugin.

package main

import (
    "context"
    "errors"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "strings"
)

func main() {}

var clientregisterer = registerer("no_redirect_plugin")

type registerer string

type logger interface {
    debug(v ...interface{})
    info(v ...interface{})
    warning(v ...interface{})
    error(v ...interface{})
    critical(v ...interface{})
    fatal(v ...interface{})
}

var logger logger = nil

func (registerer) registerlogger(v interface{}) {
    l, ok := v.(logger)
    if !ok {
        return
    }
    logger = l
    logger.info(fmt.sprintf("[plugin: %s] logger loaded", clientregisterer))
}

func (r registerer) registerclients(f func(
    name string,
    handler func(context.context, map[string]interface{}) (http.handler, error),
)) {
    f(string(r), r.registerclients)
}

func (r registerer) registerclients(_ context.context, extra map[string]interface{}) (http.handler, error) {
    name, ok := extra["name"].(string)
    if !ok {
        return nil, errors.new("wrong config")
    }

    if name != string(r) {
        return nil, fmt.errorf("unknown register %s", name)
    }

    httpclient := &http.client{
        checkredirect: func(req *http.request, via []*http.request) error {

            // trim the last "/" character from the url if it exists
            urlstr := strings.trimright(req.url.string(), "/")
            req.url, _ = url.parse(urlstr)

            logger.debug("no_redirect_plugin: redirect detected", req.url.string())
            return http.erruselastresponse
        },
    }

    return http.handlerfunc(func(w http.responsewriter, req *http.request) {

        // trim the last "/" character from the url if it exists
        urlstr := strings.trimright(req.url.string(), "/")
        req.url, _ = url.parse(urlstr)

        logger.debug("no_redirect_plugin: request received", req.url.string())
        resp, err := httpclient.do(req)
        if err != nil {
            logger.debug("error while proxying request", err.error())
            http.error(w, err.error(), http.statusinternalservererror)
            return
        }

        defer resp.body.close()

        for k, hs := range resp.header {
            for _, h := range hs {
                w.header().add(k, h)
            }
        }

        w.writeheader(resp.statuscode)
        logger.debug("status code", resp.statuscode)
        if resp.body == nil {
            return
        }

        _, err = io.copy(w, resp.body)
        if err != nil {
            logger.debug("error while proxying request 2", err.error())
            http.error(w, err.error(), http.statusinternalservererror)
            return
        }

    }), nil
}

Copy after login

My endpoint is defined as follows:

{
     "endpoint": "/",
     "input_headers":[
       "*"
     ],
     "input_query_strings":[
       "*"
     ],
     "method": "GET",
     "output_encoding": "no-op",
     "extra_config": {},
     "backend": [{
       "url_pattern": "",
       "encoding": "no-op",
       "sd": "static",
       "method": "GET",
       "extra_config": {
         "plugin/http-client": {
           "name": "no_redirect_plugin"
         }
       },
       "host": [
         "{{ env "HOST" }}"
       ],
       "disable_host_sanitize": false
   }]
},{
     "endpoint": "/{level1}",
     "input_headers":[
       "*"
     ],
     "input_query_strings":[
       "*"
     ],
     "method": "GET",
     "output_encoding": "no-op",
     "extra_config": {
     },
     "backend": [{
       "url_pattern": "/{level1}",
       "encoding": "no-op",
       "sd": "static",
       "method": "GET",
       "extra_config": {
         "plugin/http-client": {
           "name": "no_redirect_plugin"
         }
       },
       "host": [
         "{{ env "HOST" }}"
       ],
       "disable_host_sanitize": false
   }]
},{
     "endpoint": "/{level1}/{level2}",
     "input_headers":[
       "*"
     ],
     "input_query_strings":[
       "*"
     ],
     "method": "GET",
     "output_encoding": "no-op",
     "extra_config": {
     },
     "backend": [{
       "url_pattern": "/{level1}/{level2}",
       "encoding": "no-op",
       "sd": "static",
       "method": "GET",
       "extra_config": {
         "plugin/http-client": {
           "name": "no_redirect_plugin"
         }
       },
       "host": [
         "{{ env "HOST" }}"
       ],
       "disable_host_sanitize": false
   }]
}
Copy after login

EDIT: My browser still shows /abc/ instead of /abc, which could create possible collisions between routes (as seen here: https://github.com/krakendio/krakend-ce/issues /386) Anyway I don't know where to add the slash (I thought I trimmed it permanently...seems like I didn't)

edit2: I found this https://www.krakend.io/docs/service-settings/router-options/ and used "disable_redirect_fixed_path": true and "disable_redirect_trailing_slash": true, it doesn't panic anymore... Now I have another problem: infinite redirects (just 10 just kidding) when my boulder tries to redirect to /a/ or anything with a trailing slash This is done in the plugin because krakend used to handle redirects in its own way...

I guess the main problem here is routing conflict, when /{level1} and /{level1}/{level2} match /abc/ at the same time

idea?

Solution

Very good, in order to solve this problem, I tried to use this to create a wildcard no_redirect plug-in //m.sbmmt.com/link/ba530cdf0a884348613f2aaa3a5ba5e8 configuration, but even with copilot&gpt4 I failed, I dare say you can implement this. So I solved the problem with another way: I put the gateway in front of my boulder and every time the request failed I added the route... because we didn't have a logged route (*sobs). It works just fine for files that require a redirect-free plugin. A great solution but it has worked so far and not as long as I thought

The above is the detailed content of Invalid node type panic when implementing plugin for KrakenD. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template