2023-10-13 09:43:27 +00:00
|
|
|
package rep
|
|
|
|
|
|
|
|
import (
|
2023-10-16 08:50:19 +00:00
|
|
|
"encoding/json"
|
2023-10-13 09:43:27 +00:00
|
|
|
"net/http"
|
2023-10-16 08:50:19 +00:00
|
|
|
"path"
|
2023-10-13 09:43:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2023-10-16 08:50:19 +00:00
|
|
|
pathGetInfo = "get-info"
|
|
|
|
pathSendState = "send-state"
|
|
|
|
pathStreamWAL = "stream-wal"
|
2023-10-13 09:43:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func (rep *Replicator) Handle(w http.ResponseWriter, r *http.Request) {
|
2023-10-16 08:50:19 +00:00
|
|
|
// We'll handle two types of requests: HTTP GET requests for JSON, or
|
|
|
|
// streaming requets for state or wall.
|
|
|
|
|
|
|
|
base := path.Base(r.URL.Path)
|
|
|
|
switch base {
|
|
|
|
case pathGetInfo:
|
|
|
|
rep.handleGetInfo(w, r)
|
|
|
|
case pathSendState:
|
|
|
|
rep.handleSendState(w, r)
|
|
|
|
case pathStreamWAL:
|
|
|
|
rep.handleStreamWAL(w, r)
|
|
|
|
default:
|
|
|
|
http.Error(w, "not found", http.StatusNotFound)
|
2023-10-13 09:43:27 +00:00
|
|
|
}
|
2023-10-16 08:50:19 +00:00
|
|
|
}
|
2023-10-13 09:43:27 +00:00
|
|
|
|
2023-10-16 08:50:19 +00:00
|
|
|
func (rep *Replicator) handleGetInfo(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if !rep.checkBasicAuth(w, r) {
|
2023-10-13 09:43:27 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-10-16 08:50:19 +00:00
|
|
|
w.Header().Set("Content-Type", "application/json")
|
2023-10-13 09:43:27 +00:00
|
|
|
|
2023-10-16 08:50:19 +00:00
|
|
|
if err := json.NewEncoder(w).Encode(rep.Info()); err != nil {
|
|
|
|
rep.handlerLogf("Failed to send info: %s", err)
|
2023-10-13 09:43:27 +00:00
|
|
|
}
|
2023-10-16 08:50:19 +00:00
|
|
|
}
|
2023-10-13 09:43:27 +00:00
|
|
|
|
2023-10-16 08:50:19 +00:00
|
|
|
func (rep *Replicator) handleSendState(w http.ResponseWriter, r *http.Request) {
|
|
|
|
conn := rep.acceptConnect(w, r)
|
|
|
|
if conn == nil {
|
2023-10-13 09:43:27 +00:00
|
|
|
return
|
|
|
|
}
|
2023-10-16 08:50:19 +00:00
|
|
|
defer conn.Close()
|
2023-10-13 09:43:27 +00:00
|
|
|
|
2023-10-16 08:50:19 +00:00
|
|
|
if err := rep.sendState(conn); err != nil {
|
|
|
|
if !rep.stopped() {
|
|
|
|
rep.handlerLogf("Failed to send state: %s", err)
|
2023-10-13 09:43:27 +00:00
|
|
|
}
|
2023-10-16 08:50:19 +00:00
|
|
|
}
|
|
|
|
}
|
2023-10-13 09:43:27 +00:00
|
|
|
|
2023-10-16 08:50:19 +00:00
|
|
|
func (rep *Replicator) handleStreamWAL(w http.ResponseWriter, r *http.Request) {
|
|
|
|
conn := rep.acceptConnect(w, r)
|
|
|
|
if conn == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
2023-10-13 09:43:27 +00:00
|
|
|
|
2023-10-16 08:50:19 +00:00
|
|
|
err := rep.wal.Send(conn, rep.conf.NetTimeout)
|
|
|
|
if !rep.stopped() {
|
|
|
|
rep.handlerLogf("Failed when streaming WAL: %s", err)
|
2023-10-13 09:43:27 +00:00
|
|
|
}
|
|
|
|
}
|