Grebalb
Grebalb

Reputation: 113

Getting http.handleFunc() to work on gRPC server

So I'm trying to get a small gRPC app running in GOlang. The gPRC commands work fine, however, I also want to be able to interact with my database from the URL. Before I added the gRPC server, it worked fine, but after either the gRPC server or the "normal" server got blocked and wouldn't be able to start up. Is there a way to both have a gRPC interface and be able to make call from the URL?

My server code:

func main(){
    createItem("test", "test")
    http.HandleFunc("/get/", get)
    http.HandleFunc("/set/", set)
    listener, err := net.Listen("tcp", ":4000")
    if err != nil{
        log.Fatal("Listener error: ", err)
    }
    s := grpc.NewServer()
    pb.RegisterGetSetServiceServer(s, &server{})
    reflection.Register(s)
    s.Serve(listener)


    log.Printf("serving rpc on port %d", 4000)
    err = http.Serve(listener, nil)
    if err != nil{
        log.Fatal("error serving: ", err)
    }

}

func (s *server) Get(ctx Context, req *pb.GetRequest) (*pb.Response, error) {
    var body string
    log.Printf("Recived: %v", req.GetTitle())
    for _, val := range database{
        if req.GetTitle() == val.Title{
            body = val.Body
            return &pb.Response{Body:body}, nil
        }
    }
    return &pb.Response{Body:"Nothing found"}, nil

}
func get(writer http.ResponseWriter, req *http.Request ){
    var value string


    v := req.FormValue("key")
    for _, val := range database{
        if val.Title == v {
              value = val.Body
        }
    }
    fmt.Fprintln(writer,  value)
}

Upvotes: 1

Views: 953

Answers (1)

Doug Fawley
Doug Fawley

Reputation: 1111

As Mark said in the comment, you can serve gRPC inside a Go HTTP server. The documentation for ServeHTTP has an explanation:

https://godoc.org/google.golang.org/grpc#Server.ServeHTTP

However, this isn't recommended or supported by the gRPC-Go team, as it doesn't allow some gRPC features to work (e.g. Keepalives). Instead we recommend either using different ports, or using something like cmux so that you can run the full gRPC server in addition to a separate HTTP server:

https://github.com/soheilhy/cmux

Upvotes: 1

Related Questions