gRPC 上报系统信息

This commit is contained in:
奶爸
2019-12-07 18:14:40 +08:00
parent 6f623ff138
commit 5a21ce6ca6
8 changed files with 294 additions and 125 deletions

View File

@@ -1,35 +1,22 @@
package main
import (
"context"
"fmt"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
pb "github.com/p14yground/nezha/proto"
"github.com/p14yground/nezha/service/handler"
)
// NezhaService ..
type NezhaService struct {
auth *Auth
}
// ReportState ..
func (s *NezhaService) ReportState(ctx context.Context, r *pb.State) (*pb.Receipt, error) {
if err := s.auth.Check(ctx); err != nil {
return nil, err
}
fmt.Printf("receive: %s\n", r)
return &pb.Receipt{}, nil
}
func main() {
server := grpc.NewServer()
pb.RegisterNezhaServiceServer(server, &NezhaService{})
pb.RegisterNezhaServiceServer(server, &handler.NezhaHandler{
Auth: &handler.AuthHandler{
AppKey: "naiba",
AppSecret: "123456",
},
})
lis, err := net.Listen("tcp", ":5555")
if err != nil {
@@ -38,44 +25,3 @@ func main() {
server.Serve(lis)
}
// Auth ..
type Auth struct {
appKey string
appSecret string
}
// Check ..
func (a *Auth) Check(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Errorf(codes.Unauthenticated, "metadata.FromIncomingContext err")
}
var (
appKey string
appSecret string
)
if value, ok := md["app_key"]; ok {
appKey = value[0]
}
if value, ok := md["app_secret"]; ok {
appSecret = value[0]
}
if appKey != a.GetAppKey() || appSecret != a.GetAppSecret() {
return status.Errorf(codes.Unauthenticated, "invalid token")
}
return nil
}
// GetAppKey ..
func (a *Auth) GetAppKey() string {
return "naiba"
}
// GetAppSecret ..
func (a *Auth) GetAppSecret() string {
return "nbsecret"
}