Last active
April 24, 2019 10:39
-
-
Save syossan27/de979386170dc773ea9e2773a309f116 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
flag.Parse() | |
defer glog.Flush() | |
ctx := context.Background() | |
opts := gateway.Options{ | |
Addr: ":8080", | |
GRPCServer: gateway.Endpoint{ | |
Network: *network, | |
Addr: *endpoint, | |
}, | |
SwaggerDir: *swaggerDir, | |
// ここでレスポンスを返す前にフィルタリングするようにオプションを設定する | |
Mux: runtime.WithForwardResponseOption(filterFunc) | |
} | |
if err := gateway.Run(ctx, opts); err != nil { | |
glog.Fatal(err) | |
} | |
} | |
func filterFunc(ctx context.Context, _w http.ResponseWriter, resp proto.Message) error { | |
// フィルタリングするかどうかを分けるためにMessageNameで分岐させるとベター | |
switch proto.MessageName(resp) { | |
case "Response": | |
r, ok := resp.(*Response) | |
if !ok { | |
return nil | |
} | |
// Any型のPaginationに埋め込まれているValueを | |
// ServerPaginationMessageの形式に変換 | |
paginationResp := &pb.ServerPaginationMessage{} | |
err := proto.Unmarshal(r.Pagination.Value, paginationResp) | |
if err != nil { | |
return err | |
} | |
// Server側のレスポンスを用いて、Gateway側のレスポンスを構築する | |
endpoint := "http://example.com/pagination" | |
paginationMessage := &pb.GatewayPaginationMessage{ | |
Page: paginationResp.Page, | |
Limit: paginationResp.Limit, | |
Size: paginationResp.Size, | |
} | |
if paginationResp.First != nil { | |
paginationMessage.First = fmt.Sprintf("%s?page=%d&limit=%d", endpoint, paginationResp.First.Page, paginationResp.First.Limit) | |
} | |
if paginationResp.Last != nil { | |
paginationMessage.Last = fmt.Sprintf("%s?page=%d&limit=%d", endpoint, paginationResp.Last.Page, paginationResp.Last.Limit) | |
} | |
if paginationResp.Next != nil { | |
paginationMessage.Next = fmt.Sprintf("%s?page=%d&limit=%d", endpoint, paginationResp.Next.Page, paginationResp.Next.Limit) | |
} | |
if paginationResp.Prev != nil { | |
paginationMessage.Prev = fmt.Sprintf("%s?page=%d&limit=%d", endpoint, paginationResp.Prev.Page, paginationResp.Prev.Limit) | |
} | |
// 構築したpaginationMessageをAny型に埋め込む作業 | |
serialized, err := proto.Marshal(paginationMessage) | |
if err != nil { | |
return err | |
} | |
paginationAnyMessage := &any.Any{ | |
TypeUrl: proto.MessageName(paginationMessage), | |
Value: serialized, | |
} | |
r.Pagination = paginationAnyMessage | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment