gorpc 是一款非常簡單、易用、高性能的微服務框架,使用 gorpc 可以 分分鐘開發出 http 服務。gorpc 源碼非常簡單,可以參考:gorpc
一、server 創建
1、第一步,創建 gorpc server ,vim server.go ,如下:
func main() {
opts := []gorpc.ServerOption{
gorpc.WithAddress("127.0.0.1:8000"),
gorpc.WithProtocol("http"),
gorpc.WithNetwork("tcp"),
gorpc.WithTimeout(time.Millisecond * 2000),
}
s := gorpc.NewServer(opts ...)
s.ServeHttp()
}
2、第二步,實現一個 http handler,如下:
func sayHello(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form)
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
w.Write([]byte("world"))
}
3、第三部,路由註冊
func init() {
ghttp.HandleFunc("GET","/hello", sayHello)
}
完整代碼如下:
package main
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/lubanproj/gorpc"
ghttp "github.com/lubanproj/gorpc/http"
)
func init() {
ghttp.HandleFunc("GET","/hello", sayHello)
}
func main() {
opts := []gorpc.ServerOption{
gorpc.WithAddress("127.0.0.1:8000"),
gorpc.WithProtocol("http"),
gorpc.WithNetwork("tcp"),
gorpc.WithTimeout(time.Millisecond * 2000),
}
s := gorpc.NewServer(opts ...)
s.ServeHttp()
}
func sayHello(w http.ResponseWriter, r *http.Request) {
fmt.Println("path", r.URL.Path)
w.Write([]byte("world"))
}
二、運行 server
運行 go run server.go ,服務在 127.0.0.1:8000 地址監聽。在瀏覽器訪問 127.0.0.1:8000 或者 curl 127.0.0.1:8000 。可以看到頁面會輸出 world !
詳細的 demo 可以參考:http demo