frp/test/e2e/v1/plugin/utils.go

42 lines
1.0 KiB
Go
Raw Normal View History

2021-08-02 07:07:28 +02:00
package plugin
import (
"crypto/tls"
"encoding/json"
"io"
2021-08-02 07:07:28 +02: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-28 19:02:53 +02:00
type Handler func(req *plugin.Request) *plugin.Response
2021-08-02 07:07:28 +02:00
type NewPluginRequest func() *plugin.Request
2022-08-28 19:02:53 +02:00
func NewHTTPPluginServer(port int, newFunc NewPluginRequest, handler Handler, tlsConfig *tls.Config) *httpserver.Server {
2021-08-02 07:07:28 +02:00
return httpserver.New(
httpserver.WithBindPort(port),
2022-08-28 19:02:53 +02:00
httpserver.WithTLSConfig(tlsConfig),
2021-08-02 07:07:28 +02:00
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
r := newFunc()
buf, err := io.ReadAll(req.Body)
2021-08-02 07:07:28 +02:00
if err != nil {
w.WriteHeader(500)
return
}
log.Trace("plugin request: %s", string(buf))
err = json.Unmarshal(buf, &r)
if err != nil {
w.WriteHeader(500)
return
}
resp := handler(r)
buf, _ = json.Marshal(resp)
log.Trace("plugin response: %s", string(buf))
2022-08-28 19:02:53 +02:00
_, _ = w.Write(buf)
2021-08-02 07:07:28 +02:00
})),
)
}