main.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Try net/rpc/jsonrpc between backend and frontend (via GopherJS) through a websocket connection.
  2. //
  3. // based on https://github.com/shurcooL/play/tree/master/42
  4. package main
  5. import (
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/rpc"
  10. "net/rpc/jsonrpc"
  11. "github.com/shurcooL/go/gopherjs_http"
  12. "golang.org/x/net/websocket"
  13. )
  14. type Args struct {
  15. A, B int
  16. }
  17. type Arith struct {
  18. req *http.Request
  19. connClose func() error
  20. callCounter int
  21. }
  22. func (a *Arith) Multiply(args *Args, reply *int) error {
  23. fmt.Println(a.callCounter, "from", a.req.RemoteAddr)
  24. c, err := a.req.Cookie("JSESSIONID")
  25. if err != nil {
  26. return err
  27. }
  28. fmt.Println("cookie:", c)
  29. if a.callCounter > 5 {
  30. return a.connClose()
  31. }
  32. a.callCounter++
  33. *reply = args.A * args.B
  34. fmt.Printf("locally multiplying %v by %v -> %v\n", args.A, args.B, *reply)
  35. return nil
  36. }
  37. func main() {
  38. http.Handle("/rpc-websocket", websocket.Handler(func(conn *websocket.Conn) {
  39. s := rpc.NewServer()
  40. a := &Arith{
  41. req: conn.Request(),
  42. connClose: conn.Close,
  43. }
  44. s.Register(a)
  45. s.ServeCodec(jsonrpc.NewServerCodec(conn))
  46. }))
  47. http.HandleFunc("/index.html", func(w http.ResponseWriter, req *http.Request) {
  48. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  49. io.WriteString(w, `<html>
  50. <head></head>
  51. <body>
  52. <pre id="output"></pre>
  53. <script type="text/javascript" src="/script.js"></script>
  54. </body>
  55. </html>
  56. `)
  57. })
  58. http.Handle("/script.js", gopherjs_http.GoFiles("./script.go"))
  59. err := http.ListenAndServe(":8880", nil)
  60. if err != nil {
  61. panic(err)
  62. }
  63. }