登录代码提交

This commit is contained in:
tangping
2025-01-15 17:36:12 +08:00
parent 8c40855c4e
commit 22ac6c1fed
39 changed files with 2551 additions and 189 deletions

View File

@@ -0,0 +1,176 @@
package server_http
import (
"encoding/json"
"framework/ipMgr"
"io/ioutil"
"net/http"
. "common/model"
"goutil/debugUtil"
"goutil/logUtil"
"goutil/webUtil"
"goutil/zlibUtil"
)
// 请求上下文对象
type Context struct {
// 请求对象
*http.Request
// 应答写对象
http.ResponseWriter
// 请求数据
requestBytes []byte
// 数据是否已经解析数据
ifDataParsed bool
// Form的数据是否已经解析
ifFormParsed bool
}
// 检查IP是否合法
func (this *Context) checkIP() *ResultStatus {
if debugUtil.IsDebug() == false && ipMgr.IsIpValid(webUtil.GetRequestIP(this.Request)) == false {
return InvalidIP
}
return Success
}
func (this *Context) GetFormValue(key string) (value string, exists bool) {
defer func() {
this.ifFormParsed = true
}()
if !this.ifFormParsed {
this.Request.ParseForm()
}
values := this.Form[key]
if values != nil && len(values) > 0 {
value = values[0]
exists = true
return
}
return
}
// 转换内容
func (this *Context) parseContent() error {
defer func() {
this.Body.Close()
this.ifDataParsed = true
}()
data, err := ioutil.ReadAll(this.Body)
if err != nil {
logUtil.ErrorLog("url:%s,读取数据出错,错误信息为:%s", this.RequestURI, err)
return err
}
this.requestBytes = data
return nil
}
// 获取请求字节数据
// 返回值:
// []byte:请求字节数组
// error:错误信息
func (this *Context) GetRequestBytes(isCompressed bool) (result []byte, exists bool, err error) {
if this.ifDataParsed == false {
this.parseContent()
}
data := this.requestBytes
if data == nil || len(data) <= 0 {
return
} else {
exists = true
}
if isCompressed {
result, err = zlibUtil.Decompress(data)
if err != nil {
logUtil.ErrorLog("解压缩请求数据失败:%s", err)
return
}
} else {
result = data
}
return
}
// 获取请求字符串数据
// 返回值:
// 请求字符串数据
func (this *Context) GetRequestString(isCompressed bool) (result string, exists bool, err error) {
var data []byte
data, exists, err = this.GetRequestBytes(isCompressed)
if err != nil || !exists {
return
}
result = string(data)
exists = true
return
}
// Unmarshal 反序列化
// moduleName:模块名称
// obj:反序列化结果数据
// isCompressed:数据是否已经被压缩
// 返回值:
// 错误对象
func (this *Context) Unmarshal(moduleName string, obj interface{}, isCompressed bool) (exists bool, err error) {
var data []byte
data, exists, err = this.GetRequestBytes(isCompressed)
if err != nil || !exists {
return
}
// 反序列化
if err = json.Unmarshal(data, &obj); err != nil {
logUtil.ErrorLog("Module:%s, 反序列化%s出错错误信息为%s", moduleName, string(data), err)
return
}
debugUtil.Printf("接收到GM登录数据data:%v", string(data))
return
}
// 输出字符串
func (this *Context) WriteString(result string) {
this.ResponseWriter.Write([]byte(result))
}
// 输出json数据
func (this *Context) WriteJson(result interface{}) {
if bytes, err := json.Marshal(result); err == nil {
this.ResponseWriter.Write(bytes)
}
}
// 跳转到其它页面
func (this *Context) RedirectTo(url string) {
this.ResponseWriter.Header().Set("Location", url)
this.ResponseWriter.WriteHeader(301)
}
// 新建API上下文对象
// request:请求对象
// responseWriter:应答写对象
// 返回值:
// *Context:上下文
func newContext(request *http.Request, responseWriter http.ResponseWriter) *Context {
return &Context{
Request: request,
ResponseWriter: responseWriter,
}
}

View File

@@ -0,0 +1,37 @@
package server_http
import (
"fmt"
. "common/model"
)
type Handler func(*Context) *ServerResponseObject
var (
// 处理函数集合
handlerMap map[string]Handler
)
func init() {
handlerMap = make(map[string]Handler, 8)
}
// RegisterHandler 详细的注册一个WebAPI处理函数
// pattern:路由地址
// handler:处理函数
// paramInfo:参数列表
func RegisterHandler(pattern string, handler Handler) {
if _, exist := handlerMap[pattern]; exist {
panic(fmt.Errorf("存在重复的webapi注册%s", pattern))
}
// 添加处理对象
handlerMap[pattern] = handler
}
// 获取处理函数
func getHandler(pattern string) (handler Handler, exists bool) {
handler, exists = handlerMap[pattern]
return
}

View File

@@ -0,0 +1,71 @@
package server_http
import (
"encoding/json"
"net/http"
. "common/model"
"goutil/debugUtil"
"goutil/logUtil"
"goutil/webUtil"
)
// http服务对象
type httpServer struct{}
// http应答处理
// response:应答对象
// request:请求对象
func (this *httpServer) ServeHTTP(response http.ResponseWriter, request *http.Request) {
context := newContext(request, response)
responseObj := NewServerResponseObject()
defer func() {
if data := recover(); data != nil {
logUtil.LogUnknownError(data)
return
}
// 特殊路径进行特别处理
if request.URL.Path == "/" || request.URL.Path == "/favicon.ico" {
return
}
// 获取输入参数的字符串形式
parameter := ""
if len(request.Form) > 0 {
parameter_byte, _ := json.Marshal(request.Form)
parameter = string(parameter_byte)
}
// 记录日志
if debugUtil.IsDebug() || responseObj.ResultStatus != Success {
result, _ := json.Marshal(responseObj)
logUtil.DebugLog("%s-->IP:%s;Request:%v;Response:%s;", request.URL.Path, webUtil.GetRequestIP(request), parameter, string(result))
}
}()
// 特殊路径进行特别处理
if request.URL.Path == "/" || request.URL.Path == "/favicon.ico" {
context.WriteString("ok")
return
}
// 验证IP
if rs := context.checkIP(); rs != Success {
context.WriteJson(responseObj.SetResultStatus(rs))
return
}
var handler Handler
var exists bool
if handler, exists = getHandler(request.URL.Path); !exists {
logUtil.ErrorLog("访问的页面不存在RequestAddr: %s request.URL.Path: %s", request.RemoteAddr, request.URL.Path)
http.Error(response, "访问的页面不存在", 404)
return
}
// 调用处理方法,并返回结果
responseObj = handler(context)
context.WriteJson(responseObj)
}

View File

@@ -0,0 +1,44 @@
package server_http
import (
"fmt"
"net/http"
"net/http/pprof"
"sync"
)
// 启动Web服务器
// wg:WaitGroup对象
// address:服务器地址
func Start(wg *sync.WaitGroup, address string) {
defer func() {
wg.Done()
}()
//// 开启服务
//serverInstance := http.Server{
// Addr: address,
// Handler: new(httpServer),
//}
//// 开启监听
//msg := fmt.Sprintf("server_http begins to listen on: %s...", address)
//fmt.Println(msg)
//logUtil.InfoLog(msg)
// 启动Web服务器监听
mux := http.NewServeMux()
mux.Handle("/", &httpServer{})
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
if err := http.ListenAndServe(address, mux); err != nil {
panic(fmt.Sprintf("server_http ListenAndServe Error:%v", err))
}
//if err := serverInstance.ListenAndServe(); err != nil {
// panic(fmt.Sprintf("server_http ListenAndServe Error:%v", err))
//}
}