// Copyright (c) 2021. Huawei Technologies Co., Ltd. All rights reserved.

// Package common the common package of the program
package common

import (
"errors"
"github.com/gin-gonic/gin"
"golang.org/x/net/context"
"huawei.com/npu-exporter/hwlog"
"net/http"
"strconv"
)

const (
base = 10
bitSize = 64

// HeaderUserIDKey HeaderUserIDKey
HeaderUserIDKey = "UserID"
// HeaderGroupIDKey HeaderGroupIDKey
HeaderGroupIDKey = "GroupID"
// HeaderRoleIDKey HeaderRoleIDKey
HeaderRoleIDKey = "RoleID"
// HeaderRequestIDKey HeaderRequestIDKey
HeaderRequestIDKey = "RequestID"
// HeaderRoleCodeKey HeaderRoleCodeKey
HeaderRoleCodeKey = "RoleCode"
)

// RespMsg response msg
type RespMsg struct {
Status string `json:"status"`
Msg string `json:"msg"`
Data interface{} `json:"data,omitempty"`
}

// HeaderInfo header struct
type HeaderInfo struct {
TraceID string `sql:"-" json:"requestID,omitempty"`
UserID uint64 `gorm:"" json:"userId,omitempty"`
GroupID uint64 `gorm:"" json:"groupId,omitempty"`
RoleID uint64 `sql:"-" json:"roleId,omitempty"`
RoleCode string `sql:"-" json:"roleCode,omitempty"`
}

// ConstructResp construct response
func ConstructResp(c *gin.Context, errorCode string, msg string, data interface{}) {
ConstructRespWithStatus(c, errorCode, msg, data, http.StatusOK)
}

// ConstructRespWithStatus construct response
func ConstructRespWithStatus(c *gin.Context, errorCode string, msg string, data interface{}, status int) {
if msg == "" {
msg = ErrorMap[errorCode]
}
result := RespMsg{
Status: errorCode,
Msg: msg,
Data: data,
}
c.JSON(status, result)
}

// GetHeaderInfo get header info
func GetHeaderInfo(c *gin.Context) (HeaderInfo, string, error) {
var hInfo HeaderInfo
uuid := c.GetHeader(HeaderRequestIDKey)
hInfo.TraceID = uuid
userIDStr := c.GetHeader(HeaderUserIDKey)
if userIDStr == "" {
return HeaderInfo{}, ErrorNotFoundUserID, errors.New("no login")
}
userID, err := strconv.ParseUint(userIDStr, base, bitSize)
if err != nil {
return HeaderInfo{}, ErrorConvertStr2Uint, errors.New("convert userID failed")
}
hInfo.UserID = userID
groupIDStr := c.GetHeader(HeaderGroupIDKey)
if groupIDStr == "" {
return hInfo, ErrorNotFoundGroupID, errors.New("not found groupID")
}
groupID, err := strconv.ParseUint(groupIDStr, base, bitSize)
if err != nil {
return HeaderInfo{}, ErrorConvertStr2Uint, errors.New("convert groupID failed")
}
hInfo.GroupID = groupID
roleIDStr := c.GetHeader(HeaderRoleIDKey)
if roleIDStr == "" {
return hInfo, ErrorNotFoundRoleID, errors.New("not found roleID")
}
roleID, err := strconv.ParseUint(roleIDStr, base, bitSize)
if err != nil {
return HeaderInfo{}, ErrorConvertStr2Uint, errors.New("convert groupID failed")
}
hInfo.RoleID = roleID
code := c.GetHeader(HeaderRoleCodeKey)
hInfo.RoleCode = code
return hInfo, "", nil
}

// BaseCtx the base of all controller
type BaseCtx struct {
Ctx context.Context
HdInfo HeaderInfo
}

// WrapHeader check and wrap the header parameter
func WrapHeader() gin.HandlerFunc {
return func(c *gin.Context) {
hInfo, errorCode, err := GetHeaderInfo(c)
if err != nil {
hwlog.OpLog.Error(err)
c.Abort()
ConstructRespWithStatus(c, errorCode, err.Error(), nil, http.StatusUnauthorized)
return
}
ctx := context.WithValue(context.TODO(), hwlog.ReqID, hInfo.TraceID)
ctx = context.WithValue(ctx, hwlog.UserID, hInfo.UserID)
baseCtx := BaseCtx{
Ctx: ctx,
HdInfo: hInfo,
}
c.Set("Ctx", baseCtx)
}
}

// Convert extract the baseCtx from gin.context and use as a parameter
func Convert(f func(b BaseCtx, c *gin.Context)) gin.HandlerFunc {
return func(c *gin.Context) {
baseCtx, ok := c.Get("Ctx")
if !ok {
ConstructResp(c, ErrNoLoginInfo, "", nil)
}
b, err := baseCtx.(BaseCtx)
if !err {
ConstructResp(c, ErrTypeConvert, "", nil)
}
f(b, c)
}
}

mindxdl--common--head_handler.go的更多相关文章

  1. Socket聊天程序——Common

    写在前面: 上一篇记录了Socket聊天程序的客户端设计,为了记录的完整性,这里还是将Socket聊天的最后一个模块--Common模块记录一下.Common的设计如下: 功能说明: Common模块 ...

  2. angularjs 1 开发简单案例(包含common.js,service.js,controller.js,page)

    common.js var app = angular.module('app', ['ngFileUpload']) .factory('SV_Common', function ($http) { ...

  3. Common Bugs in C Programming

    There are some Common Bugs in C Programming. Most of the contents are directly from or modified from ...

  4. ANSI Common Lisp Practice - My Answers - Chatper - 3

    Ok, Go ahead. 1 (a) (b) (c) (d) 2 注:union 在 Common Lisp 中的作用就是求两个集合的并集.但是这有一个前提,即给的两个列表已经满足集合的属性了.具体 ...

  5. [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  6. [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  7. [LeetCode] Longest Common Prefix 最长共同前缀

    Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...

  8. 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]

    [题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下:  C++ Code  123456   struct BinaryTreeNode {     int ...

  9. 动态规划求最长公共子序列(Longest Common Subsequence, LCS)

    1. 问题描述 子串应该比较好理解,至于什么是子序列,这里给出一个例子:有两个母串 cnblogs belong 比如序列bo, bg, lg在母串cnblogs与belong中都出现过并且出现顺序与 ...

  10. 【leetcode】Longest Common Prefix

    题目简述: Write a function to find the longest common prefix string amongst an array of strings. 解题思路: c ...

随机推荐

  1. multiprocessing 让子进程忽略信号,手动关闭子进程

    起因 同事想要写一个代码,主进程中监听SIGINT.SIGTERM信号退出,并关闭启动的子进程,代码类似这样 import signal import sys import time from mul ...

  2. Spark 读Hive并写入HBase

    package com.grady import org.apache.hadoop.hbase.HBaseConfiguration import org.apache.hadoop.hbase.c ...

  3. PLM产品生命周期管理,包含哪些阶段?

    PLM:Product Lifecycle Management=产品生命周期管理.产品的整个生命周期包括:投入期.成长期.成熟期.衰退期.结束期.PLM系统使企业可以把多年积累的所有产品相关数据放到 ...

  4. 清源正本,鉴往知来,Go lang1.18入门精炼教程,由白丁入鸿儒,Golang中引用类型是否进行引用传递EP18

    开篇明义,Go lang中从来就不存在所谓的"引用传递",从来就只有一种变量传递方式,那就是值传递.因为引用传递的前提是存在"引用变量",但是Go lang中从 ...

  5. 阿色全息脑图,及制作软件AHMM

    阿色全息脑图 AHMM 全息脑图是按照大系统观原理开发的新型思维工具,用于升维思考. 让您以系统的观点看待世界,专注系统的结构信息--全息,抓住事物的本质,透过表象和数据发现规律. 世间每项事物都是一 ...

  6. liunx标准输入与输出

    一.Linux提供了三种输入/输出通道给程序在linux中,每个进程都会有三个文件,并且这三个文件会进行重定向处理:1. 标准输入(STDIN) - 缺省为键盘2. 标准输出(STDOUT) - 默认 ...

  7. 01 uniapp/微信小程序 项目day01

    一.起步 1.1 配置uni-app开发环境 什么是uni-app,就是基于vue的一个开发框架,可以将我们写的一套代码,同时发布到ios.安卓.小程序等多个平台 官方推荐使用Hbuilderx来写u ...

  8. ProxySQL(11):链式规则( flagIN 和 flagOUT )

    文章转载自:https://www.cnblogs.com/f-ck-need-u/p/9350631.html 理解链式规则 在mysql_query_rules表中,有两个特殊字段"fl ...

  9. 查看pod创建时使用yaml文件内容

    除了 kubectl describe pod 以外,另一种获取 Pod 额外信息(除了 kubectl get pod)的方法 是给 kubectl get pod 增加 -o yaml 输出格式参 ...

  10. 使用ConfigMap配置您的应用程序

    转载自:https://kuboard.cn/learning/k8s-intermediate/config/config-map.html ConfigMap 作为 Kubernetes API ...