-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin_context.go
202 lines (180 loc) · 8.25 KB
/
gin_context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
//"reflect"
"strings"
)
var ginConfigAPITable = map[string]map[string]gin.HandlerFunc{
"/api/0/config/institute": instituteConfigHandlerTable,
"/api/0/config/teacher": teacherConfigHandlerTable,
"/api/0/config/course": courseConfigHandlerTable,
"/api/0/config/course_record": courseRecordConfigHandlerTable,
"/api/0/config/course_comment": courseCommentConfigHandlerTable,
"/api/0/config/relative": relativeConfigHandlerTable,
"/api/0/config/student": studentConfigHandlerTable,
"/api/0/config/cloudmedia": cloudMediaConfigHandlerTable,
"/api/0/config/reference/student_relative": studentRelativeRefConfigHandlerTable,
"/api/0/config/reference/student_course": studentCourseRefConfigHandlerTable,
}
var ginWorkflowAPITable = map[string]gin.HandlerFunc{
"/api/0/workflow/teacher/login": teacherLoginHandler,
"/api/0/workflow/student/generatecode": studentGenerateCodeHandler,
"/api/0/workflow/student/bind": studentBindingRelativeHandler,
"/api/0/workflow/student/unbind": studentUnbindingRelativeHandler,
"/api/0/workflow/student/mediaquery": studentMediaQueryHandler,
"/api/0/workflow/relative/wxlogin": relativeWeChatLoginHandler,
"/api/0/workflow/relative/findstudent": relativeFindBoundStudentHandler,
// "/api/0/workflow/relative/extra/add": relativeExtraAddHandler,
// "/api/0/workflow/relative/extra/delete": relativeExtraDeleteHandler,
}
// GinParameter a generic paramter wrapper for gin web framework handler
type GinParameter struct {
Token string // auth token
PID string // primary id
SID string // secondary id
Data []byte // data content
}
// GinResponse a generic response struct for gin web framework handler
type GinResponse struct {
Status int `json:"-"`
Message string `json:"message"`
Payload interface{} `json:"payload"`
}
func ginContextRequestParameter(ctx *gin.Context) *GinParameter {
var tokenString string = ""
if token, exist := ctx.Get("JWT_TOKEN"); exist {
tokenString = token.(string)
}
var primaryKey = ctx.Request.URL.Query().Get("pid")
var secondarykey = ctx.Request.URL.Query().Get("sid")
var bodyData []byte = nil
switch strings.ToLower(ctx.Request.Method) {
case "post", "put":
if reqBuffer, err := ioutil.ReadAll(ctx.Request.Body); err != nil {
logging.Warnmf(logModGinContext, "Http request body read err: %v\n", err.Error())
} else {
bodyData = reqBuffer
}
default:
}
return &GinParameter{tokenString, primaryKey, secondarykey, bodyData}
}
func ginContextProcessResponse(ctx *gin.Context, response *GinResponse) {
responseContent := gin.H{}
if response.Status == http.StatusOK {
if response.Payload != nil {
responseContent["payload"] = response.Payload
} else {
// payload should exist with http status ok ==> internal error occurs
response.Status = http.StatusInternalServerError
responseContent["message"] = fmt.Sprintf("[%s] - Please check error log", serverErrorMessages[seUnresolvedError])
}
if len(response.Message) > 0 {
responseContent["message"] = response.Message
}
} else {
responseContent["message"] = response.Message
}
ctx.JSON(response.Status, responseContent)
logging.Debugmf(logModGinContext, "GIN: [%s] FROM %v | URL %v | RESPONSE CODE %v", ctx.Request.Method, ctx.Request.RemoteAddr, ctx.Request.URL, response.Status)
}
/* gin input struct check */
// func ginStructValidCheck(input interface{}) error {
// val := reflect.ValueOf(input)
// if val.Kind() == reflect.Ptr {
// val = reflect.Indirect(val)
// }
// if val.Kind() != reflect.Struct {
// return fmt.Errorf("[%s] - unexpected type (%s) - struct required", serverErrorMessages[seInputSchemaNotValid], val.Type().Name())
// }
// structType := val.Type()
// for i := 0; i < structType.NumField(); i++ {
// field := structType.Field(i)
// fieldName := field.Name
// logging.Tracemf(logModGinContext, "check struct (%s) field: %s", val.Type().Name(), fieldName)
// switch fieldName {
// case "InstituteUID", "ClassUID", "TeacherUID", "StudentUID", "ParentUID",
// "Name", "InstituteName", "ClassName", "StudentName", "ParentName",
// "Address", "CountryCode", "Location", "MediaLocation",
// "PhoneNumber", "Email", "Occupation":
// if len(val.FieldByName(fieldName).Interface().(string)) < 1 {
// return fmt.Errorf("[%s] - invalid struct (%s) field: %s", serverErrorMessages[seInputSchemaNotValid], structType.Name(), fieldName)
// }
// break
// case "Password":
// if len(val.FieldByName(fieldName).Interface().(string)) < 5 {
// return fmt.Errorf("[%s] - invalid struct (%s) field: %s (at least 5 length)", serverErrorMessages[seInputSchemaNotValid], structType.Name(), fieldName)
// }
// break
// case "PID":
// if val.FieldByName(fieldName).Interface().(int) < 0 {
// return fmt.Errorf("[%s] - invalid struct (%s) field: %s (require postive value)", serverErrorMessages[seInputSchemaNotValid], structType.Name(), fieldName)
// }
// break
// case "InstitutePID", "ClassPID", "StudentPID", "TeacherPID", "ParentPID":
// pid := val.FieldByName(fieldName).Interface().(null.Int)
// if pid.Valid && pid.ValueOrZero() <= 0 {
// return fmt.Errorf("[%s] - invalid struct (%s) field: %s (require postive value)", serverErrorMessages[seInputSchemaNotValid], structType.Name(), fieldName)
// }
// break
// }
// }
// return nil
// }
// func ginStructEqualCheck(x, y interface{}) error {
// valx := reflect.ValueOf(x)
// if valx.Kind() == reflect.Ptr {
// valx = reflect.Indirect(valx)
// }
// valy := reflect.ValueOf(y)
// if valy.Kind() == reflect.Ptr {
// valy = reflect.Indirect(valy)
// }
// if valx.Kind() != reflect.Struct || valy.Kind() != reflect.Struct {
// return fmt.Errorf("[%s] - unexpected type (%s, %s) - struct required", serverErrorMessages[seInputSchemaNotValid], valx.Type().Name(), valy.Type().Name())
// }
// structTypex := valx.Type()
// structTypey := valy.Type()
// if structTypex.Name() != structTypey.Name() {
// return fmt.Errorf("[%s] - inconsistent type (%s != %s) ", serverErrorMessages[seInputSchemaNotValid], valx.Type().Name(), valy.Type().Name())
// }
// for i := 0; i < structTypex.NumField(); i++ {
// field := structTypex.Field(i)
// fieldName := field.Name
// logging.Tracemf(logModGinContext, "compare struct [%s]: field [%s]", valx.Type().Name(), fieldName)
// switch fieldName {
// case "InstituteUID", "ClassUID", "TeacherUID", "StudentUID", "ParentUID",
// "Name", "InstituteName", "ClassName", "FirstName", "LastName",
// "Address", "CountryCode", "Location", "MediaLocation",
// "DateOfBirth", "PhoneNumber", "Email", "Occupation":
// if valx.FieldByName(fieldName).Interface().(string) != valy.FieldByName(fieldName).Interface().(string) {
// return fmt.Errorf("[%s] - field (%s) not equal in struct (%s)", serverErrorMessages[seInputSchemaNotValid], fieldName, valx.Type().Name())
// }
// break
// case "PID":
// if valx.FieldByName(fieldName).Interface().(int) != valy.FieldByName(fieldName).Interface().(int) {
// return fmt.Errorf("[%s] - field (%s) not equal in struct (%s)", serverErrorMessages[seInputSchemaNotValid], fieldName, valx.Type().Name())
// }
// break
// case "InstitutePID", "ClassPID", "TeacherPID", "StudentPID", "ParentPID":
// if valx.FieldByName(fieldName).Interface().(int) != valy.FieldByName(fieldName).Interface().(int) {
// return fmt.Errorf("[%s] - field (%s) not equal in struct (%s)", serverErrorMessages[seInputSchemaNotValid], fieldName, valx.Type().Name())
// }
// break
// case "Enabled":
// if valx.FieldByName(fieldName).Interface().(bool) != valy.FieldByName(fieldName).Interface().(bool) {
// return fmt.Errorf("[%s] - field (%s) not equal in struct (%s)", serverErrorMessages[seInputSchemaNotValid], fieldName, valx.Type().Name())
// }
// break
// case "PIDs":
// if !isIntListEqual(valx.FieldByName(fieldName).Interface().([]int), valy.FieldByName(fieldName).Interface().([]int)) {
// return fmt.Errorf("[%s] - field (%s) not equal in struct (%s)", serverErrorMessages[seInputSchemaNotValid], fieldName, valx.Type().Name())
// }
// break
// }
// }
// return nil
// }