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