-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
69 lines (56 loc) · 1.48 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package grpc
import (
"context"
"fmt"
"net/http"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/types/known/wrapperspb"
)
// ToString convert to a string pointer from wrapper
func ToString(value *wrapperspb.StringValue) *string {
if value != nil {
return &value.Value
}
return nil
}
// GetString converts to a string wrapper from a string pointer
func GetString(value *string) *wrapperspb.StringValue {
if value != nil {
return &wrapperspb.StringValue{Value: *value}
}
return nil
}
// SetCookie adds a Set-Cookie header to the provided server transport context.
// The provided cookie must have a valid Name. Invalid cookies may be
// silently dropped.
func SetCookie(ctx context.Context, cookie *http.Cookie) error {
if v := cookie.String(); v != "" {
md := metadata.Pairs("Set-Cookie", v)
return grpc.SetHeader(ctx, md)
}
return nil
}
// SetStatusCode sets the status code
func SetStatusCode(ctx context.Context, code int) {
value := fmt.Sprintf("%v", code)
// set the header
grpc.SetHeader(ctx, metadata.Pairs("x-http-code", value))
}
// CookieFromIncomingContext returns the cookie
func CookieFromIncomingContext(ctx context.Context, name string) (*http.Cookie, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, http.ErrNoCookie
}
value, ok := md["cookie"]
if !ok {
return nil, http.ErrNoCookie
}
r := &http.Request{
Header: http.Header{
"Cookie": value,
},
}
return r.Cookie(name)
}