Adding custom routes to the mux

The gRPC-Gateway allows you to add custom routes to the serve mux, for example, if you want to support a use case that isn’t supported by the gRPC-Gateway, like file uploads.

Example

  1. package main
  2. import (
  3. "context"
  4. "net/http"
  5. pb "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/helloworld"
  6. "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
  7. )
  8. func main() {
  9. ctx := context.TODO()
  10. mux := runtime.NewServeMux()
  11. // Register generated routes to mux
  12. err := pb.RegisterGreeterHandlerServer(ctx, mux, &GreeterServer{})
  13. if err != nil {
  14. panic(err)
  15. }
  16. // Register custom route for GET /hello/{name}
  17. err = mux.HandlePath("GET", "/hello/{name}", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
  18. w.Write([]byte("hello " + pathParams["name"]))
  19. })
  20. if err != nil {
  21. panic(err)
  22. }
  23. http.ListenAndServe(":8080", mux)
  24. }
  25. // GreeterServer is the server API for Greeter service.
  26. type GreeterServer struct {
  27. }
  28. // SayHello implement to say hello
  29. func (h *GreeterServer) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) {
  30. return &pb.HelloReply{
  31. Message: "hello " + req.Name,
  32. }, nil
  33. }