数据 输入输出 处理
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.

50 lines
1001 B

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