Skip to content

Instantly share code, notes, and snippets.

@fatih

fatih/changes.diff

Last active Oct 24, 2016
Embed
What would you like to do?
Router example
--- other.go 2016-10-16 16:23:33.000000000 +0300
+++ demo.go 2016-10-16 16:24:27.000000000 +0300
@@ -9,12 +9,12 @@
)
var Session *http.Server
-var r Router
+var r *Router
func Run(port string) {
Session = &http.Server{
Addr: port,
- Handler: &r,
+ Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
@@ -54,7 +54,7 @@
}
func main() {
- r := newRouter()
+ r = newRouter()
r.Add("/hello", hello)
Run(":8080")
}
package main
import (
"fmt"
"log"
"net/http"
"strings"
"time"
)
var Session *http.Server
var r *Router
func Run(port string) {
Session = &http.Server{
Addr: port,
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(Session.ListenAndServe())
}
type Handle func(http.ResponseWriter, *http.Request)
type Router struct {
mux map[string]Handle
}
func newRouter() *Router {
return &Router{
mux: make(map[string]Handle),
}
}
func (r *Router) Add(path string, handle Handle) {
r.mux[path] = handle
}
func GetHeader(url string) string {
sl := strings.Split(url, "/")
return fmt.Sprintf("/%s", sl[1])
}
func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
head := GetHeader(r.URL.Path)
h, ok := rt.mux[head]
if ok {
h(w, r)
return
}
http.NotFound(w, r)
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", "hello world")
}
func main() {
r = newRouter()
r.Add("/hello", hello)
Run(":8080")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment