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.

44 lines
1.0 KiB

package nwweb
import (
"fmt"
"net/http"
)
type Server struct {
httpServeMux *http.ServeMux
httpServer *http.Server
}
func NewServer(hostname string, port int) *Server {
mux := http.NewServeMux()
return &Server{
httpServeMux: mux,
httpServer: &http.Server{
Addr: fmt.Sprintf("%s:%d", hostname, port),
Handler: mux,
},
}
}
func (s *Server) RegisterFunc(pattern, method string, handler func(response *Response, request *Request)) {
s.httpServeMux.HandleFunc(pattern, func(httpResponseWriter http.ResponseWriter, httpRequest *http.Request) {
if len(method) == 0 || method == "*" || method == httpRequest.Method {
handler(newResponseServer(httpResponseWriter), newRequestServer(httpRequest))
return
}
httpResponseWriter.WriteHeader(http.StatusMethodNotAllowed)
})
}
func (s *Server) RegisterController(controller IController) {
for _, route := range controller.GetRoutes() {
s.RegisterFunc(route.Pattern, route.Method, route.Handler)
}
}
func (s *Server) Start() error {
return s.httpServer.ListenAndServe()
}