This commit is contained in:
aozhiwei 2020-10-22 16:55:13 +08:00
parent 2674163215
commit 69d556c643

55
httpserver.go Normal file
View File

@ -0,0 +1,55 @@
package f5
import (
"net/http"
"sync"
"fmt"
"q5"
)
type HttpServer struct {
handlersMutex sync.RWMutex
handlers map[string]func(http.ResponseWriter, *http.Request)
}
func (this *HttpServer) Init() *HttpServer {
this.handlers = make(map[string]func(http.ResponseWriter, *http.Request))
http.HandleFunc("/webapp/index.php", this.dispatchRequest)
this.RegisterHandle("Ops", "selfChecking", func (w http.ResponseWriter,r *http.Request) {
w.Write([]byte(`{"errcode":0, "errmsg":"", "health":1, "max_rundelay": 10}`))
})
fmt.Println("HttpServer.Init\n")
return this
}
func (this *HttpServer) UnInit() {
fmt.Println("HttpServer.UnInit\n")
}
func (this *HttpServer) Start(listen_port int32) {
go http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", listen_port), nil)
}
func (this *HttpServer) dispatchRequest(w http.ResponseWriter, r *http.Request) {
handleName := q5.Request(r, "c").GetString() + "$" + q5.Request(r, "a").GetString()
handle := this.getHandle(handleName)
if handle != nil {
handle(w, r)
} else {
w.Write([]byte(`{"errcode":404, "errmsg":"接口不存在"}`))
}
}
func (this *HttpServer) getHandle(handleName string) (func(http.ResponseWriter, *http.Request)) {
this.handlersMutex.Lock()
defer this.handlersMutex.Unlock()
handle, _ := this.handlers[handleName]
return handle
}
func (this *HttpServer) RegisterHandle(c string, a string, handle func(http.ResponseWriter, *http.Request)) {
this.handlersMutex.Lock()
defer this.handlersMutex.Unlock()
handleName := c + "$" + a
this.handlers[handleName] = handle
}