Skip to content

Instantly share code, notes, and snippets.

View sang-w0o's full-sized avatar
🎯
Focusing

나상우(Roy) sang-w0o

🎯
Focusing
View GitHub Profile
@sang-w0o
sang-w0o / grpc_gateway_1.go
Created February 28, 2022 08:36
grpc_gateway_1.go
func New() {
// Chi Router 초기화
router := chi.NewRouter()
// Middleware 적용
router.Use(authorizeMiddleware())
router.Use(middleWare())
router.Use(anotherMiddleware())
// grpc-gateway 사용을 위한 코드
@sang-w0o
sang-w0o / grpc_gateway_2.go
Last active February 28, 2022 08:52
grpc_gateway_2.go
func New() {
// chi.Router 초기화 및 middleware 적용
// gRPC Service 구현체에 context를 넘기기 위한 코드
annotationFunc := func(ctx context.Context, request *http.Request) metadata.MD {
return metadata.New(map[string]string{
"key1": "value1",
"key2": "value2",
})
@sang-w0o
sang-w0o / grpc_gateway_3.go
Last active February 28, 2022 09:04
grpc_gateway_3.go
func setContextFromMetadata(ctx context.Context) (context.Context, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
// handle error
}
data := md.Get("value1")
if len(data) == 0 {
return nil, fmt.Errorf("some error occured.")
}
@sang-w0o
sang-w0o / grpc_gateway_4.go
Created March 2, 2022 02:58
grpc_gateway_4.go
func New() {
router := chi.NewRouter()
//..
router.Route("/api/", func(r chi.Router) {
r.Post("/1", func(w http.ResponseWriter, r *http.Request) {
mux.ServeHTTP(w, r)
})
@sang-w0o
sang-w0o / grpc_gateway_5.go
Last active March 2, 2022 03:37
grpc_gateway_5.go
type ServeMux struct {
// handlers maps HTTP method to a list of handlers.
handlers map[string][]handler
//..
}
type handler struct {
pat Pattern
h HandlerFunc
}
@sang-w0o
sang-w0o / grpc_gateway_6.go
Created March 2, 2022 05:20
grpc_gateway_6.go
func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//..
// ServeMux의 handler를 하나씩 순회해요.
for _, h := range s.handlers[r.Method] {
// http.Request를 통해 알맞은 endpoint에 등록된
// handler를 찾아 아래 request를 handle하게 해요.
h.h(w, r, pathParams)
}
}
@sang-w0o
sang-w0o / grpc_gateway_7.go
Created March 2, 2022 05:54
grpc_gateway_7.go
func RegisterAdminHandlerClient(ctx context.Context, mux *runtime.ServeMux, client AdminClient) error {
mux.Handle("POST", pattern_Admin_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
// http request (body, path parameter, query parameter 등)를 Proto Message로 변환해
// 매핑된 gRPC Service 함수를 호출해요.
})
}
@sang-w0o
sang-w0o / grpc_gateway_8.go
Created March 2, 2022 05:57
grpc_gateway_8.go
func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) {
s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...)
}
@sang-w0o
sang-w0o / grpc_gateway_9.go
Created March 2, 2022 06:32
grpc_gateway_9.go
func New() {
router = chi.NewRoter()
//..
router.Mount("/api", http.HandlerFunc(mux.ServeHTTP))
}
@sang-w0o
sang-w0o / mini_memcached.go
Last active March 14, 2022 05:21
mini_memcached.go
package benchmarks
import (
"net"
"sync"
)
type Server struct {
l net.Listener
}