Commit 0d8946a0 by Li Feifei

服务端错误返回code嘛

parent 1db452e8
...@@ -2,12 +2,14 @@ package helper ...@@ -2,12 +2,14 @@ package helper
import ( import (
"context" "context"
"errors"
"im-microservice/db"
"log" "log"
"math" "math"
"time" "time"
"im-microservice/db"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gopkg.in/go-playground/validator.v9" "gopkg.in/go-playground/validator.v9"
) )
...@@ -18,7 +20,7 @@ func Valiator(in interface{}) error { ...@@ -18,7 +20,7 @@ func Valiator(in interface{}) error {
if err != nil { if err != nil {
for _, err := range err.(validator.ValidationErrors) { for _, err := range err.(validator.ValidationErrors) {
log.Println("error == ", err) log.Println("error == ", err)
return errors.New("表单验证失败") return status.Error(codes.PermissionDenied, "表单验证失败")
} }
} }
return nil return nil
......
...@@ -3,34 +3,28 @@ package main ...@@ -3,34 +3,28 @@ package main
import ( import (
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"sync"
"log" "log"
"net" "net"
"regexp" "regexp"
"strconv" "strconv"
"sync"
"time" "time"
"im-microservice/helper" "im-microservice/helper"
"im-microservice/pb" "im-microservice/pb"
"im-microservice/sevice/im_chat_room" "im-microservice/sevice/im_chat_room"
ic "im-microservice/sevice/im_configure"
"im-microservice/sevice/im_user" "im-microservice/sevice/im_user"
iur "im-microservice/sevice/im_user_relationship" iur "im-microservice/sevice/im_user_relationship"
ic "im-microservice/sevice/im_configure"
"golang.org/x/net/context" "golang.org/x/net/context"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection" "google.golang.org/grpc/reflection"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
) )
type Health interface { type Health interface {
// Check returns if server is healthy or not // Check returns if server is healthy or not
Check(c context.Context) (bool, error) Check(c context.Context) (bool, error)
...@@ -47,15 +41,18 @@ func NewServer() *Server { ...@@ -47,15 +41,18 @@ func NewServer() *Server {
statusMap: make(map[string]pb.HealthCheckResponse_ServingStatus), statusMap: make(map[string]pb.HealthCheckResponse_ServingStatus),
} }
} }
func permissionError(msg string) error {
return status.Error(codes.InvalidArgument, msg)
}
func (s *Server) Check(ctx context.Context, in *pb.HealthCheckRequest) (*pb.HealthCheckResponse, error) { func (s *Server) Check(ctx context.Context, in *pb.HealthCheckRequest) (*pb.HealthCheckResponse, error) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
if in.Service == "" { if in.Service == "" {
return &pb.HealthCheckResponse{Status:pb.HealthCheckResponse_SERVING,},nil return &pb.HealthCheckResponse{Status: pb.HealthCheckResponse_SERVING}, nil
} }
if status, ok := s.statusMap[in.Service]; ok { if status, ok := s.statusMap[in.Service]; ok {
return &pb.HealthCheckResponse{Status:status,}, nil return &pb.HealthCheckResponse{Status: status}, nil
} }
return nil, status.Error(codes.NotFound, "unkonw service") return nil, status.Error(codes.NotFound, "unkonw service")
} }
...@@ -69,32 +66,30 @@ func checksum(req map[string]string) error { ...@@ -69,32 +66,30 @@ func checksum(req map[string]string) error {
err, AppSecret := helper.GetSecretByKey(req["Appkey"]) err, AppSecret := helper.GetSecretByKey(req["Appkey"])
if err != nil { if err != nil {
return errors.New("appkey不存在") return status.Error(codes.NotFound, "appkey不存在")
} }
server_time := time.Now().Unix() server_time := time.Now().Unix()
client_time, err := strconv.Atoi(req["Curtime"]) client_time, err := strconv.Atoi(req["Curtime"])
if err != nil { if err != nil {
return err return status.Error(codes.Aborted, err.Error())
} }
if server_time > int64(client_time) { if server_time > int64(client_time) {
return errors.New("当前客户端时间不能小于服务端时间") return permissionError("当前客户端时间不能小于服务端时间")
} }
sha11 := sha1.New() sha11 := sha1.New()
sha11.Write([]byte(AppSecret + req["Nonce"] + req["Curtime"])) sha11.Write([]byte(AppSecret + req["Nonce"] + req["Curtime"]))
sevice_checksum := hex.EncodeToString(sha11.Sum([]byte(nil))) sevice_checksum := hex.EncodeToString(sha11.Sum([]byte(nil)))
if sevice_checksum != req["Checksum"] { if sevice_checksum != req["Checksum"] {
return errors.New("加密串不正确") return permissionError("加密串不正确")
} }
return nil return nil
} }
func auth(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { func auth(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
_, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, grpc.Errorf(codes.Unauthenticated, "无Token认证信息")
}
if info.FullMethod != health_path { if info.FullMethod != health_path {
request_map := make(map[string]string) request_map := make(map[string]string)
s := fmt.Sprintf("%v", req) s := fmt.Sprintf("%v", req)
...@@ -110,27 +105,25 @@ func auth(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, hand ...@@ -110,27 +105,25 @@ func auth(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, hand
check_sum := cs_r.FindAllStringSubmatch(s, -1) check_sum := cs_r.FindAllStringSubmatch(s, -1)
if len(appkey) < 1 { if len(appkey) < 1 {
return nil, errors.New("缺少appkey") return nil, permissionError("缺少appkey")
} }
if len(nonce) < 1 { if len(nonce) < 1 {
return nil, errors.New("缺少nonce") return nil, permissionError("缺少nonce")
} }
if len(curtime) < 1 { if len(curtime) < 1 {
return nil, errors.New("缺少curtime") return nil, permissionError("缺少curtime")
} }
if len(check_sum) < 1 { if len(check_sum) < 1 {
return nil, errors.New("缺少checksum") return nil, permissionError("缺少checksum")
} }
request_map["Appkey"] = appkey[0][1] request_map["Appkey"] = appkey[0][1]
request_map["Nonce"] = nonce[0][1] request_map["Nonce"] = nonce[0][1]
request_map["Curtime"] = curtime[0][1] request_map["Curtime"] = curtime[0][1]
request_map["Checksum"] = check_sum[0][1] request_map["Checksum"] = check_sum[0][1]
if err := checksum(request_map); err != nil { if err := checksum(request_map); err != nil {
return nil, err return nil, err
} }
} }
return handler(ctx, req) return handler(ctx, req)
} }
...@@ -144,10 +137,8 @@ func main() { ...@@ -144,10 +137,8 @@ func main() {
var opts []grpc.ServerOption var opts []grpc.ServerOption
opts = append(opts, grpc.UnaryInterceptor(auth)) opts = append(opts, grpc.UnaryInterceptor(auth))
s := grpc.NewServer(opts...) s := grpc.NewServer(opts...)
// s := grpc.NewServer()
srv := NewServer() srv := NewServer()
pb.RegisterHealthServer(s, srv) pb.RegisterHealthServer(s, srv)
pb.RegisterConfigureSeviceServer(s, &ic.ConfigureSevice{}) pb.RegisterConfigureSeviceServer(s, &ic.ConfigureSevice{})
pb.RegisterChatRoomServiceServer(s, &im_chat_room.ImChatRoomService{}) pb.RegisterChatRoomServiceServer(s, &im_chat_room.ImChatRoomService{})
pb.RegisterImUserServer(s, &im_user.ImUserServer{}) pb.RegisterImUserServer(s, &im_user.ImUserServer{})
......
package im_chat_room package im_chat_room
import ( import (
"errors" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"im-microservice/db" "im-microservice/db"
"im-microservice/helper" "im-microservice/helper"
...@@ -31,7 +32,7 @@ func AddChatRoom(addStruct *validator_struct.ChatRoomAddStruct) (int64, error) { ...@@ -31,7 +32,7 @@ func AddChatRoom(addStruct *validator_struct.ChatRoomAddStruct) (int64, error) {
chat.Createtime = now chat.Createtime = now
chat.Updatetime = now chat.Updatetime = now
room_id, err := db.MysqlClient.Insert(&chat) room_id, err := db.MysqlClient.Insert(&chat)
return room_id, err return room_id, status.Error(codes.Internal, err.Error())
} }
func UpdateChatRoom(update *validator_struct.ChatRoomUpdate) error { func UpdateChatRoom(update *validator_struct.ChatRoomUpdate) error {
...@@ -47,7 +48,7 @@ func UpdateChatRoom(update *validator_struct.ChatRoomUpdate) error { ...@@ -47,7 +48,7 @@ func UpdateChatRoom(update *validator_struct.ChatRoomUpdate) error {
} }
if len(orm_params) == 0 { if len(orm_params) == 0 {
return errors.New("修改房间的参数为空") return status.Error(codes.InvalidArgument, "修改房间的参数为空")
} }
orm_params["updatetime"] = helper.GetNowTime() orm_params["updatetime"] = helper.GetNowTime()
_, err := db.MysqlClient.QueryTable(chat_table_name). _, err := db.MysqlClient.QueryTable(chat_table_name).
...@@ -59,11 +60,18 @@ func UpdateChatRoom(update *validator_struct.ChatRoomUpdate) error { ...@@ -59,11 +60,18 @@ func UpdateChatRoom(update *validator_struct.ChatRoomUpdate) error {
func DeleteChatRoom(room_id int64) error { func DeleteChatRoom(room_id int64) error {
_, err := db.MysqlClient.QueryTable(chat_table_name). _, err := db.MysqlClient.QueryTable(chat_table_name).
Filter(chat_room_id, room_id).Delete() Filter(chat_room_id, room_id).Delete()
return err if err != nil {
return status.Error(codes.Internal, err.Error())
}
return nil
} }
func ChatRoomInfo(info *validator_struct.ChatRoomInfo) (res db.ImChatRoom, err error) { func ChatRoomInfo(info *validator_struct.ChatRoomInfo) (res db.ImChatRoom, err error) {
err = db.MysqlClient.QueryTable(chat_table_name).Filter(chat_room_id, info.RoomId).One(&res) err = db.MysqlClient.QueryTable(chat_table_name).Filter(chat_room_id, info.RoomId).One(&res)
if err != nil {
err = status.Error(codes.Internal, err.Error())
}
return return
} }
...@@ -71,7 +79,7 @@ func GetChatRooms(request *pb.ChatRoomAllRequest) (results map[string]interface{ ...@@ -71,7 +79,7 @@ func GetChatRooms(request *pb.ChatRoomAllRequest) (results map[string]interface{
var ( var (
announcement = request.GetAnnouncement() announcement = request.GetAnnouncement()
name = request.GetName() name = request.GetName()
status = request.GetStatus() req_status = request.GetStatus()
creator = request.GetCreator() creator = request.GetCreator()
createtime = request.GetCreatetime() createtime = request.GetCreatetime()
page = request.GetPage() page = request.GetPage()
...@@ -86,8 +94,8 @@ func GetChatRooms(request *pb.ChatRoomAllRequest) (results map[string]interface{ ...@@ -86,8 +94,8 @@ func GetChatRooms(request *pb.ChatRoomAllRequest) (results map[string]interface{
if name != "" { if name != "" {
count_db = count_db.Filter(chat_room+"__icontains", name) count_db = count_db.Filter(chat_room+"__icontains", name)
} }
if status != 0 { if req_status != 0 {
count_db = count_db.Filter(chat_status, status) count_db = count_db.Filter(chat_status, req_status)
} }
if creator != "" { if creator != "" {
count_db = count_db.Filter(chat_creator, creator) count_db = count_db.Filter(chat_creator, creator)
......
...@@ -7,6 +7,9 @@ import ( ...@@ -7,6 +7,9 @@ import (
"im-microservice/helper" "im-microservice/helper"
"im-microservice/pb" "im-microservice/pb"
vs "im-microservice/validator_struct" vs "im-microservice/validator_struct"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
type ImChatRoomService struct { type ImChatRoomService struct {
...@@ -31,7 +34,6 @@ func (cr *ImChatRoomService) Add(ctx context.Context, ...@@ -31,7 +34,6 @@ func (cr *ImChatRoomService) Add(ctx context.Context,
func (cr *ImChatRoomService) Update(ctx context.Context, func (cr *ImChatRoomService) Update(ctx context.Context,
in *pb.ChatRoomUpdateRequest) (reply *pb.ChatRoomUpdateReply, err error) { in *pb.ChatRoomUpdateRequest) (reply *pb.ChatRoomUpdateReply, err error) {
chat_room_struct := vs.NewChatRoomUpdate(in) chat_room_struct := vs.NewChatRoomUpdate(in)
if err = helper.Valiator(chat_room_struct); err != nil { if err = helper.Valiator(chat_room_struct); err != nil {
return return
...@@ -89,6 +91,7 @@ func (cr *ImChatRoomService) All(ctx context.Context, ...@@ -89,6 +91,7 @@ func (cr *ImChatRoomService) All(ctx context.Context,
in *pb.ChatRoomAllRequest) (reply *pb.GetChatRoomsReply, err error) { in *pb.ChatRoomAllRequest) (reply *pb.GetChatRoomsReply, err error) {
results, err := GetChatRooms(in) results, err := GetChatRooms(in)
if err != nil { if err != nil {
err = status.Error(codes.Internal, err.Error())
return return
} }
reply = &pb.GetChatRoomsReply{Paginate: &pb.Page{}} reply = &pb.GetChatRoomsReply{Paginate: &pb.Page{}}
......
...@@ -2,9 +2,13 @@ package im_configure ...@@ -2,9 +2,13 @@ package im_configure
import ( import (
"errors" "errors"
"github.com/astaxie/beego/orm"
"im-microservice/db" "im-microservice/db"
"im-microservice/validator_struct" "im-microservice/validator_struct"
"github.com/astaxie/beego/orm"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
const ( const (
...@@ -18,6 +22,9 @@ func GetImBaseByUserId(user_id int64) (db.ImBase, error) { ...@@ -18,6 +22,9 @@ func GetImBaseByUserId(user_id int64) (db.ImBase, error) {
var im_base db.ImBase var im_base db.ImBase
err := db.MysqlClient.QueryTable(b_table_name). err := db.MysqlClient.QueryTable(b_table_name).
Filter(b_user_id, user_id).One(&im_base) Filter(b_user_id, user_id).One(&im_base)
if err != nil {
err = status.Error(codes.Internal, err.Error())
}
return im_base, err return im_base, err
} }
...@@ -27,14 +34,21 @@ func AddImBase(im *validator_struct.ConfigureAddStruct) error { ...@@ -27,14 +34,21 @@ func AddImBase(im *validator_struct.ConfigureAddStruct) error {
configure.MsgHookUrl = im.MsgHookUrl configure.MsgHookUrl = im.MsgHookUrl
configure.MultideviceType = im.MultideviceType configure.MultideviceType = im.MultideviceType
_, err := db.MysqlClient.Insert(configure) _, err := db.MysqlClient.Insert(configure)
return err if err != nil {
err = status.Error(codes.Internal, err.Error())
}
return nil
} }
func DelConfigure(user_id int64) error { func DelConfigure(user_id int64) (err error) {
configure := new(db.ImBase) configure := new(db.ImBase)
configure.CompanyUserId = user_id configure.CompanyUserId = user_id
_, err := db.MysqlClient.Delete(configure) _, err = db.MysqlClient.Delete(configure)
return err if err != nil {
err = status.Error(codes.Internal, err.Error())
return
}
return
} }
func GetConfigureAll() ([]*db.ImBase, error) { func GetConfigureAll() ([]*db.ImBase, error) {
...@@ -43,6 +57,9 @@ func GetConfigureAll() ([]*db.ImBase, error) { ...@@ -43,6 +57,9 @@ func GetConfigureAll() ([]*db.ImBase, error) {
if num == 0 { if num == 0 {
return configurs, nil return configurs, nil
} }
if err != nil {
err = status.Error(codes.Internal, err.Error())
}
return configurs, err return configurs, err
} }
......
...@@ -3,6 +3,8 @@ package im_configure ...@@ -3,6 +3,8 @@ package im_configure
import ( import (
"context" "context"
"errors" "errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"im-microservice/helper" "im-microservice/helper"
"im-microservice/pb" "im-microservice/pb"
...@@ -82,6 +84,7 @@ func (cs *ConfigureSevice) Update(ctx context.Context, ...@@ -82,6 +84,7 @@ func (cs *ConfigureSevice) Update(ctx context.Context,
} }
// 更新数据 // 更新数据
if err = UpdateConfiguer(configure_add_struct); err != nil { if err = UpdateConfiguer(configure_add_struct); err != nil {
err = status.Error(codes.Internal, err.Error())
return return
} }
reply = &pb.ConfigureReply{} reply = &pb.ConfigureReply{}
......
...@@ -2,10 +2,14 @@ package im_user_relationship ...@@ -2,10 +2,14 @@ package im_user_relationship
import ( import (
"errors" "errors"
"github.com/astaxie/beego/orm"
"im-microservice/db" "im-microservice/db"
"im-microservice/helper" "im-microservice/helper"
"im-microservice/validator_struct" "im-microservice/validator_struct"
"github.com/astaxie/beego/orm"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
var ( var (
...@@ -41,12 +45,18 @@ func AddUserRelationship(in *validator_struct.UserRelationshipAdd) error { ...@@ -41,12 +45,18 @@ func AddUserRelationship(in *validator_struct.UserRelationshipAdd) error {
us.Mute = open us.Mute = open
us.Createtime = now us.Createtime = now
_, err := db.MysqlClient.Insert(&us) _, err := db.MysqlClient.Insert(&us)
if err != nil {
err = status.Error(codes.Internal, err.Error())
}
return err return err
} }
func DBDelete(in *validator_struct.UserRelationshipDel) error { func DBDelete(in *validator_struct.UserRelationshipDel) error {
_, err := db.MysqlClient.QueryTable(db_tabel).Filter(db_field_accid, in.Accid). _, err := db.MysqlClient.QueryTable(db_tabel).Filter(db_field_accid, in.Accid).
Filter(db_field_faccid, in.Faccid).Delete() Filter(db_field_faccid, in.Faccid).Delete()
if err != nil {
err = status.Error(codes.Internal, err.Error())
}
return err return err
} }
......
...@@ -2,7 +2,9 @@ package im_user_relationship ...@@ -2,7 +2,9 @@ package im_user_relationship
import ( import (
"context" "context"
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"im-microservice/sevice/im_user" "im-microservice/sevice/im_user"
"im-microservice/helper" "im-microservice/helper"
...@@ -28,7 +30,7 @@ func (us *UserRelationshipService) Add(ctx context.Context, ...@@ -28,7 +30,7 @@ func (us *UserRelationshipService) Add(ctx context.Context,
return return
} }
if ok := IsUserRelationship(request.Accid, request.Faccid); ok { if ok := IsUserRelationship(request.Accid, request.Faccid); ok {
err = errors.New("已经添加过该好友") err = status.Error(codes.AlreadyExists, "已经添加过该好友")
return return
} }
//添加好友 //添加好友
...@@ -82,6 +84,7 @@ func (us *UserRelationshipService) All(ctx context.Context, ...@@ -82,6 +84,7 @@ func (us *UserRelationshipService) All(ctx context.Context,
results, err := DBAll(request) results, err := DBAll(request)
if err != nil { if err != nil {
err = status.Error(codes.Internal, err.Error())
return return
} }
reply = &pb.UserRelationshipListReply{} reply = &pb.UserRelationshipListReply{}
...@@ -108,6 +111,7 @@ func (us *UserRelationshipService) SetSpecialRelation(ctx context.Context, ...@@ -108,6 +111,7 @@ func (us *UserRelationshipService) SetSpecialRelation(ctx context.Context,
return return
} }
if err = SetSpecialRelationDb(request); err != nil { if err = SetSpecialRelationDb(request); err != nil {
err = status.Error(codes.Internal, err.Error())
return return
} }
reply = &pb.UserRelationshipAddReply{} reply = &pb.UserRelationshipAddReply{}
...@@ -127,6 +131,7 @@ func (us *UserRelationshipService) ListBlackAndMuteList(ctx context.Context, ...@@ -127,6 +131,7 @@ func (us *UserRelationshipService) ListBlackAndMuteList(ctx context.Context,
blacklist, mutelist, err := ListBlackAndMuteListDB(request) blacklist, mutelist, err := ListBlackAndMuteListDB(request)
if err != nil { if err != nil {
err = status.Error(codes.Internal, err.Error())
return return
} }
reply = &pb.ListBlackAndMuteListReply{} reply = &pb.ListBlackAndMuteListReply{}
......
...@@ -207,7 +207,7 @@ type SetSpecialRelation struct { ...@@ -207,7 +207,7 @@ type SetSpecialRelation struct {
Value int64 `validate:"required,numeric,min=1"` Value int64 `validate:"required,numeric,min=1"`
} }
func NewSetSpecialRelation(in map[string]interface{}) *SetSpecialRelation{ func NewSetSpecialRelation(in map[string]interface{}) *SetSpecialRelation {
return &SetSpecialRelation{ return &SetSpecialRelation{
Accid: in["accid"].(string), Accid: in["accid"].(string),
TargetAcc: in["faccid"].(string), TargetAcc: in["faccid"].(string),
...@@ -222,5 +222,5 @@ type ListBlackAndMuteList struct { ...@@ -222,5 +222,5 @@ type ListBlackAndMuteList struct {
} }
func NewListBlackAndMuteList(in map[string]interface{}) *ListBlackAndMuteList { func NewListBlackAndMuteList(in map[string]interface{}) *ListBlackAndMuteList {
return &ListBlackAndMuteList{Accid:in["accid"].(string)} return &ListBlackAndMuteList{Accid: in["accid"].(string)}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment