Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
SantiagoAriasDev committed Jun 28, 2020
0 parents commit 1aafbd5
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 0 deletions.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/soy4rias/web_server

go 1.14
46 changes: 46 additions & 0 deletions router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package web_server

import (
"net/http"
)

type Router struct {
rules map[string]map[string]http.HandlerFunc
}

func (r *Router) FindHandler(method string, path string) (http.HandlerFunc, bool, bool) {
var pathExists, methodExists bool
var handler http.HandlerFunc

_, pathExists = r.rules[path]

handler, methodExists = r.rules[path][method]

return handler, pathExists, methodExists
}

func NewRouter() *Router {
return &Router{
rules: make(map[string]map[string]http.HandlerFunc),
}
}

func (r *Router) ServeHTTP(w http.ResponseWriter, request *http.Request) {

var pathExists, methodExists bool
var handler http.HandlerFunc

handler, pathExists, methodExists = r.FindHandler(request.Method, request.URL.Path)

if !pathExists {
w.WriteHeader(http.StatusNotFound)
return
}

if !methodExists {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}

handler(w, request)
}
56 changes: 56 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package web_server

import "net/http"

type Server struct {
port string
router *Router
}

func CreateServer(port string) *Server {
return &Server{
port: port,
router: NewRouter(),
}
}

func (s *Server) Get(path string, handler http.HandlerFunc) {
s.handle("GET", path, handler)
}
func (s *Server) Post(path string, handler http.HandlerFunc) {
s.handle("POST", path, handler)
}
func (s *Server) Put(path string, handler http.HandlerFunc) {
s.handle("PUT", path, handler)
}
func (s *Server) Delete(path string, handler http.HandlerFunc) {
s.handle("DELETE", path, handler)
}

func (s *Server) handle(method string, path string, handler http.HandlerFunc) {
_, exists := s.router.rules[path]

if !exists {
s.router.rules[path] = make(map[string]http.HandlerFunc)
}

s.router.rules[path][method] = handler
}

func (s *Server) AddMiddleWare(f http.HandlerFunc, middleWares ...MiddleWare) http.HandlerFunc {
for _, m := range middleWares {
f = m(f)
}
return f
}

func (s *Server) Listen() error {
http.Handle("/", s.router)
err := http.ListenAndServe(s.port, nil)

if err != nil {
return err
}

return nil
}
7 changes: 7 additions & 0 deletions types_server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package web_server

import (
"net/http"
)

type MiddleWare func(http.HandlerFunc) http.HandlerFunc

0 comments on commit 1aafbd5

Please sign in to comment.