-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathhosts.go
51 lines (42 loc) · 1.37 KB
/
hosts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"fmt"
"log"
"github.com/fasthttp/router"
"github.com/valyala/fasthttp"
)
// Index is the index handler
func Index(ctx *fasthttp.RequestCtx) {
fmt.Fprint(ctx, "Welcome!\n")
}
// Hello is the Hello handler
func Hello(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "hello, %s!\n", ctx.UserValue("name"))
}
// HostSwitch is the host-handler map
// We need an object that implements the fasthttp.RequestHandler interface.
// We just use a map here, in which we map host names (with port) to fasthttp.RequestHandlers
type HostSwitch map[string]fasthttp.RequestHandler
// CheckHost Implement a CheckHost method on our new type
func (hs HostSwitch) CheckHost(ctx *fasthttp.RequestCtx) {
// Check if a http.Handler is registered for the given host.
// If yes, use it to handle the request.
if handler := hs[string(ctx.Host())]; handler != nil {
handler(ctx)
} else {
// Handle host names for which no handler is registered
ctx.Error("Forbidden", 403) // Or Redirect?
}
}
func main() {
// Initialize a router as usual
r := router.New()
r.GET("/", Index)
r.GET("/hello/{name}", Hello)
// Make a new HostSwitch and insert the router (our http handler)
// for example.com and port 12345
hs := make(HostSwitch)
hs["example.com:12345"] = r.Handler
// Use the HostSwitch to listen and serve on port 12345
log.Fatal(fasthttp.ListenAndServe(":12345", hs.CheckHost))
}