feat:新增rpc服务

This commit is contained in:
tongque
2025-04-22 19:03:42 +08:00
parent a1452eb635
commit f921d81a76
10 changed files with 1160 additions and 58 deletions
+409
View File
@@ -0,0 +1,409 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.6
// protoc (unknown)
// source: proto/fscan.proto
package lib
import (
_ "google.golang.org/genproto/googleapis/api/annotations"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// 启动任务的请求
type StartScanRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Secret string `protobuf:"bytes,1,opt,name=secret,proto3" json:"secret,omitempty"`
Arg string `protobuf:"bytes,2,opt,name=arg,proto3" json:"arg,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *StartScanRequest) Reset() {
*x = StartScanRequest{}
mi := &file_proto_fscan_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *StartScanRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StartScanRequest) ProtoMessage() {}
func (x *StartScanRequest) ProtoReflect() protoreflect.Message {
mi := &file_proto_fscan_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StartScanRequest.ProtoReflect.Descriptor instead.
func (*StartScanRequest) Descriptor() ([]byte, []int) {
return file_proto_fscan_proto_rawDescGZIP(), []int{0}
}
func (x *StartScanRequest) GetSecret() string {
if x != nil {
return x.Secret
}
return ""
}
func (x *StartScanRequest) GetArg() string {
if x != nil {
return x.Arg
}
return ""
}
// 启动任务的响应
type StartScanResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *StartScanResponse) Reset() {
*x = StartScanResponse{}
mi := &file_proto_fscan_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *StartScanResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StartScanResponse) ProtoMessage() {}
func (x *StartScanResponse) ProtoReflect() protoreflect.Message {
mi := &file_proto_fscan_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StartScanResponse.ProtoReflect.Descriptor instead.
func (*StartScanResponse) Descriptor() ([]byte, []int) {
return file_proto_fscan_proto_rawDescGZIP(), []int{1}
}
func (x *StartScanResponse) GetTaskId() string {
if x != nil {
return x.TaskId
}
return ""
}
func (x *StartScanResponse) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
// 获取扫描结果的请求
type TaskResultsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *TaskResultsRequest) Reset() {
*x = TaskResultsRequest{}
mi := &file_proto_fscan_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *TaskResultsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TaskResultsRequest) ProtoMessage() {}
func (x *TaskResultsRequest) ProtoReflect() protoreflect.Message {
mi := &file_proto_fscan_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use TaskResultsRequest.ProtoReflect.Descriptor instead.
func (*TaskResultsRequest) Descriptor() ([]byte, []int) {
return file_proto_fscan_proto_rawDescGZIP(), []int{2}
}
func (x *TaskResultsRequest) GetTaskId() string {
if x != nil {
return x.TaskId
}
return ""
}
func (x *TaskResultsRequest) GetOffset() uint32 {
if x != nil {
return x.Offset
}
return 0
}
// 获取扫描结果的响应
type TaskResultsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
Results []*ScanResult `protobuf:"bytes,2,rep,name=results,proto3" json:"results,omitempty"`
Finished bool `protobuf:"varint,3,opt,name=finished,proto3" json:"finished,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *TaskResultsResponse) Reset() {
*x = TaskResultsResponse{}
mi := &file_proto_fscan_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *TaskResultsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TaskResultsResponse) ProtoMessage() {}
func (x *TaskResultsResponse) ProtoReflect() protoreflect.Message {
mi := &file_proto_fscan_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use TaskResultsResponse.ProtoReflect.Descriptor instead.
func (*TaskResultsResponse) Descriptor() ([]byte, []int) {
return file_proto_fscan_proto_rawDescGZIP(), []int{3}
}
func (x *TaskResultsResponse) GetTaskId() string {
if x != nil {
return x.TaskId
}
return ""
}
func (x *TaskResultsResponse) GetResults() []*ScanResult {
if x != nil {
return x.Results
}
return nil
}
func (x *TaskResultsResponse) GetFinished() bool {
if x != nil {
return x.Finished
}
return false
}
// 扫描结果结构体
type ScanResult struct {
state protoimpl.MessageState `protogen:"open.v1"`
Time string `protobuf:"bytes,1,opt,name=time,proto3" json:"time,omitempty"`
Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"`
Target string `protobuf:"bytes,3,opt,name=target,proto3" json:"target,omitempty"`
Status string `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"`
DetailsJson string `protobuf:"bytes,5,opt,name=details_json,json=detailsJson,proto3" json:"details_json,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ScanResult) Reset() {
*x = ScanResult{}
mi := &file_proto_fscan_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ScanResult) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ScanResult) ProtoMessage() {}
func (x *ScanResult) ProtoReflect() protoreflect.Message {
mi := &file_proto_fscan_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ScanResult.ProtoReflect.Descriptor instead.
func (*ScanResult) Descriptor() ([]byte, []int) {
return file_proto_fscan_proto_rawDescGZIP(), []int{4}
}
func (x *ScanResult) GetTime() string {
if x != nil {
return x.Time
}
return ""
}
func (x *ScanResult) GetType() string {
if x != nil {
return x.Type
}
return ""
}
func (x *ScanResult) GetTarget() string {
if x != nil {
return x.Target
}
return ""
}
func (x *ScanResult) GetStatus() string {
if x != nil {
return x.Status
}
return ""
}
func (x *ScanResult) GetDetailsJson() string {
if x != nil {
return x.DetailsJson
}
return ""
}
var File_proto_fscan_proto protoreflect.FileDescriptor
const file_proto_fscan_proto_rawDesc = "" +
"\n" +
"\x11proto/fscan.proto\x12\x03lib\x1a\x1cgoogle/api/annotations.proto\"<\n" +
"\x10StartScanRequest\x12\x16\n" +
"\x06secret\x18\x01 \x01(\tR\x06secret\x12\x10\n" +
"\x03arg\x18\x02 \x01(\tR\x03arg\"F\n" +
"\x11StartScanResponse\x12\x17\n" +
"\atask_id\x18\x01 \x01(\tR\x06taskId\x12\x18\n" +
"\amessage\x18\x02 \x01(\tR\amessage\"E\n" +
"\x12TaskResultsRequest\x12\x17\n" +
"\atask_id\x18\x01 \x01(\tR\x06taskId\x12\x16\n" +
"\x06offset\x18\x02 \x01(\rR\x06offset\"u\n" +
"\x13TaskResultsResponse\x12\x17\n" +
"\atask_id\x18\x01 \x01(\tR\x06taskId\x12)\n" +
"\aresults\x18\x02 \x03(\v2\x0f.lib.ScanResultR\aresults\x12\x1a\n" +
"\bfinished\x18\x03 \x01(\bR\bfinished\"\x87\x01\n" +
"\n" +
"ScanResult\x12\x12\n" +
"\x04time\x18\x01 \x01(\tR\x04time\x12\x12\n" +
"\x04type\x18\x02 \x01(\tR\x04type\x12\x16\n" +
"\x06target\x18\x03 \x01(\tR\x06target\x12\x16\n" +
"\x06status\x18\x04 \x01(\tR\x06status\x12!\n" +
"\fdetails_json\x18\x05 \x01(\tR\vdetailsJson2\xa0\x02\n" +
"\fFscanService\x12T\n" +
"\tStartScan\x12\x15.lib.StartScanRequest\x1a\x16.lib.StartScanResponse\"\x18\x82\xd3\xe4\x93\x02\x12:\x01*\"\r/v1/startscan\x12^\n" +
"\x0eGetScanResults\x12\x17.lib.TaskResultsRequest\x1a\x18.lib.TaskResultsResponse\"\x19\x82\xd3\xe4\x93\x02\x13:\x01*\"\x0e/v1/getresults\x12Z\n" +
"\x11StreamScanResults\x12\x17.lib.TaskResultsRequest\x1a\x0f.lib.ScanResult\"\x19\x82\xd3\xe4\x93\x02\x13\x12\x11/v1/streamresults0\x01B\x1eZ\x1cgithub.com/shadow1ng/RPC;libb\x06proto3"
var (
file_proto_fscan_proto_rawDescOnce sync.Once
file_proto_fscan_proto_rawDescData []byte
)
func file_proto_fscan_proto_rawDescGZIP() []byte {
file_proto_fscan_proto_rawDescOnce.Do(func() {
file_proto_fscan_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_fscan_proto_rawDesc), len(file_proto_fscan_proto_rawDesc)))
})
return file_proto_fscan_proto_rawDescData
}
var file_proto_fscan_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
var file_proto_fscan_proto_goTypes = []any{
(*StartScanRequest)(nil), // 0: lib.StartScanRequest
(*StartScanResponse)(nil), // 1: lib.StartScanResponse
(*TaskResultsRequest)(nil), // 2: lib.TaskResultsRequest
(*TaskResultsResponse)(nil), // 3: lib.TaskResultsResponse
(*ScanResult)(nil), // 4: lib.ScanResult
}
var file_proto_fscan_proto_depIdxs = []int32{
4, // 0: lib.TaskResultsResponse.results:type_name -> lib.ScanResult
0, // 1: lib.FscanService.StartScan:input_type -> lib.StartScanRequest
2, // 2: lib.FscanService.GetScanResults:input_type -> lib.TaskResultsRequest
2, // 3: lib.FscanService.StreamScanResults:input_type -> lib.TaskResultsRequest
1, // 4: lib.FscanService.StartScan:output_type -> lib.StartScanResponse
3, // 5: lib.FscanService.GetScanResults:output_type -> lib.TaskResultsResponse
4, // 6: lib.FscanService.StreamScanResults:output_type -> lib.ScanResult
4, // [4:7] is the sub-list for method output_type
1, // [1:4] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_proto_fscan_proto_init() }
func file_proto_fscan_proto_init() {
if File_proto_fscan_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_fscan_proto_rawDesc), len(file_proto_fscan_proto_rawDesc)),
NumEnums: 0,
NumMessages: 5,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_proto_fscan_proto_goTypes,
DependencyIndexes: file_proto_fscan_proto_depIdxs,
MessageInfos: file_proto_fscan_proto_msgTypes,
}.Build()
File_proto_fscan_proto = out.File
file_proto_fscan_proto_goTypes = nil
file_proto_fscan_proto_depIdxs = nil
}
+269
View File
@@ -0,0 +1,269 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: proto/fscan.proto
/*
Package lib is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package lib
import (
"context"
"errors"
"io"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// Suppress "imported and not used" errors
var (
_ codes.Code
_ io.Reader
_ status.Status
_ = errors.New
_ = runtime.String
_ = utilities.NewDoubleArray
_ = metadata.Join
)
func request_FscanService_StartScan_0(ctx context.Context, marshaler runtime.Marshaler, client FscanServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var (
protoReq StartScanRequest
metadata runtime.ServerMetadata
)
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.StartScan(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_FscanService_StartScan_0(ctx context.Context, marshaler runtime.Marshaler, server FscanServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var (
protoReq StartScanRequest
metadata runtime.ServerMetadata
)
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.StartScan(ctx, &protoReq)
return msg, metadata, err
}
func request_FscanService_GetScanResults_0(ctx context.Context, marshaler runtime.Marshaler, client FscanServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var (
protoReq TaskResultsRequest
metadata runtime.ServerMetadata
)
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.GetScanResults(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_FscanService_GetScanResults_0(ctx context.Context, marshaler runtime.Marshaler, server FscanServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var (
protoReq TaskResultsRequest
metadata runtime.ServerMetadata
)
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.GetScanResults(ctx, &protoReq)
return msg, metadata, err
}
var filter_FscanService_StreamScanResults_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
func request_FscanService_StreamScanResults_0(ctx context.Context, marshaler runtime.Marshaler, client FscanServiceClient, req *http.Request, pathParams map[string]string) (FscanService_StreamScanResultsClient, runtime.ServerMetadata, error) {
var (
protoReq TaskResultsRequest
metadata runtime.ServerMetadata
)
io.Copy(io.Discard, req.Body)
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FscanService_StreamScanResults_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
stream, err := client.StreamScanResults(ctx, &protoReq)
if err != nil {
return nil, metadata, err
}
header, err := stream.Header()
if err != nil {
return nil, metadata, err
}
metadata.HeaderMD = header
return stream, metadata, nil
}
// RegisterFscanServiceHandlerServer registers the http handlers for service FscanService to "mux".
// UnaryRPC :call FscanServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterFscanServiceHandlerFromEndpoint instead.
// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call.
func RegisterFscanServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server FscanServiceServer) error {
mux.Handle(http.MethodPost, pattern_FscanService_StartScan_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/lib.FscanService/StartScan", runtime.WithHTTPPathPattern("/v1/startscan"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_FscanService_StartScan_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_FscanService_StartScan_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle(http.MethodPost, pattern_FscanService_GetScanResults_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/lib.FscanService/GetScanResults", runtime.WithHTTPPathPattern("/v1/getresults"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_FscanService_GetScanResults_0(annotatedContext, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_FscanService_GetScanResults_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle(http.MethodGet, pattern_FscanService_StreamScanResults_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport")
_, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
})
return nil
}
// RegisterFscanServiceHandlerFromEndpoint is same as RegisterFscanServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterFscanServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.NewClient(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterFscanServiceHandler(ctx, mux, conn)
}
// RegisterFscanServiceHandler registers the http handlers for service FscanService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterFscanServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterFscanServiceHandlerClient(ctx, mux, NewFscanServiceClient(conn))
}
// RegisterFscanServiceHandlerClient registers the http handlers for service FscanService
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "FscanServiceClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "FscanServiceClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "FscanServiceClient" to call the correct interceptors. This client ignores the HTTP middlewares.
func RegisterFscanServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client FscanServiceClient) error {
mux.Handle(http.MethodPost, pattern_FscanService_StartScan_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/lib.FscanService/StartScan", runtime.WithHTTPPathPattern("/v1/startscan"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_FscanService_StartScan_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_FscanService_StartScan_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle(http.MethodPost, pattern_FscanService_GetScanResults_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/lib.FscanService/GetScanResults", runtime.WithHTTPPathPattern("/v1/getresults"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_FscanService_GetScanResults_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_FscanService_GetScanResults_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle(http.MethodGet, pattern_FscanService_StreamScanResults_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/lib.FscanService/StreamScanResults", runtime.WithHTTPPathPattern("/v1/streamresults"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_FscanService_StreamScanResults_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_FscanService_StreamScanResults_0(annotatedContext, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_FscanService_StartScan_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "startscan"}, ""))
pattern_FscanService_GetScanResults_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "getresults"}, ""))
pattern_FscanService_StreamScanResults_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "streamresults"}, ""))
)
var (
forward_FscanService_StartScan_0 = runtime.ForwardResponseMessage
forward_FscanService_GetScanResults_0 = runtime.ForwardResponseMessage
forward_FscanService_StreamScanResults_0 = runtime.ForwardResponseStream
)
+207
View File
@@ -0,0 +1,207 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc (unknown)
// source: proto/fscan.proto
package lib
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
FscanService_StartScan_FullMethodName = "/lib.FscanService/StartScan"
FscanService_GetScanResults_FullMethodName = "/lib.FscanService/GetScanResults"
FscanService_StreamScanResults_FullMethodName = "/lib.FscanService/StreamScanResults"
)
// FscanServiceClient is the client API for FscanService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type FscanServiceClient interface {
// 启动扫描任务
StartScan(ctx context.Context, in *StartScanRequest, opts ...grpc.CallOption) (*StartScanResponse, error)
// 获取扫描结果(非流式)
GetScanResults(ctx context.Context, in *TaskResultsRequest, opts ...grpc.CallOption) (*TaskResultsResponse, error)
// 获取扫描结果(流式)
StreamScanResults(ctx context.Context, in *TaskResultsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ScanResult], error)
}
type fscanServiceClient struct {
cc grpc.ClientConnInterface
}
func NewFscanServiceClient(cc grpc.ClientConnInterface) FscanServiceClient {
return &fscanServiceClient{cc}
}
func (c *fscanServiceClient) StartScan(ctx context.Context, in *StartScanRequest, opts ...grpc.CallOption) (*StartScanResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(StartScanResponse)
err := c.cc.Invoke(ctx, FscanService_StartScan_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *fscanServiceClient) GetScanResults(ctx context.Context, in *TaskResultsRequest, opts ...grpc.CallOption) (*TaskResultsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(TaskResultsResponse)
err := c.cc.Invoke(ctx, FscanService_GetScanResults_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *fscanServiceClient) StreamScanResults(ctx context.Context, in *TaskResultsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ScanResult], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &FscanService_ServiceDesc.Streams[0], FscanService_StreamScanResults_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[TaskResultsRequest, ScanResult]{ClientStream: stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type FscanService_StreamScanResultsClient = grpc.ServerStreamingClient[ScanResult]
// FscanServiceServer is the server API for FscanService service.
// All implementations must embed UnimplementedFscanServiceServer
// for forward compatibility.
type FscanServiceServer interface {
// 启动扫描任务
StartScan(context.Context, *StartScanRequest) (*StartScanResponse, error)
// 获取扫描结果(非流式)
GetScanResults(context.Context, *TaskResultsRequest) (*TaskResultsResponse, error)
// 获取扫描结果(流式)
StreamScanResults(*TaskResultsRequest, grpc.ServerStreamingServer[ScanResult]) error
mustEmbedUnimplementedFscanServiceServer()
}
// UnimplementedFscanServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedFscanServiceServer struct{}
func (UnimplementedFscanServiceServer) StartScan(context.Context, *StartScanRequest) (*StartScanResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method StartScan not implemented")
}
func (UnimplementedFscanServiceServer) GetScanResults(context.Context, *TaskResultsRequest) (*TaskResultsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetScanResults not implemented")
}
func (UnimplementedFscanServiceServer) StreamScanResults(*TaskResultsRequest, grpc.ServerStreamingServer[ScanResult]) error {
return status.Errorf(codes.Unimplemented, "method StreamScanResults not implemented")
}
func (UnimplementedFscanServiceServer) mustEmbedUnimplementedFscanServiceServer() {}
func (UnimplementedFscanServiceServer) testEmbeddedByValue() {}
// UnsafeFscanServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to FscanServiceServer will
// result in compilation errors.
type UnsafeFscanServiceServer interface {
mustEmbedUnimplementedFscanServiceServer()
}
func RegisterFscanServiceServer(s grpc.ServiceRegistrar, srv FscanServiceServer) {
// If the following call pancis, it indicates UnimplementedFscanServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&FscanService_ServiceDesc, srv)
}
func _FscanService_StartScan_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(StartScanRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FscanServiceServer).StartScan(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: FscanService_StartScan_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FscanServiceServer).StartScan(ctx, req.(*StartScanRequest))
}
return interceptor(ctx, in, info, handler)
}
func _FscanService_GetScanResults_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TaskResultsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FscanServiceServer).GetScanResults(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: FscanService_GetScanResults_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FscanServiceServer).GetScanResults(ctx, req.(*TaskResultsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _FscanService_StreamScanResults_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(TaskResultsRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(FscanServiceServer).StreamScanResults(m, &grpc.GenericServerStream[TaskResultsRequest, ScanResult]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type FscanService_StreamScanResultsServer = grpc.ServerStreamingServer[ScanResult]
// FscanService_ServiceDesc is the grpc.ServiceDesc for FscanService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var FscanService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "lib.FscanService",
HandlerType: (*FscanServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "StartScan",
Handler: _FscanService_StartScan_Handler,
},
{
MethodName: "GetScanResults",
Handler: _FscanService_GetScanResults_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "StreamScanResults",
Handler: _FscanService_StreamScanResults_Handler,
ServerStreams: true,
},
},
Metadata: "proto/fscan.proto",
}
+66
View File
@@ -0,0 +1,66 @@
syntax = "proto3";
package lib;
option go_package = "./;lib";
import "google/api/annotations.proto";
service FscanService {
// 启动扫描任务
rpc StartScan(StartScanRequest) returns (StartScanResponse) {
option (google.api.http) = {
post: "/v1/startscan"
body: "*"
};
}
// 获取扫描结果(非流式)
rpc GetScanResults(TaskResultsRequest) returns (TaskResultsResponse) {
option (google.api.http) = {
post: "/v1/getresults"
body: "*"
};
}
// 获取扫描结果(流式)
rpc StreamScanResults(TaskResultsRequest) returns (stream ScanResult) {
option (google.api.http) = {
get: "/v1/streamresults"
};
}
}
// 启动任务的请求
message StartScanRequest {
string secret = 1;
string arg= 2;
}
// 启动任务的响应
message StartScanResponse {
string task_id = 1;
string message = 2;
}
// 获取扫描结果的请求
message TaskResultsRequest {
string task_id = 1;
uint32 offset = 2;
}
// 获取扫描结果的响应
message TaskResultsResponse {
string task_id = 1;
repeated ScanResult results = 2;
bool finished = 3;
}
// 扫描结果结构体
message ScanResult {
string time = 1;
string type = 2;
string target = 3;
string status = 4;
string details_json = 5;
}
+70
View File
@@ -0,0 +1,70 @@
package rpc
import (
"context"
"log"
"net"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
pb "github.com/shadow1ng/fscan/RPC/lib"
"github.com/shadow1ng/fscan/RPC/service"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// 暴露的启动函数(可供外部调用)
func StartHTTPServer() {
go runGRPCServer() // 启动 gRPC 服务
if err := runHTTPGateway(); err != nil {
log.Fatalf("HTTP 启动失败: %v", err)
}
}
// 启动 gRPC 服务
func runGRPCServer() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("监听失败: %v", err)
}
s := grpc.NewServer()
pb.RegisterFscanServiceServer(s, &service.FscanService{})
log.Println("✅ gRPC 服务已启动,端口 50051")
if err := s.Serve(lis); err != nil {
log.Fatalf("gRPC 启动失败: %v", err)
}
}
// 启动 HTTP Gateway 服务
func runHTTPGateway() error {
ctx := context.Background()
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
err := pb.RegisterFscanServiceHandlerFromEndpoint(ctx, mux, "localhost:50051", opts)
if err != nil {
return err
}
// 包裹 mux,加上 CORS 支持
handler := allowCORS(mux)
log.Println("✅ HTTP Gateway 已启动,端口 8080")
return http.ListenAndServe(":8080", handler)
}
// 添加 CORS 支持
func allowCORS(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
h.ServeHTTP(w, r)
})
}
+85
View File
@@ -0,0 +1,85 @@
package service
import (
"context"
"log"
"time"
pb "github.com/shadow1ng/fscan/RPC/lib"
)
// FscanService 实现了 pb.FscanServiceServer 接口,用于提供扫描相关的服务。
type FscanService struct {
pb.UnimplementedFscanServiceServer
}
// StartScan 用于启动扫描任务。
// 参数:
// - ctx:请求上下文,用于控制超时、取消等操作。
// - req:StartScanRequest,包括扫描目标、端口、模式等参数。
// 返回值:
// - StartScanResponse:包含任务 ID 和提示信息。
// - error:执行中出现的错误信息。
func (s *FscanService) StartScan(ctx context.Context, req *pb.StartScanRequest) (*pb.StartScanResponse, error) {
log.Printf("启动扫描: target=%s, port=%s, mode=%s", req.Secret, req.Arg)
// TODO: 在此处实现实际的扫描逻辑,例如调用扫描器、创建任务、存储任务状态等。
// 可以异步执行扫描逻辑,并生成一个唯一的 taskID 进行标识。
return &pb.StartScanResponse{
TaskId: "task_123456", // TODO: 返回真实生成的 taskID
Message: "扫描任务已启动",
}, nil
}
// GetScanResults 用于获取指定任务 ID 的扫描结果。
// 参数:
// - ctx:请求上下文。
// - req:TaskResultsRequest,包含任务 ID。
// 返回值:
// - TaskResultsResponse:包含结果列表、任务状态等信息。
// - error:执行中出现的错误信息。
func (s *FscanService) GetScanResults(ctx context.Context, req *pb.TaskResultsRequest) (*pb.TaskResultsResponse, error) {
// TODO: 实现根据任务 ID 查询任务结果,可以从缓存、数据库或临时文件中获取。
// 此处为模拟数据
result := &pb.ScanResult{
Time: time.Now().Format(time.RFC3339),
Type: "port",
Target: "192.168.1.1:80",
Status: "open",
DetailsJson: `{"banner":"nginx"}`,
}
return &pb.TaskResultsResponse{
TaskId: req.TaskId,
Results: []*pb.ScanResult{result},
Finished: true, // TODO: 判断任务是否真正完成
}, nil
}
// StreamScanResults 用于通过流式返回任务扫描结果,适合长时间扫描过程。
// 参数:
// - req:TaskResultsRequest,包含任务 ID。
// - stream:用于向客户端持续推送结果。
// 返回值:
// - error:执行中出现的错误信息。
func (s *FscanService) StreamScanResults(req *pb.TaskResultsRequest, stream pb.FscanService_StreamScanResultsServer) error {
// TODO: 根据任务 ID 逐步查询任务结果,并通过 stream.Send 发送给客户端。
// 可以监听任务进度,逐步推送最新结果。
for i := 0; i < 5; i++ {
result := &pb.ScanResult{
Time: time.Now().Format(time.RFC3339),
Type: "vuln",
Target: "192.168.1.1",
Status: "found",
DetailsJson: `{"vuln":"CVE-2021-12345"}`,
}
if err := stream.Send(result); err != nil {
return err
}
time.Sleep(1 * time.Second) // 模拟异步推送过程
}
return nil
}