数据 输入输出 处理
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.3 KiB

package dbOperate
import (
"fmt"
"goInOut/config"
"log"
"net/http"
)
type ApiServerHelper struct {
mux *http.ServeMux
routes []config.Router
port uint
server http.Server
}
func NewApiServer(port uint, routes []config.Router) *ApiServerHelper {
return &ApiServerHelper{
mux: http.NewServeMux(),
routes: routes,
port: port,
}
}
func (the *ApiServerHelper) Initial() {
the.mux = http.NewServeMux()
// 创建 HTTP 服务器
the.server = http.Server{
Handler: the.mux,
Addr: fmt.Sprintf(":%d", the.port),
}
//the.routeRegister()
}
func (the *ApiServerHelper) Run() {
log.Printf("apiServer监听端口 %d", the.port)
the.server.ListenAndServe()
}
func (the *ApiServerHelper) routeRegister() {
for _, route := range the.routes {
the.mux.HandleFunc(route.Router, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
s := fmt.Sprintf(`{"route":"%s","resp":"安全带状态应答"}`, route)
println("收到请求", route.Router)
fmt.Fprintf(w, s)
})
log.Printf("注册路由 %s", route)
}
}
func (the *ApiServerHelper) RouteRegister(route string, handler func(w http.ResponseWriter, r *http.Request)) {
the.mux.HandleFunc(route, handler)
log.Printf("注册路由 %s", route)
}