main.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. Authenticate if token present (Except for LOGIN command itself)
  106. if req.Command != "LOGIN" && token != "" {
  107. fmt.Fprintf(c, "AUTH %s\n\n", token)
  108. authResp, err := reader.ReadString('\n')
  109. if err != nil {
  110. return err
  111. }
  112. if !strings.HasPrefix(authResp, "OK") {
  113. // Special handling: if auth fails, we return a specific error that is NOT a network error
  114. // but we still want to return it to the client.
  115. // However, if we are reusing a connection, maybe the previous session is interfering?
  116. // AUTH command should override previous session.
  117. // If it fails here, it means the token is invalid.
  118. return fmt.Errorf("Session Expired")
  119. }
  120. }
  121. // 5. Construct TCP Command
  122. cmdStr := req.Command
  123. if len(req.Args) > 0 {
  124. cmdStr += " " + strings.Join(req.Args, " ")
  125. }
  126. // Send command followed by empty line to terminate headers (protocol requirement)
  127. fmt.Fprintf(c, "%s\n\n", cmdStr)
  128. // 6. Read TCP Response
  129. respStr, err := reader.ReadString('\n')
  130. if err != nil {
  131. return err
  132. }
  133. respStr = strings.TrimSpace(respStr)
  134. // 7. Parse Response
  135. if strings.HasPrefix(respStr, "OK") {
  136. payload := strings.TrimPrefix(respStr, "OK ")
  137. // If payload looks like JSON, try to parse it
  138. var jsonData any
  139. if strings.HasPrefix(payload, "[") || strings.HasPrefix(payload, "{") {
  140. if err := json.Unmarshal([]byte(payload), &jsonData); err == nil {
  141. jsonResponse(w, APIResponse{Status: "ok", Data: jsonData})
  142. return nil
  143. }
  144. }
  145. jsonResponse(w, APIResponse{Status: "ok", Data: payload})
  146. } else if strings.HasPrefix(respStr, "ERR") {
  147. errMsg := strings.TrimPrefix(respStr, "ERR ")
  148. jsonResponse(w, APIResponse{Status: "error", Error: errMsg})
  149. } else {
  150. jsonResponse(w, APIResponse{Status: "error", Error: "Unknown response: " + respStr})
  151. }
  152. return nil
  153. }
  154. // Try with pooled connection
  155. err = execute(conn)
  156. if err != nil {
  157. // If error is "Session Expired", it's a logic error, not network. Don't retry.
  158. if err.Error() == "Session Expired" {
  159. pool.Put(conn) // Connection is fine, token is bad
  160. jsonResponse(w, APIResponse{Status: "error", Error: "Session Expired"})
  161. return
  162. }
  163. // If network error, discard and retry once
  164. pool.Discard(conn)
  165. // Retry with new connection
  166. conn, err = net.Dial("tcp", TargetTCPAddr)
  167. if err != nil {
  168. jsonResponse(w, APIResponse{Status: "error", Error: "Connection failed: 无法连接到后端节点 (127.0.0.1:9011)。请确保 Raft 服务已启动。 (" + err.Error() + ")"})
  169. return
  170. }
  171. err = execute(conn)
  172. if err != nil {
  173. pool.Discard(conn)
  174. // Return error to client
  175. errMsg := err.Error()
  176. if errMsg != "Session Expired" {
  177. errMsg = "Connection failed: 无法连接到后端节点。请确保 Raft 服务已启动。 (" + errMsg + ")"
  178. }
  179. jsonResponse(w, APIResponse{Status: "error", Error: errMsg})
  180. return
  181. }
  182. // Success on retry
  183. pool.Put(conn)
  184. } else {
  185. // Success on first try
  186. pool.Put(conn)
  187. }
  188. }
  189. func jsonResponse(w http.ResponseWriter, resp APIResponse) {
  190. w.Header().Set("Content-Type", "application/json")
  191. json.NewEncoder(w).Encode(resp)
  192. }