feat: implement http support

Signed-off-by: Kairee Wu <kaireewu@gmail.com>
This commit is contained in:
2022-04-23 17:34:50 +08:00
parent 74ef998a9b
commit 4477a63c49
6 changed files with 150 additions and 4 deletions

View File

@ -4,7 +4,9 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"strings"
"sync"
"time"
@ -110,3 +112,35 @@ func Register(rcvr interface{}) error {
}
func Accept(lis net.Listener) { DefaultServer.Accept(lis) }
const (
connected = "200 Connected to kRPC"
defaultRPCPath = "/_krpc_"
defaultDebugPath = "/debug/krpc"
)
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodConnect {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = fmt.Fprintln(w, "405 method not allowed")
return
}
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Printf("rpc hijacking %s: %s", r.RemoteAddr, err.Error())
return
}
_, _ = fmt.Fprintf(conn, "HTTP/1.0 %s\n\n", connected)
s.ServeConn(conn)
}
func (s *Server) HandleHTTP() {
http.Handle(defaultRPCPath, s)
http.Handle(defaultDebugPath, debugHTTP{s})
log.Println("rpc: server debug path:", defaultDebugPath)
}
func HandleHTTP() {
DefaultServer.HandleHTTP()
}