utils.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package plugin
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. plugin "github.com/fatedier/frp/pkg/plugin/server"
  8. "github.com/fatedier/frp/pkg/util/log"
  9. "github.com/fatedier/frp/test/e2e/mock/server/httpserver"
  10. )
  11. type PluginHandler func(req *plugin.Request) *plugin.Response
  12. type NewPluginRequest func() *plugin.Request
  13. func NewHTTPPluginServer(port int, newFunc NewPluginRequest, handler PluginHandler, tlsConfig *tls.Config) *httpserver.Server {
  14. return httpserver.New(
  15. httpserver.WithBindPort(port),
  16. httpserver.WithTlsConfig(tlsConfig),
  17. httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  18. r := newFunc()
  19. buf, err := io.ReadAll(req.Body)
  20. if err != nil {
  21. w.WriteHeader(500)
  22. return
  23. }
  24. log.Trace("plugin request: %s", string(buf))
  25. err = json.Unmarshal(buf, &r)
  26. if err != nil {
  27. w.WriteHeader(500)
  28. return
  29. }
  30. resp := handler(r)
  31. buf, _ = json.Marshal(resp)
  32. log.Trace("plugin response: %s", string(buf))
  33. w.Write(buf)
  34. })),
  35. )
  36. }