Created
March 30, 2017 12:35
-
-
Save monirz/8a50aebc3095e2bb373f42649234c581 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "errors" | |
| "log" | |
| "net/http" | |
| ) | |
| //A simple and basic router | |
| type Router struct { | |
| routes []Route | |
| } | |
| //Route holds the method, path and HandlerFunc | |
| type Route struct { | |
| Method string | |
| Path string | |
| Handle http.HandlerFunc | |
| } | |
| func main() { | |
| r := New() | |
| r.GET("/", hello) | |
| r.POST("/users", users) | |
| r.GET("/hello", hello) | |
| http.ListenAndServe(":8080", r) | |
| } | |
| //New instanciate a new Router | |
| func New() *Router { | |
| var router Router | |
| return &router | |
| } | |
| //POST accepts and append handler, path, method to Router rouet slice | |
| func (rt *Router) POST(path string, handle http.HandlerFunc) { | |
| route := Route{} | |
| route.Method = "POST" | |
| route.Path = path | |
| route.Handle = handle | |
| rt.routes = append(rt.routes, route) | |
| } | |
| //GET for a get request | |
| func (rt *Router) GET(path string, handle http.HandlerFunc) { | |
| route := Route{} | |
| route.Method = "GET" | |
| route.Path = path | |
| route.Handle = handle | |
| rt.routes = append(rt.routes, route) | |
| } | |
| //ServeHTTP runs the server | |
| func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| path := r.URL.Path | |
| route, err := rt.checkRoute(r.Method, path) | |
| log.Printf("path %v", r.URL.Path) | |
| if err != nil { | |
| log.Printf("%v", err) | |
| http.NotFound(w, r) | |
| return | |
| } | |
| route.Handle(w, r) | |
| return | |
| } | |
| func (rt *Router) checkRoute(method string, path string) (*Route, error) { | |
| for _, route := range rt.routes { | |
| // log.Printf("%v", k) | |
| if route.Method == method && route.Path == path { | |
| return &route, nil | |
| } | |
| } | |
| return &Route{}, errors.New("Not found") | |
| } | |
| func users(w http.ResponseWriter, r *http.Request) { | |
| users := `{"username": "John Doe"}` | |
| w.Header().Set("Content-Type", "application/json") | |
| w.WriteHeader(200) | |
| w.Write([]byte(users)) | |
| } | |
| func hello(w http.ResponseWriter, r *http.Request) { | |
| users := `{"welcome": "home"}` | |
| w.Header().Set("Content-Type", "application/json") | |
| w.WriteHeader(200) | |
| w.Write([]byte(users)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment