Created
May 12, 2015 03:10
-
-
Save blockloop/570964662aebc1a82641 to your computer and use it in GitHub Desktop.
Listening to RPC and HTTP simultaneously with golang
This file contains hidden or 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 ( | |
"errors" | |
"io" | |
"log" | |
"net" | |
"net/http" | |
"net/rpc" | |
) | |
const ( | |
RPC_PORT = "9876" | |
HTTP_PORT = "8008" | |
) | |
func main() { | |
err1 := make(chan error) | |
err2 := make(chan error) | |
go listenRpc(err1) | |
go listenHttp(err2) | |
select { | |
case er := <-err1: | |
log.Fatalf("Exited rpc with error: %s", er.Error()) | |
case er := <-err1: | |
log.Fatalf("Exited http with error: %s", er.Error()) | |
} | |
} | |
func listenRpc(err_chan chan error) { | |
rpc.Register(NewRPC()) | |
listener, err := net.Listen("tcp", ":"+RPC_PORT) | |
if err != nil { | |
err_chan <- err | |
return | |
} | |
log.Printf("Listening for RPC requests on port %s...", RPC_PORT) | |
rpc.Accept(listener) | |
err_chan <- errors.New("stopped listening for RPC requests") | |
} | |
func listenHttp(err_chan chan error) { | |
http.HandleFunc("/", hello) | |
log.Printf("Listening for HTTP requests on port %s...", HTTP_PORT) | |
err_chan <- http.ListenAndServe(":8008", nil) | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
io.WriteString(w, "Hello world!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment