1 Star 1 Fork 0

lople/geerpc

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ServerHTTP.go 1.65 KB
一键复制 编辑 原始数据 按行查看 历史
lople 提交于 2021-05-22 14:09 +08:00 . 20210522
package server
import (
"io"
"log"
"net/http"
"gitee.com/lople/geerpc/codec"
)
/*
客户端和服务端封装HTTP层
服务端支持 HTTP 协议:
1.客户端向 RPC 服务器发送 CONNECT 请求
CONNECT 10.0.0.1:9999/_geerpc_ HTTP/1.0
2.RPC 服务器返回 HTTP 200 状态码表示连接建立。
HTTP/1.0 200 Connected to Gee RPC
3.客户端使用创建好的连接发送 RPC 报文,先发送 Option,再发送 N 个请求报文,服务端处理 RPC 请求并响应。
*/
const (
connected = "200 connected to Gee RPC"
defalutRPCPath = "/geerpc"
defalutDebugPath = "/debug/geerpc"
)
// ServeHTTP implements an http.Handler that answers RPC requests.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "CONNECT" {
w.Header().Set("Content-Type", "text/plain;charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
io.WriteString(w, "405 must CONNECT\n")
return
}
//type assert,Hijack return origin tcp conn
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Print("rpc hijacking", req.RemoteAddr, ":", err.Error())
return
}
//return connected status ok
io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
s.ServerConn(conn)
}
// HandleHTTP registers an HTTP handler for RPC messages on rpcPath.
// It is still necessary to invoke http.Serve(), typically in a go statement.
func (s *Server) HandleHTTP() {
codec.Init()
http.Handle(defalutRPCPath, s)
http.Handle(defalutDebugPath, debugHTTP{s})
log.Println("rpc server debug path:", defalutDebugPath)
}
// HandleHTTP is a convenient approach for default server to register HTTP handlers
func HandleHTTP() {
defaultServer.HandleHTTP()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/lople/geerpc.git
git@gitee.com:lople/geerpc.git
lople
geerpc
geerpc
v1.4.0

搜索帮助