funcmain() { // set 2 route- "/" and "/hello" http.HandleFunc("/", indexHandler) http.HandleFunc("/hello", helloHandler) // launch web service // :9999 : address AT 9999 port // nil : solve instance by Standard library log.Fatal(http.ListenAndServe(":9999", nil)) }
// Engine is the uni handler for all requests type Engine struct{}
// ResponseWriter: create the response of this HTTP request. // http.Request: all the information of this HTTP request. For example, the address, Header and Body
func(engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request){ switch req.URL.Path{ case"/": fmt.Fprintf(w, "URL.Path = %q\n", req.URL.Path) case"/hello": for k, v := range req.Header{ fmt.Fprintf(w, "Header[%q] = %q\n", k, v) } default: fmt.Fprintf(w, "404 NOT FOUND: %s\n", req.URL) } }
funcmain() {
// Transfer all the request to our own solution. engine := new(Engine) // launch web service // :9999 : address AT 9999 port // log.Fatal(http.ListenAndServe(":9999", engine)) }
// HandlerFunc defines the request handler used by Gogee type HandlerFunc func(http.ResponseWriter, *http.Request)
// Engine implement the interface of ServeHTTP type Engine struct{ router map[string]HandlerFunc }
// New is the constructor of Gogee.Engine funcNew() *Engine{ return &Engine{router: make(map[string]HandlerFunc)} }
// addRoute is the way to add something to route func(engine *Engine) addRoute(method string, pattern string, handler HandlerFunc){ key := method + "-" + pattern engine.router[key] = handler }
// GET defines the method to add GET request func(engine *Engine) GET(pattern string, handler HandlerFunc){ engine.addRoute("GET", pattern, handler) }
//POST defines the method to POST request func(engine *Engine) POST(pattern string, handler HandlerFunc){ engine.addRoute("POST", pattern, handler) }
//Run definesd the method to start a http server func(engine *Engine) Run(addr string) (err error){ return http.ListenAndServe(addr, engine) }
// To use the ListenAndServe, we need to set a ServeHTTP struct func(engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { key := req.Method + "-" + req.URL.Path if handler, ok := engine.router[key]; ok { handler(w, req) } else { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "404 MOT FOUND: %s\n", req.URL) } }