AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-13102905

Ming's questions

Martin Hope
Ming
Asked: 2025-04-02 11:53:44 +0800 CST

servidor golang grpc e módulos grpc ui fx

  • 6

Estou tentando configurar módulos FX, mas tenho dúvidas e não consigo encontrar uma maneira de avançar. Basicamente, tenho um módulo para o servidor:

    func NewGRPCServer(
    lc fx.Lifecycle, log *zap.Logger, tracer trace.Tracer,
    srvsInterceptors []grpc.UnaryServerInterceptor, serverOpt []grpc.ServerOption,
) *grpc.Server {
    defaultRecoveryHandler := func(ctx context.Context, r interface{}) (err error) {
        logger.FromContext(ctx).Error("recovered from panic", zap.Any("panic", r), zap.Stack("stacktrace"))

        return status.Error(codes.Internal, "unexpected error")
    }

    interceptors := append([]grpc.UnaryServerInterceptor{
        LoggerToContextInterceptor(log),
        TracerToContextInterceptor(tracer),
        grpc_recovery.UnaryServerInterceptor(grpc_recovery.WithRecoveryHandlerContext(defaultRecoveryHandler)),
    }, srvsInterceptors...)

    otelHandler := otelgrpc.NewServerHandler(
        otelgrpc.WithTracerProvider(otel.GetTracerProvider()),
    )

    serverOpts := []grpc.ServerOption{
        grpc.ChainUnaryInterceptor(interceptors...),
        grpc.StatsHandler(otelHandler),
        grpc.KeepaliveEnforcementPolicy(
            keepalive.EnforcementPolicy{
                MinTime:             60 * time.Second,
                PermitWithoutStream: true,
            }),
        grpc.KeepaliveParams(
            keepalive.ServerParameters{
                Time:    60 * time.Second,
                Timeout: 10 * time.Second,
            },
        ),
    }

    serverOpts = append(serverOpts, serverOpt...)

    server := grpc.NewServer(serverOpts...)

    grpc_health_v1.RegisterHealthServer(server, health.NewServer())
    reflection.Register(server)

    return server
}

// NewListener creates a new network listener for the gRPC server using the gRPC server address parsed from the config.
func NewListener(cfg Config) (net.Listener, error) {
    lis, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.GRPC))
    if err != nil {
        return nil, fmt.Errorf("dial connection: %w", err)
    }

    return lis, nil
}

func GRPCModule() fx.Option {
    return fx.Module(
        "grpc",
        fx.Provide(
            fx.Annotate(
                NewGRPCServer,
                fx.ParamTags(``, ``, ``, `optional:"true"`, `optional:"true"`),
            ),
        ),
        fx.Invoke(func(lc fx.Lifecycle, server *grpc.Server, config Config, log *zap.Logger) {
            lc.Append(fx.Hook{
                OnStart: func(ctx context.Context) error {
                    lis, err := NewListener(config)
                    if err != nil {
                        return err
                    }

                    go func(srv *grpc.Server, logger *zap.Logger) {
                        logger.Info("Starting gRPC server")
                        if err := srv.Serve(lis); err != nil && err != grpc.ErrServerStopped {
                            logger.Error("gRPC server failed", zap.Error(err))
                        }
                    }(server, log)

                    return nil
                },
                OnStop: func(ctx context.Context) error {
                    server.GracefulStop()
                    return nil
                },
            })
        }),
    )
}

E um módulo para UI:

func NewGRPCUIServer(
    lc fx.Lifecycle,
    logger *zap.Logger,
    tracer trace.Tracer,
    config Config,
) (*http.Server, error) {
    logger.Info("enter on new grpc ui server.")

    rpcGrpcHost := fmt.Sprintf("0.0.0.0:%d", config.GRPC)
    keepAliveOpt := grpc.WithKeepaliveParams(keepalive.ClientParameters{
        Time:                60 * time.Second,
        Timeout:             10 * time.Second,
        PermitWithoutStream: true,
    })

    cc, err := grpc.NewClient(
        rpcGrpcHost,
        grpc.WithTransportCredentials(insecure.NewCredentials()),
        grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
        keepAliveOpt,
    )
    if err != nil {
        logger.Error("Failed to connect to gRPC server for UI", zap.Error(err))
        return nil, err
    }

    h, err := standalone.HandlerViaReflection(context.Background(), cc, rpcGrpcHost)
    if err != nil {
        logger.Error("Failed to create UI handler", zap.Error(err))
        return nil, err
    }

    mux := http.NewServeMux()
    mux.Handle("/grpc-ui/", http.StripPrefix("/grpc-ui", h))

    return httplib.NewHTTPServerFx(
        lc,
        httplib.Config{
            ServerAddr:         fmt.Sprintf(":%d", config.UI),
            ServerReadTimeout:  15 * time.Second,
            ServerWriteTimeout: 15 * time.Second,
        },
        logger,
        tracer,
        mux,
    )
}

type GRPCUIParams struct {
    fx.In

    WebServer *http.Server `name:"grpc-ui-server"`
    Logger    *zap.Logger
}

func GRPCUIModule() fx.Option {
    return fx.Module(
        "x:ui",
        fx.Provide(
            NewGRPCUIServer,
            fx.Annotate(
                NewGRPCUIServer,
                fx.ParamTags(``, ``, ``, ``, ``),
                fx.ResultTags(`name:"grpc-ui-server"`),
            ),
        ),
        fx.Invoke(func(params GRPCUIParams) {
            params.Logger.Info("gRPC UI Server initialized:", zap.String("address", params.WebServer.Addr))
        }),
    )
}

Mas por algum motivo está falhando em handlerViaReflection:

h, err := standalone.HandlerViaReflection(context.Background(), cc, rpcGrpcHost)
if err != nil {
    logger.Error("Failed to create UI handler", zap.Error(err))
    return nil, err
}

E está dando erro porque o servidor gRPC ainda não iniciou. Coloquei um breakpoint aqui no módulo do servidor:

fx.Invoke(func(lc fx.Lifecycle, server *grpc.Server, config Config, log *zap.Logger) {
    lc.Append(fx.Hook{
        OnStart: func(ctx context.Context) error {
            lis, err := NewListener(config)
            if err != nil {
                return err
            }

            go func(srv *grpc.Server, logger *zap.Logger) {
                logger.Info("Starting gRPC server")
                if err := srv.Serve(lis); err != nil && err != grpc.ErrServerStopped {
                    logger.Error("gRPC server failed", zap.Error(err))
                }
            }(server, log)

            return nil
        },

E não entra; ele sempre vai para o módulo UI primeiro. Ele cria o servidor: NewGRPCServer, mas nunca o inicializa. Alguém sabe como posso resolver isso?

go
  • 1 respostas
  • 28 Views
Martin Hope
Ming
Asked: 2024-10-25 20:56:52 +0800 CST

Substituir uma string em uma fatia de byte por uma nova string de comprimento diferente sem interferir em outros dados

  • 7

Estou trabalhando em um código onde sei a posição inicial de uma string em um pacote, e sei o terminador da string, que é 0x00 0x00 0x00. Preciso substituir a string antiga por uma nova, mas estou tendo um problema: a nova string pode ser maior ou menor que a antiga, e não posso interferir nos outros bytes do meu pacote. Alguém pode me ajudar com isso?

func replaceString(data []byte, newString string, startPos int) error {
    // Checks if the start position is valid
    if startPos >= len(data) || startPos < 0 {
        return fmt.Errorf("start position out of bounds")
    }

    terminatorPos := bytes.Index(data[startPos:], []byte{0x00, 0x00, 0x00})
    if terminatorPos == -1 {
        return fmt.Errorf("termination sequence not found")
    }

    buf := &bytes.Buffer{}
    packets.WriteS(buf, "testing long string")

    return nil
}

func WriteS(buf *bytes.Buffer, value string) {
    // Converter a string para UCS-2
    ucs2 := utf16.Encode([]rune(value))

    // Escrever os bytes da string em UCS-2 (little-endian)
    for _, char := range ucs2 {
        buf.WriteByte(byte(char & 0xff))        // Byte menos significativo
        buf.WriteByte(byte((char >> 8) & 0xff)) // Byte mais significativo
    }

    // Escrever o terminador null (2 bytes de 0x00)
    buf.WriteByte(0x00)
    buf.WriteByte(0x00)
    buf.WriteByte(0x00)
}
go
  • 1 respostas
  • 69 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve