cubefs

Форк
0
119 строк · 3.8 Кб
1
// Copyright 2022 The CubeFS Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12
// implied. See the License for the specific language governing
13
// permissions and limitations under the License.
14

15
package example
16

17
import (
18
	"net/http"
19
	"time"
20

21
	"github.com/cubefs/cubefs/blobstore/common/rpc"
22
	"github.com/cubefs/cubefs/blobstore/common/trace"
23
)
24

25
func init() {
26
	trace.RequestIDKey = "rid"
27
	trace.PrefixBaggage = "baggage-"
28
	trace.FieldKeyTraceID = "traceid"
29
	trace.FieldKeySpanID = "spanid"
30
}
31

32
type metaValue struct {
33
	val int
34
}
35

36
func interceptorWholeRequest(c *rpc.Context) {
37
	span := trace.SpanFromContextSafe(c.Request.Context())
38

39
	c.Set("var", &metaValue{0})
40
	start := time.Now()
41
	c.Next()
42
	metaVal, _ := c.Get("var")
43
	val := metaVal.(*metaValue)
44
	span.Infof("Request %s: done Val=%d, spent %s", c.Request.URL.Path, val.val, time.Since(start).String())
45
}
46

47
func interceptorNothing1(c *rpc.Context) {
48
	span := trace.SpanFromContextSafe(c.Request.Context())
49

50
	metaVal, _ := c.Get("var")
51
	val := metaVal.(*metaValue)
52
	val.val += 10
53
	span.Infof("Request %s: interceptor nothing-1 Val=%d", c.Request.URL.Path, val.val)
54
}
55

56
func interceptorNothing2(c *rpc.Context) {
57
	span := trace.SpanFromContextSafe(c.Request.Context())
58

59
	metaVal, _ := c.Get("var")
60
	val := metaVal.(*metaValue)
61
	val.val++
62
	span.Debugf("Request %s: interceptor nothing-2 Val=%d", c.Request.URL.Path, val.val)
63
}
64

65
// NewAppHandler returns app server handler, use rpc.DefaultRouter
66
func NewAppHandler(cfg AppConfig) *rpc.Router {
67
	// must be register args with tag
68
	rpc.RegisterArgsParser(&ArgsUpload{}, "flag")
69
	rpc.RegisterArgsParser(&ArgsDelete{})
70
	rpc.RegisterArgsParser(&ArgsDownload{}, "form", "formx")
71
	rpc.RegisterArgsParser(&ArgsExist{})
72
	rpc.RegisterArgsParser(&ArgsURIOptional{}, "json")
73

74
	app := NewApp(cfg)
75

76
	rpc.Use(interceptorWholeRequest)                  // first interceptor
77
	rpc.Use(interceptorNothing1, interceptorNothing2) // second, then third
78

79
	// args key/val in c.Param
80
	rpc.PUT("/upload/:name/:size/:mode/:desc", app.Upload, rpc.OptArgsURI())
81
	// parse args in handler by c.ArgsBody
82
	rpc.POST("/update", app.Update)
83
	rpc.DELETE("/delete", app.Delete, rpc.OptArgsQuery())
84
	rpc.POST("/download", app.Download, rpc.OptArgsForm())
85
	rpc.GET("/stream", app.Stream)
86
	// param priority is uri > query > form > postfrom by default
87
	// but you can define you own rpc.Parser on args struct
88
	rpc.HEAD("/exist/:name", app.Exist, rpc.OptArgsURI(), rpc.OptArgsQuery())
89
	rpc.GET("/stat/:name", app.Stat, rpc.OptArgsURI(), rpc.OptArgsQuery())
90
	// initialized 8 room for key/val map of c.Meta
91
	rpc.GET("/list", app.List, rpc.OptMetaCapacity(8))
92

93
	// argument in uri with option
94
	rpc.GET("/args/:require/:option", app.OptionalArgs, rpc.OptArgsURI())
95
	// argument in uri without option
96
	rpc.GET("/args/:require", app.OptionalArgs, rpc.OptArgsURI())
97

98
	return rpc.DefaultRouter
99
}
100

101
// NewFileHandler returns file server handler
102
func NewFileHandler() *rpc.Router {
103
	rpc.RegisterArgsParser(&ArgsWrite{}, "flag")
104

105
	router := rpc.New()
106
	filer := NewFile()
107
	router.Handle(http.MethodPut, "/write/:size", filer.Write, rpc.OptArgsURI())
108
	router.Handle(http.MethodGet, "/read/:size", filer.Read, rpc.OptArgsURI())
109
	return router
110
}
111

112
// NewMetaHandler returns meta server handler
113
func NewMetaHandler() *rpc.Router {
114
	router := rpc.New()
115
	filer := NewFile()
116
	router.Handle(http.MethodPut, "/write/:size", filer.Write, rpc.OptArgsURI())
117
	router.Handle(http.MethodGet, "/read/:size", filer.Read, rpc.OptArgsURI())
118
	return router
119
}
120

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.