main.go 5.7 KB

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