add api config for router

This commit is contained in:
ginuerzh
2023-11-19 16:16:12 +08:00
parent c95edd6ed3
commit 44064e4dd1
7 changed files with 179 additions and 81 deletions

View File

@ -1,7 +1,6 @@
package router
import (
"bytes"
"context"
"encoding/json"
"io"
@ -64,22 +63,6 @@ func (p *grpcPlugin) GetRoute(ctx context.Context, dst net.IP, opts ...router.Op
return ParseRoute(r.Net, r.Gateway)
}
func (p *grpcPlugin) SetRoute(ctx context.Context, route *router.Route, opts ...router.Option) bool {
if p.client == nil || route == nil {
return false
}
r, _ := p.client.SetRoute(ctx, &proto.SetRouteRequest{
Net: route.Net.String(),
Gateway: route.Gateway.String(),
})
if r == nil {
return false
}
return r.Ok
}
func (p *grpcPlugin) Close() error {
if closer, ok := p.conn.(io.Closer); ok {
return closer.Close()
@ -96,15 +79,6 @@ type httpPluginGetRouteResponse struct {
Gateway string `json:"gateway"`
}
type httpPluginSetRouteRequest struct {
Net string `json:"net"`
Gateway string `json:"gateway"`
}
type httpPluginSetRouteResponse struct {
OK bool `json:"ok"`
}
type httpPlugin struct {
url string
client *http.Client
@ -165,43 +139,3 @@ func (p *httpPlugin) GetRoute(ctx context.Context, dst net.IP, opts ...router.Op
return ParseRoute(res.Net, res.Gateway)
}
func (p *httpPlugin) SetRoute(ctx context.Context, route *router.Route, opts ...router.Option) bool {
if p.client == nil || route == nil {
return false
}
rb := httpPluginSetRouteRequest{
Net: route.Net.String(),
Gateway: route.Gateway.String(),
}
v, err := json.Marshal(&rb)
if err != nil {
return false
}
req, err := http.NewRequestWithContext(ctx, http.MethodPut, p.url, bytes.NewReader(v))
if err != nil {
return false
}
if p.header != nil {
req.Header = p.header.Clone()
}
req.Header.Set("Content-Type", "application/json")
resp, err := p.client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false
}
res := httpPluginSetRouteResponse{}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return false
}
return res.OK
}