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