<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                ## 將GRPC導出為JSON API 在第六章的“理解GRPC的使用”一節中,我們實現了一個基礎的GRPC服務器和客戶端。本節將通過將常見的RPC函數放在一個包中并將它們包裝在GRPC服務器和標準Web處理程序中來進行擴展。當你的API希望支持兩種類型的客戶端,但不希望復制代碼以實現常見功能時,這非常有用。 ### 實踐 1. 安裝GRPC: https://github.com/grpc/grpc/blob/master/INSTALL.md. ``` go get github.com/golang/protobuf/proto go get github.com/golang/protobuf/protoc-gen-go ``` 2. 建立greeter.proto: ``` syntax = "proto3"; package keyvalue; service KeyValue{ rpc Set(SetKeyValueRequest) returns (KeyValueResponse){} rpc Get(GetKeyValueRequest) returns (KeyValueResponse){} } message SetKeyValueRequest { string key = 1; string value = 2; } message GetKeyValueRequest{ string key = 1; } message KeyValueResponse{ string success = 1; string value = 2; } ``` 運行 ``` protoc --go_out=plugins=grpc:. greeter.proto ``` 3. 建立 keyvalue.go: ``` package internal import ( "golang.org/x/net/context" "sync" "github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue" "google.golang.org/grpc" "google.golang.org/grpc/codes" ) type KeyValue struct { mutex sync.RWMutex m map[string]string } // NewKeyValue 初始化了KeyValue中的map func NewKeyValue() *KeyValue { return &KeyValue{ m: make(map[string]string), } } // Set 為鍵設置一個值,然后返回該值 func (k *KeyValue) Set(ctx context.Context, r *keyvalue.SetKeyValueRequest) (*keyvalue.KeyValueResponse, error) { k.mutex.Lock() k.m[r.GetKey()] = r.GetValue() k.mutex.Unlock() return &keyvalue.KeyValueResponse{Value: r.GetValue()}, nil } // Get 得到一個給定鍵的值,或者如果它不存在報告查找失敗 func (k *KeyValue) Get(ctx context.Context, r *keyvalue.GetKeyValueRequest) (*keyvalue.KeyValueResponse, error) { k.mutex.RLock() defer k.mutex.RUnlock() val, ok := k.m[r.GetKey()] if !ok { return nil, grpc.Errorf(codes.NotFound, "key not set") } return &keyvalue.KeyValueResponse{Value: val}, nil } ``` 4. 建立 grpc/main.go: ``` package main import ( "fmt" "net" "github.com/agtorre/go-cookbook/chapter7/grpcjson/internal" "github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue" "google.golang.org/grpc" ) func main() { grpcServer := grpc.NewServer() keyvalue.RegisterKeyValueServer(grpcServer, internal.NewKeyValue()) lis, err := net.Listen("tcp", ":4444") if err != nil { panic(err) } fmt.Println("Listening on port :4444") grpcServer.Serve(lis) } ``` 5. 建立 set.go: ``` package main import ( "encoding/json" "net/http" "github.com/agtorre/go-cookbook/chapter7/grpcjson/internal" "github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue" "github.com/apex/log" ) // Controller 保存一個內部的KeyValueObject type Controller struct { *internal.KeyValue } // SetHandler 封裝了RPC的Set調用 func (c *Controller) SetHandler(w http.ResponseWriter, r *http.Request) { var kv keyvalue.SetKeyValueRequest decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&kv); err != nil { log.Errorf("failed to decode: %s", err.Error()) w.WriteHeader(http.StatusBadRequest) return } gresp, err := c.Set(r.Context(), &kv) if err != nil { log.Errorf("failed to set: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } resp, err := json.Marshal(gresp) if err != nil { log.Errorf("failed to marshal: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.Write(resp) } ``` 6. 建立 get.go: ``` package main import ( "encoding/json" "net/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue" "github.com/apex/log" ) // GetHandler 封裝了RPC的Get調用 func (c *Controller) GetHandler(w http.ResponseWriter, r *http.Request) { key := r.URL.Query().Get("key") kv := keyvalue.GetKeyValueRequest{Key: key} gresp, err := c.Get(r.Context(), &kv) if err != nil { if grpc.Code(err) == codes.NotFound { w.WriteHeader(http.StatusNotFound) return } log.Errorf("failed to get: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) resp, err := json.Marshal(gresp) if err != nil { log.Errorf("failed to marshal: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.Write(resp) } ``` 7. 建立 main.go: ``` package main import ( "fmt" "net/http" "github.com/agtorre/go-cookbook/chapter7/grpcjson/internal" ) func main() { c := Controller{KeyValue: internal.NewKeyValue()} http.HandleFunc("/set", c.SetHandler) http.HandleFunc("/get", c.GetHandler) fmt.Println("Listening on port :3333") err := http.ListenAndServe(":3333", nil) panic(err) } ``` 8. 運行: ``` $ go run http/*.go Listening on port :3333 $curl "http://localhost:3333/set" -d '{"key":"test", "value":"123"}' -v {"value":"123"} $curl "http://localhost:3333/get?key=badtest" -v 'name=Reader;greeting=Goodbye' <should return a 404> $curl "http://localhost:3333/get?key=test" -v 'name=Reader;greeting=Goodbye' {"value":"123"} ``` ### 說明 雖然示例中省略了客戶端,但你可以復制第6章GRPC章節中的步驟,這樣應該看到與示例中相同的結果。http和grpc使用了相同的內部包。我們必須返回適當的GRPC錯誤代碼,并將這些錯誤代碼映射到HTTP響應。在這種情況下,我們使用codes.NotFound,它映射到http.StatusNotFound。如果必須處理多種錯誤,則switch語句可能比if ... else語句更有意義。 你可能注意到GRPC簽名通常非常一致。他們接受請求并返回可選響應和錯誤。如果你的GRPC調用重復性很強并且看起來很適合代碼生成,那么可以創建一個通用的處理程序來填充它,像 github.com/goadesign/goa 這樣的庫就是這么干的。 * * * * 學識淺薄,錯誤在所難免。歡迎在群中就本書提出修改意見,以饗后來者,長風拜謝。 Golang中國(211938256) beego實戰(258969317) Go實踐(386056972)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看