Skip to content
This repository has been archived by the owner on Oct 2, 2020. It is now read-only.

Commit

Permalink
Add convenience for serving protocols
Browse files Browse the repository at this point in the history
  • Loading branch information
Joshua T Corbin committed May 19, 2016
1 parent 565bcb8 commit 6e4ec07
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 11 deletions.
16 changes: 5 additions & 11 deletions example_server/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package main

import (
"log"
"net/http"

"code.uber.internal/personal/joshua/gwr"
"code.uber.internal/personal/joshua/gwr/protocol"
gwrProto "code.uber.internal/personal/joshua/gwr/protocol"
)

func main() {
Expand All @@ -14,13 +13,8 @@ func main() {

gwr.AddMarshaledDataSource(reqLog)
gwr.AddMarshaledDataSource(resLog)
go func() {
log.Fatal(http.ListenAndServe(":4040", reqLog))
}()

go func() {
log.Fatal(protocol.NewRedisServer(&gwr.DefaultDataSources).ListenAndServe(":6379"))
}()

select {}
gwrProto.ListenAndServe(map[string]string{
"http": ":4040",
"resp": ":4041",
})
}
55 changes: 55 additions & 0 deletions protocol/serve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package protocol

import (
"log"
"net/http"

"code.uber.internal/personal/joshua/gwr"
)

// TODO: write a http+rest server that heuristically detects the protocol

// ListenAndServeResp starts a redis protocol gwr server.
func ListenAndServeResp(hostPort string) error {
return NewRedisServer(&gwr.DefaultDataSources).ListenAndServe(hostPort)
}

// ListenAndServeHTTP starts an http protocol gwr server.
func ListenAndServeHTTP(hostPort string) error {
return http.ListenAndServe(hostPort, NewHTTPRest(&gwr.DefaultDataSources, ""))
}

// ProtoListenAndServe maps protocol names to listenAndServe func(hostPort
// string) error.
var ProtoListenAndServe = map[string]func(string) error{
"resp": ListenAndServeResp,
"http": ListenAndServeHTTP,
}

// TODO: provide a default protoHostPorts based on environment variables

// ListenAndServe starts one or more servers given a map of protocol name to
// hostPort string. Any errors are passed to log.Fatal.
func ListenAndServe(protoHostPorts map[string]string) {
for proto := range protoHostPorts {
if ProtoListenAndServe[proto] == nil {
log.Fatalf("invalid protocol %v", proto)
}
}

if len(protoHostPorts) == 1 {
for proto, hostPort := range protoHostPorts {
listenAndServe := ProtoListenAndServe[proto]
log.Fatal(listenAndServe(hostPort))
return
}
}

for proto, hostPort := range protoHostPorts {
go func(proto, hostPort string) {
listenAndServe := ProtoListenAndServe[proto]
log.Fatal(listenAndServe(hostPort))
}(proto, hostPort)
}
select {}
}

0 comments on commit 6e4ec07

Please sign in to comment.