github.com/vcilabs/webrpc@v0.5.2-0.20201116131534-162e27b1b33b/_examples/hello-webrpc/server/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  	"net/http"
     7  
     8  	"github.com/go-chi/chi"
     9  	"github.com/go-chi/chi/middleware"
    10  	"github.com/go-chi/cors"
    11  )
    12  
    13  func main() {
    14  	err := startServer()
    15  	if err != nil {
    16  		log.Fatal(err)
    17  	}
    18  }
    19  
    20  func startServer() error {
    21  	r := chi.NewRouter()
    22  	r.Use(middleware.RequestID)
    23  	r.Use(middleware.Logger)
    24  	r.Use(middleware.Recoverer)
    25  
    26  	cors := cors.New(cors.Options{
    27  		// AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts
    28  		AllowedOrigins: []string{"*"},
    29  		// AllowOriginFunc:  func(r *http.Request, origin string) bool { return true },
    30  		AllowedMethods:   []string{"POST", "OPTIONS"},
    31  		AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
    32  		ExposedHeaders:   []string{"Link"},
    33  		AllowCredentials: true,
    34  		MaxAge:           300, // Maximum value not ignored by any of major browsers
    35  	})
    36  	r.Use(cors.Handler)
    37  
    38  	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
    39  		w.Write([]byte("."))
    40  	})
    41  
    42  	webrpcHandler := NewExampleServiceServer(&ExampleServiceRPC{})
    43  	r.Handle("/*", webrpcHandler)
    44  
    45  	return http.ListenAndServe(":4242", r)
    46  }
    47  
    48  type ExampleServiceRPC struct {
    49  }
    50  
    51  func (s *ExampleServiceRPC) Ping(ctx context.Context) (bool, error) {
    52  	return true, nil
    53  }
    54  
    55  func (s *ExampleServiceRPC) GetUser(ctx context.Context, userID uint64) (*User, error) {
    56  	if userID == 911 {
    57  		return nil, ErrorNotFound("unknown userID %d", 911)
    58  		// return nil, webrpc.Errorf(webrpc.ErrNotFound, "unknown userID %d", 911)
    59  		// return nil, webrpc.WrapError(webrpc.ErrNotFound, err, "unknown userID %d", 911)
    60  	}
    61  
    62  	return &User{
    63  		ID:       userID,
    64  		Username: "hihi",
    65  	}, nil
    66  }