main.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package main
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net"
  9. "net/http"
  10. "strings"
  11. "sync"
  12. )
  13. // Configuration
  14. const (
  15. TargetTCPAddr = "127.0.0.1:9011"
  16. WebPort = ":8088"
  17. )
  18. type APIRequest struct {
  19. Command string `json:"command"`
  20. Args []string `json:"args"`
  21. }
  22. type APIResponse struct {
  23. Status string `json:"status"`
  24. Data any `json:"data,omitempty"`
  25. Error string `json:"error,omitempty"`
  26. }
  27. // TCPPool implements a simple connection pool
  28. type TCPPool struct {
  29. mu sync.Mutex
  30. conns []net.Conn
  31. addr string
  32. }
  33. func NewTCPPool(addr string) *TCPPool {
  34. return &TCPPool{
  35. addr: addr,
  36. conns: make([]net.Conn, 0),
  37. }
  38. }
  39. func (p *TCPPool) Get() (net.Conn, error) {
  40. p.mu.Lock()
  41. if len(p.conns) > 0 {
  42. conn := p.conns[len(p.conns)-1]
  43. p.conns = p.conns[:len(p.conns)-1]
  44. p.mu.Unlock()
  45. return conn, nil
  46. }
  47. p.mu.Unlock()
  48. return net.Dial("tcp", p.addr)
  49. }
  50. func (p *TCPPool) Put(conn net.Conn) {
  51. p.mu.Lock()
  52. p.conns = append(p.conns, conn)
  53. p.mu.Unlock()
  54. }
  55. func (p *TCPPool) Discard(conn net.Conn) {
  56. if conn != nil {
  57. conn.Close()
  58. }
  59. }
  60. var pool *TCPPool
  61. func main() {
  62. // Initialize Connection Pool
  63. pool = NewTCPPool(TargetTCPAddr)
  64. // Serve static files (HTML)
  65. http.HandleFunc("/", handleIndex)
  66. // API Endpoint
  67. http.HandleFunc("/api/proxy", handleAPI)
  68. fmt.Printf("Web Admin started at http://localhost%s\n", WebPort)
  69. log.Fatal(http.ListenAndServe(WebPort, nil))
  70. }
  71. func handleIndex(w http.ResponseWriter, r *http.Request) {
  72. if r.URL.Path != "/" {
  73. http.NotFound(w, r)
  74. return
  75. }
  76. // Serve the embedded HTML directly
  77. http.ServeFile(w, r, "example/web_admin/index.html")
  78. }
  79. func handleAPI(w http.ResponseWriter, r *http.Request) {
  80. if r.Method != "POST" {
  81. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  82. return
  83. }
  84. // 1. Parse Request
  85. body, _ := io.ReadAll(r.Body)
  86. var req APIRequest
  87. if err := json.Unmarshal(body, &req); err != nil {
  88. jsonResponse(w, APIResponse{Status: "error", Error: "Invalid JSON"})
  89. return
  90. }
  91. // 2. Get Token from Header
  92. token := r.Header.Get("X-Session-Token")
  93. // 3. Connect to TCP (via Pool)
  94. conn, err := pool.Get()
  95. if err != nil {
  96. jsonResponse(w, APIResponse{Status: "error", Error: "Connection failed: 无法连接到后端节点 (127.0.0.1:9011)。请确保 Raft 服务已启动。 (" + err.Error() + ")"})
  97. return
  98. }
  99. // Helper to execute request with retry logic
  100. execute := func(c net.Conn) error {
  101. // Set deadline to avoid hanging
  102. // c.SetDeadline(time.Now().Add(5 * time.Second))
  103. reader := bufio.NewReader(c)
  104. // 4. Authenticate if token present (Except for LOGIN command itself)
  105. if req.Command != "LOGIN" && token != "" {
  106. fmt.Fprintf(c, "AUTH %s\n", token)
  107. authResp, err := reader.ReadString('\n')
  108. if err != nil {
  109. return err
  110. }
  111. if !strings.HasPrefix(authResp, "OK") {
  112. // Special handling: if auth fails, we return a specific error that is NOT a network error
  113. // but we still want to return it to the client.
  114. // However, if we are reusing a connection, maybe the previous session is interfering?
  115. // AUTH command should override previous session.
  116. // If it fails here, it means the token is invalid.
  117. return fmt.Errorf("Session Expired")
  118. }
  119. }
  120. // 5. Construct TCP Command
  121. cmdStr := req.Command
  122. if len(req.Args) > 0 {
  123. cmdStr += " " + strings.Join(req.Args, " ")
  124. }
  125. fmt.Fprintf(c, "%s\n", cmdStr)
  126. // 6. Read TCP Response
  127. respStr, err := reader.ReadString('\n')
  128. if err != nil {
  129. return err
  130. }
  131. respStr = strings.TrimSpace(respStr)
  132. // 7. Parse Response
  133. if strings.HasPrefix(respStr, "OK") {
  134. payload := strings.TrimPrefix(respStr, "OK ")
  135. // If payload looks like JSON, try to parse it
  136. var jsonData any
  137. if strings.HasPrefix(payload, "[") || strings.HasPrefix(payload, "{") {
  138. if err := json.Unmarshal([]byte(payload), &jsonData); err == nil {
  139. jsonResponse(w, APIResponse{Status: "ok", Data: jsonData})
  140. return nil
  141. }
  142. }
  143. jsonResponse(w, APIResponse{Status: "ok", Data: payload})
  144. } else if strings.HasPrefix(respStr, "ERR") {
  145. errMsg := strings.TrimPrefix(respStr, "ERR ")
  146. jsonResponse(w, APIResponse{Status: "error", Error: errMsg})
  147. } else {
  148. jsonResponse(w, APIResponse{Status: "error", Error: "Unknown response: " + respStr})
  149. }
  150. return nil
  151. }
  152. // Try with pooled connection
  153. err = execute(conn)
  154. if err != nil {
  155. // If error is "Session Expired", it's a logic error, not network. Don't retry.
  156. if err.Error() == "Session Expired" {
  157. pool.Put(conn) // Connection is fine, token is bad
  158. jsonResponse(w, APIResponse{Status: "error", Error: "Session Expired"})
  159. return
  160. }
  161. // If network error, discard and retry once
  162. pool.Discard(conn)
  163. // Retry with new connection
  164. conn, err = net.Dial("tcp", TargetTCPAddr)
  165. if err != nil {
  166. jsonResponse(w, APIResponse{Status: "error", Error: "Connection failed: 无法连接到后端节点 (127.0.0.1:9011)。请确保 Raft 服务已启动。 (" + err.Error() + ")"})
  167. return
  168. }
  169. err = execute(conn)
  170. if err != nil {
  171. pool.Discard(conn)
  172. // Return error to client
  173. errMsg := err.Error()
  174. if errMsg != "Session Expired" {
  175. errMsg = "Connection failed: 无法连接到后端节点。请确保 Raft 服务已启动。 (" + errMsg + ")"
  176. }
  177. jsonResponse(w, APIResponse{Status: "error", Error: errMsg})
  178. return
  179. }
  180. // Success on retry
  181. pool.Put(conn)
  182. } else {
  183. // Success on first try
  184. pool.Put(conn)
  185. }
  186. }
  187. func jsonResponse(w http.ResponseWriter, resp APIResponse) {
  188. w.Header().Set("Content-Type", "application/json")
  189. json.NewEncoder(w).Encode(resp)
  190. }