Created
April 1, 2015 02:59
-
-
Save suzuken/65a3ce16c02afc0bda87 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"fmt" | |
"github.com/hydrogen18/stoppableListener" | |
"github.com/julienschmidt/httprouter" | |
"log" | |
"net" | |
"net/http" | |
"sync" | |
"time" | |
) | |
type HostSwitch map[string]http.Handler | |
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
if handler := hs[r.Host]; handler != nil { | |
handler.ServeHTTP(w, r) | |
} else { | |
http.Error(w, "Forbidden", 403) | |
} | |
} | |
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { | |
fmt.Fprint(w, "Welcome!\n") | |
} | |
func main() { | |
router := httprouter.New() | |
router.GET("/", Index) | |
log.Print("create router") | |
hs := make(HostSwitch) | |
for i := 0; i < 10; i++ { | |
log.Printf("create host: %s", fmt.Sprintf("hoge%d.dev:5555", i)) | |
hs[fmt.Sprintf("hoge%d.dev:5555", i)] = router | |
} | |
l, err := net.Listen("tcp", ":5555") | |
if err != nil { | |
panic(err) | |
} | |
sl, err := stoppableListener.New(l) | |
if err != nil { | |
panic(err) | |
} | |
s := http.Server{Addr: ":5555", Handler: hs} | |
var wg sync.WaitGroup | |
go func() { | |
wg.Add(1) | |
defer wg.Done() | |
s.Serve(sl) | |
}() | |
time.Sleep(10 * time.Second) | |
fmt.Println("stopping listener..") | |
sl.Stop() | |
fmt.Println("waiting on server") | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment