frp/test/e2e/pkg/plugin/plugin.go

42 lines
1.0 KiB
Go
Raw Normal View History

2021-08-02 13:07:28 +08:00
package plugin
import (
"crypto/tls"
"encoding/json"
"io"
2021-08-02 13:07:28 +08:00
"net/http"
plugin "github.com/fatedier/frp/pkg/plugin/server"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
)
2022-08-29 01:02:53 +08:00
type Handler func(req *plugin.Request) *plugin.Response
2021-08-02 13:07:28 +08:00
type NewPluginRequest func() *plugin.Request
2022-08-29 01:02:53 +08:00
func NewHTTPPluginServer(port int, newFunc NewPluginRequest, handler Handler, tlsConfig *tls.Config) *httpserver.Server {
2021-08-02 13:07:28 +08:00
return httpserver.New(
httpserver.WithBindPort(port),
2022-08-29 01:02:53 +08:00
httpserver.WithTLSConfig(tlsConfig),
2021-08-02 13:07:28 +08:00
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
r := newFunc()
buf, err := io.ReadAll(req.Body)
2021-08-02 13:07:28 +08:00
if err != nil {
w.WriteHeader(500)
return
}
2024-03-12 13:58:53 +08:00
log.Tracef("plugin request: %s", string(buf))
2021-08-02 13:07:28 +08:00
err = json.Unmarshal(buf, &r)
if err != nil {
w.WriteHeader(500)
return
}
resp := handler(r)
buf, _ = json.Marshal(resp)
2024-03-12 13:58:53 +08:00
log.Tracef("plugin response: %s", string(buf))
2022-08-29 01:02:53 +08:00
_, _ = w.Write(buf)
2021-08-02 13:07:28 +08:00
})),
)
}