-
Notifications
You must be signed in to change notification settings - Fork 8
/
simpleserver.go
58 lines (52 loc) · 1.13 KB
/
simpleserver.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
52
53
54
55
56
57
58
package httpsimple
import (
"fmt"
"log"
"net/http"
"strconv"
"strings"
"github.com/apex/gateway"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
)
const (
EngineAwsLambda = "awslambda"
EngineNetHttp = "nethttp"
EngineFastHttp = "fasthttp"
)
type SimpleServer interface {
PortInt() int
HttpEngine() string
Router() http.Handler
RouterFast() *fasthttprouter.Router
}
func Serve(svc SimpleServer) {
engine := strings.ToLower(strings.TrimSpace(svc.HttpEngine()))
if len(engine) == 0 {
engine = EngineNetHttp
}
switch engine {
case EngineNetHttp:
log.Fatal(
http.ListenAndServe(
portAddress(svc.PortInt()),
svc.Router()))
case EngineAwsLambda:
log.Fatal(
gateway.ListenAndServe(
portAddress(svc.PortInt()),
svc.Router()))
case EngineFastHttp:
router := svc.RouterFast()
if router == nil {
log.Fatal("E_NO_FASTROUTER_FOR_ENGINE_FASTHTTP")
}
log.Fatal(
fasthttp.ListenAndServe(
portAddress(svc.PortInt()),
router.Handler))
default:
log.Fatal(fmt.Sprintf("E_ENGINE_NOT_FOUND [%s]", engine))
}
}
func portAddress(port int) string { return ":" + strconv.Itoa(port) }