http_server.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package tests
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "regexp"
  7. "strings"
  8. "github.com/gorilla/websocket"
  9. )
  10. var upgrader = websocket.Upgrader{}
  11. func StartHttpServer() {
  12. http.HandleFunc("/", handleHttp)
  13. http.HandleFunc("/ws", handleWebSocket)
  14. http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", TEST_HTTP_PORT), nil)
  15. }
  16. func handleWebSocket(w http.ResponseWriter, r *http.Request) {
  17. c, err := upgrader.Upgrade(w, r, nil)
  18. if err != nil {
  19. log.Print("upgrade:", err)
  20. return
  21. }
  22. defer c.Close()
  23. for {
  24. mt, message, err := c.ReadMessage()
  25. if err != nil {
  26. break
  27. }
  28. err = c.WriteMessage(mt, message)
  29. if err != nil {
  30. log.Println("write:", err)
  31. break
  32. }
  33. }
  34. }
  35. func handleHttp(w http.ResponseWriter, r *http.Request) {
  36. match, err := regexp.Match(`.*\.sub\.com`, []byte(r.Host))
  37. if err != nil {
  38. w.WriteHeader(500)
  39. return
  40. }
  41. if match {
  42. w.WriteHeader(200)
  43. w.Write([]byte(r.Host))
  44. return
  45. }
  46. if strings.Contains(r.Host, "127.0.0.1") || strings.Contains(r.Host, "test2.frp.com") ||
  47. strings.Contains(r.Host, "test5.frp.com") {
  48. w.WriteHeader(200)
  49. w.Write([]byte(TEST_HTTP_NORMAL_STR))
  50. } else if strings.Contains(r.Host, "test3.frp.com") {
  51. w.WriteHeader(200)
  52. if strings.Contains(r.URL.Path, "foo") {
  53. w.Write([]byte(TEST_HTTP_FOO_STR))
  54. } else if strings.Contains(r.URL.Path, "bar") {
  55. w.Write([]byte(TEST_HTTP_BAR_STR))
  56. } else {
  57. w.Write([]byte(TEST_HTTP_NORMAL_STR))
  58. }
  59. } else {
  60. w.WriteHeader(404)
  61. }
  62. return
  63. }