How to use Get method of v1 Package

Best Testkube code snippet using v1.Get

http_handler.go

Source:http_handler.go Github

copy

Full Screen

...31 jsonStr = string(json_str)32 }33 return34}35func GetPutJson(req *gin.Context) *simplejson.Json{36 bodyByte := make([]byte,1000)37 _,_ = req.Request.Body.Read(bodyByte)38 js, err := simplejson.NewJson([]byte(bodyByte))39 if err != nil {40 return nil41 }42 return js43}44func GetUserInfo(token string) (*common.JwtTokenInfo){45 if token==""{46 return nil47 }48 info,succ := common.JwtDecry(token)49 if !succ {50 return nil51 }52 return &info53}54// 认证中间件55func AuthMiddleWare() gin.HandlerFunc {56 return func(c *gin.Context) {57 userInfo := GetUserInfo(c.Request.Header.Get("Authorization"))58 if userInfo == nil {59 c.String(http.StatusUnauthorized,"token invalid")60 c.Abort()61 }62 c.Set("user_info",userInfo)// 设置变量到Context的key中,可以通过Get()取63 }64}65func PostReq(c *gin.Context,resp proto.Message,err error){66 if err != nil {67 status, _ := status.FromError(err)68 c.JSON(http.StatusBadRequest, gin.H{69 "err_code": status.Code(),70 "err_msg": status.Message(),71 })72 return73 }74 c.JSON(http.StatusOK,resp)75}76type ApiServerV1 struct {77 conf *config.Access78 rmg *RoomManager79}80func NewApiServerV1(c *config.Access) *ApiServerV1{81 return &ApiServerV1{82 conf: c,83 rmg: NewRoomManager(),84 }85}86func (v1 *ApiServerV1)InitRouter(){87 router := gin.Default()88 router.GET("/login",v1.Login)//websocket收发消息处理89 router.PUT("/user/create",v1.AddUser)90 r1 := router.Group("/v1")91 //r1.Use(AuthMiddleWare())92 {93 r1.GET("/ws",v1.WsClient)//websocket收发消息处理94 r1.GET("/rtc",v1.RtcClient)//websocket收发消息处理95 r1.PUT("/device/register",v1.RegisterDevice)96 r1.DELETE("/device/delete",v1.DeleteDevice)97 r1.GET("/device/list",v1.GetDeviceList)98 //user99 r1.POST("/user/update",v1.UpdateUser)100 r1.GET("/user/get",v1.GetUser)101 r1.GET("/user/group/list",v1.GetUserGroups)102 //group103 r1.GET("/group/create",v1.CreateGroup)104 r1.POST("/group/update",v1.UpdateGroup)105 r1.GET("/group/get",v1.GetGroup)106 r1.DELETE("/group/delete",v1.DeleteGroup)107 //group member108 r1.PUT("/group_member/add",v1.AddGroupMember)109 r1.POST("/group_member/update",v1.UpdateGroupMember)110 r1.DELETE("/group_member/delete",v1.DeleteGroupMember)111 r1.GET("/group_member/list",v1.GetGroupMembers)112 }113 router.Run(v1.conf.HttpAddr)114}115func (v1 *ApiServerV1) Close(){116}117func (v1 *ApiServerV1)Login(c *gin.Context){118 body := GetPutJson(c)119 if body ==nil {120 c.String(http.StatusBadRequest,"nil body")121 return122 }123 appIdStr := body.Get("app_id").MustString()124 appId,_ := strconv.ParseInt(appIdStr, 10, 64)125 userIdStr := body.Get("user_id").MustString()126 userId,_ := strconv.ParseInt(userIdStr,10,64)127 passwd := body.Get("password").MustString()128 req := &pb.SignInReq{129 AppId: appId,130 UserId: userId,131 Passwd: passwd,132 ConnId: global.AppConfig.AppId,133 DeviceId: 0,134 UserIp: c.Request.RemoteAddr,135 }136 userBasicInfo,_ := c.Get("user_info")137 resp, err := global.WsDispatch.SignIn(common.GetContext(userBasicInfo.(common.JwtTokenInfo)),req)138 if err != nil {139 status, _ := status.FromError(err)140 c.JSON(http.StatusBadRequest, gin.H{141 "err_code": status.Code(),142 "err_msg": status.Message(),143 })144 return145 }146 c.JSON(http.StatusOK,resp)147}148func (v1 *ApiServerV1)WsClient(c *gin.Context) {149 if ! c.IsWebsocket() {150 c.String(http.StatusOK, "====not websocket request====")151 }152 w,r := c.Writer,c.Request153 upgrader := websocket.Upgrader{}154 appId, _ := strconv.ParseInt(r.Header.Get(common.CtxAppId), 10, 64)155 userId, _ := strconv.ParseInt(r.Header.Get(common.CtxUserId), 10, 64)156 deviceId, _ := strconv.ParseInt(r.Header.Get(common.CtxDeviceId), 10, 64)157 passwd := r.Header.Get(common.CtxToken)158 if appId == 0 || userId == 0 || deviceId == 0 || passwd == "" {159 s, _ := status.FromError(common.ErrUnauthorized)160 bytes, err := json.Marshal(s.Proto())161 if err != nil {162 common.Sugar.Error(err)163 return164 }165 w.Write(bytes)166 return167 }168 _, err := global.WsDispatch.SignIn(common.ContextWithRequstId(context.TODO()), &pb.SignInReq{169 AppId: appId,170 UserId: userId,171 DeviceId: deviceId,172 Passwd: passwd,173 ConnId: global.AppConfig.SrvDisc.ID,174 UserIp:r.RemoteAddr,175 })176 s, _ := status.FromError(err)177 if s.Code() != codes.OK {178 bytes, err := json.Marshal(s.Proto())179 if err != nil {180 common.Sugar.Error(err)181 return182 }183 w.Write(bytes)184 return185 }186 conn, err := upgrader.Upgrade(w, r, nil)187 if err != nil {188 common.Sugar.Error(err)189 return190 }191 // 断开这个设备之前的连接192 preCtx := LoadWsClientOnline(userId)193 if preCtx != nil {194 preCtx.DeviceId = 0195 }196 ctx := NewWSConnContext(conn, appId, userId, deviceId)197 StoreWsClientOnline(userId, ctx)198 ctx.DoConn()199}200func (v1 *ApiServerV1)RtcClient(c *gin.Context) {201 if ! c.IsWebsocket() {202 c.String(http.StatusOK, "====not websocket request====")203 }204 w,r := c.Writer,c.Request205 upgrader := websocket.Upgrader{}206 appId, _ := strconv.ParseInt(r.Header.Get(common.CtxAppId), 10, 64)207 userId, _ := strconv.ParseInt(r.Header.Get(common.CtxUserId), 10, 64)208 //passwd := r.Header.Get(common.CtxToken)209 //210 //if appId == 0 || userId == 0 || passwd == "" {211 // s, _ := status.FromError(common.ErrUnauthorized)212 // bytes, err := json.Marshal(s.Proto())213 // if err != nil {214 // common.Sugar.Error(err)215 // return216 // }217 // w.Write(bytes)218 // return219 //}220 //_, err := global.WsDispatch.SignIn(common.ContextWithRequstId(context.TODO()), &pb.SignInReq{221 // AppId: appId,222 // UserId: userId,223 // Passwd: passwd,224 // ConnId: global.AppConfig.SrvDisc.ID,225 // UserIp:r.RemoteAddr,226 //})227 //228 //s, _ := status.FromError(err)229 //if s.Code() != codes.OK {230 // bytes, err := json.Marshal(s.Proto())231 // if err != nil {232 // common.Sugar.Error(err)233 // return234 // }235 // w.Write(bytes)236 // return237 //}238 conn, err := upgrader.Upgrade(w, r, nil)239 if err != nil {240 common.Sugar.Error(err)241 return242 }243 ctx := NewRtcContext(v1.rmg,conn, appId, userId )244 ctx.Serve()245}246func(v1 *ApiServerV1) RegisterDevice(c *gin.Context) {247 body := GetPutJson(c)248 if body ==nil {249 c.String(http.StatusBadRequest,"nil body")250 return251 }252 appIdStr := body.Get("app_id").MustString()253 appId,_ := strconv.ParseInt(appIdStr, 10, 64)254 brand := body.Get("brand").MustString()255 model := body.Get("model").MustString()256 sysVer := body.Get("system_version").MustString()257 sdkVer := body.Get("sdk_version").MustString()258 req := &pb.RegisterDeviceReq{259 AppId: appId,260 Brand: brand,261 Model: model,262 SystemVersion: sysVer,263 SdkVersion: sdkVer,264 Type: int32(2),265 }266 userBasicInfo,_ := c.Get("user_info")267 remoteSrv := global.GetHttpDispathServer(c.Request.RemoteAddr)268 if remoteSrv ==nil {269 c.String(http.StatusInternalServerError,"远程服务不可用")270 c.Abort()271 }272 resp, err := remoteSrv.RegisterDevice(common.GetContext(userBasicInfo.(common.JwtTokenInfo)),req)273 PostReq(c,resp,err)274}275func(v1 *ApiServerV1) DeleteDevice(c *gin.Context) {276 //deviceId := c.Param("device_id")277 c.String(http.StatusOK, "to be design...")278}279func(v1 *ApiServerV1) GetDeviceList(c *gin.Context) {280 c.String(http.StatusOK, "to be design...")281}282func GetPage(w http.ResponseWriter, r *http.Request) {283 output := make(chan bool, 1)284 errors := hystrix.Go("get_page", func() error {285 _, err := http.Get("https://www.baidu.com/")286 if err == nil {287 output <- true288 }289 return err290 }, func(err2 error) error {//失败返回291 fmt.Println("get page fail")292 return nil293 })294 select {295 case out := <-output:296 log.Printf("success %v", out)// success297 case err := <-errors:298 log.Printf("failed %s", err)// failure299 }300}301func(v1 *ApiServerV1) AddUser(c *gin.Context) {302 body := GetPutJson(c)303 if body ==nil {304 c.String(http.StatusBadRequest,"nil body")305 return306 }307 //appIdStr := body.Get("app_id").MustString()308 //appId,_ := strconv.ParseInt(appIdStr, 10, 64)309 name := body.Get("nick_name").MustString()310 avatar := body.Get("avatar_url").MustString()311 extra := body.Get("system_version").MustString()312 sexStr := body.Get("sex").MustString()313 gender,_ := strconv.Atoi(sexStr)314 req := &pb.AddUserReq{315 User: &pb.User{316 UserId: 1,317 Nickname: name,318 Sex: int32(gender),319 AvatarUrl: avatar,320 Extra: extra,321 },322 }323 //自定义配置324 //hystrix.ConfigureCommand("chat_api", hystrix.CommandConfig{325 // Timeout: 500,326 // MaxConcurrentRequests: 100,327 // ErrorPercentThreshold: 50,328 // RequestVolumeThreshold: 3,329 // SleepWindow: 1000,330 //})331 hystrix.Go("add_user", func() error {332 resp, err := global.WsDispatch.AddUser(common.SimpleContext(),req)333 if err != nil {334 fmt.Println("add user failed")335 return err336 }337 PostReq(c,resp,err)338 return nil339 }, func(e error) error {340 fmt.Println("add user failed:",e)341 return nil342 })343}344func(v1 *ApiServerV1) UpdateUser(c *gin.Context) {345 c.String(http.StatusOK, "to be design...")346}347func(v1 *ApiServerV1) GetUser(c *gin.Context) {348 c.String(http.StatusOK, "to be design...")349}350func(v1 *ApiServerV1) GetUserGroups(c *gin.Context) {351 c.String(http.StatusOK, "to be design...")352}353func(v1 *ApiServerV1) CreateGroup(c *gin.Context) {354 c.String(http.StatusOK, "to be design...")355}356func(v1 *ApiServerV1) UpdateGroup(c *gin.Context) {357 c.String(http.StatusOK, "to be design...")358}359func(v1 *ApiServerV1) GetGroup(c *gin.Context) {360 c.String(http.StatusOK, "to be design...")361}362func(v1 *ApiServerV1) DeleteGroup(c *gin.Context) {363 c.String(http.StatusOK, "to be design...")364}365func(v1 *ApiServerV1) AddGroupMember(c *gin.Context) {366 c.String(http.StatusOK, "to be design...")367}368func(v1 *ApiServerV1) UpdateGroupMember(c *gin.Context) {369 c.String(http.StatusOK, "to be design...")370}371func(v1 *ApiServerV1) DeleteGroupMember(c *gin.Context) {372 c.String(http.StatusOK, "to be design...")373}374func(v1 *ApiServerV1) GetGroupMembers(c *gin.Context) {375 c.String(http.StatusOK, "to be design...")376}...

Full Screen

Full Screen

http_register.go

Source:http_register.go Github

copy

Full Screen

...3 registerEndpoint("/v1/acl/bootstrap", []string{"PUT"}, (*HTTPServer).ACLBootstrap)4 registerEndpoint("/v1/acl/create", []string{"PUT"}, (*HTTPServer).ACLCreate)5 registerEndpoint("/v1/acl/update", []string{"PUT"}, (*HTTPServer).ACLUpdate)6 registerEndpoint("/v1/acl/destroy/", []string{"PUT"}, (*HTTPServer).ACLDestroy)7 registerEndpoint("/v1/acl/info/", []string{"GET"}, (*HTTPServer).ACLGet)8 registerEndpoint("/v1/acl/clone/", []string{"PUT"}, (*HTTPServer).ACLClone)9 registerEndpoint("/v1/acl/list", []string{"GET"}, (*HTTPServer).ACLList)10 registerEndpoint("/v1/acl/login", []string{"POST"}, (*HTTPServer).ACLLogin)11 registerEndpoint("/v1/acl/logout", []string{"POST"}, (*HTTPServer).ACLLogout)12 registerEndpoint("/v1/acl/replication", []string{"GET"}, (*HTTPServer).ACLReplicationStatus)13 registerEndpoint("/v1/acl/policies", []string{"GET"}, (*HTTPServer).ACLPolicyList)14 registerEndpoint("/v1/acl/policy", []string{"PUT"}, (*HTTPServer).ACLPolicyCreate)15 registerEndpoint("/v1/acl/policy/", []string{"GET", "PUT", "DELETE"}, (*HTTPServer).ACLPolicyCRUD)16 registerEndpoint("/v1/acl/policy/name/", []string{"GET"}, (*HTTPServer).ACLPolicyReadByName)17 registerEndpoint("/v1/acl/roles", []string{"GET"}, (*HTTPServer).ACLRoleList)18 registerEndpoint("/v1/acl/role", []string{"PUT"}, (*HTTPServer).ACLRoleCreate)19 registerEndpoint("/v1/acl/role/name/", []string{"GET"}, (*HTTPServer).ACLRoleReadByName)20 registerEndpoint("/v1/acl/role/", []string{"GET", "PUT", "DELETE"}, (*HTTPServer).ACLRoleCRUD)21 registerEndpoint("/v1/acl/binding-rules", []string{"GET"}, (*HTTPServer).ACLBindingRuleList)22 registerEndpoint("/v1/acl/binding-rule", []string{"PUT"}, (*HTTPServer).ACLBindingRuleCreate)23 registerEndpoint("/v1/acl/binding-rule/", []string{"GET", "PUT", "DELETE"}, (*HTTPServer).ACLBindingRuleCRUD)24 registerEndpoint("/v1/acl/auth-methods", []string{"GET"}, (*HTTPServer).ACLAuthMethodList)25 registerEndpoint("/v1/acl/auth-method", []string{"PUT"}, (*HTTPServer).ACLAuthMethodCreate)26 registerEndpoint("/v1/acl/auth-method/", []string{"GET", "PUT", "DELETE"}, (*HTTPServer).ACLAuthMethodCRUD)27 registerEndpoint("/v1/acl/rules/translate", []string{"POST"}, (*HTTPServer).ACLRulesTranslate)28 registerEndpoint("/v1/acl/rules/translate/", []string{"GET"}, (*HTTPServer).ACLRulesTranslateLegacyToken)29 registerEndpoint("/v1/acl/tokens", []string{"GET"}, (*HTTPServer).ACLTokenList)30 registerEndpoint("/v1/acl/token", []string{"PUT"}, (*HTTPServer).ACLTokenCreate)31 registerEndpoint("/v1/acl/token/self", []string{"GET"}, (*HTTPServer).ACLTokenSelf)32 registerEndpoint("/v1/acl/token/", []string{"GET", "PUT", "DELETE"}, (*HTTPServer).ACLTokenCRUD)33 registerEndpoint("/v1/agent/token/", []string{"PUT"}, (*HTTPServer).AgentToken)34 registerEndpoint("/v1/agent/self", []string{"GET"}, (*HTTPServer).AgentSelf)35 registerEndpoint("/v1/agent/host", []string{"GET"}, (*HTTPServer).AgentHost)36 registerEndpoint("/v1/agent/maintenance", []string{"PUT"}, (*HTTPServer).AgentNodeMaintenance)37 registerEndpoint("/v1/agent/reload", []string{"PUT"}, (*HTTPServer).AgentReload)38 registerEndpoint("/v1/agent/monitor", []string{"GET"}, (*HTTPServer).AgentMonitor)39 registerEndpoint("/v1/agent/metrics", []string{"GET"}, (*HTTPServer).AgentMetrics)40 registerEndpoint("/v1/agent/services", []string{"GET"}, (*HTTPServer).AgentServices)41 registerEndpoint("/v1/agent/service/", []string{"GET"}, (*HTTPServer).AgentService)42 registerEndpoint("/v1/agent/checks", []string{"GET"}, (*HTTPServer).AgentChecks)43 registerEndpoint("/v1/agent/members", []string{"GET"}, (*HTTPServer).AgentMembers)44 registerEndpoint("/v1/agent/join/", []string{"PUT"}, (*HTTPServer).AgentJoin)45 registerEndpoint("/v1/agent/leave", []string{"PUT"}, (*HTTPServer).AgentLeave)46 registerEndpoint("/v1/agent/force-leave/", []string{"PUT"}, (*HTTPServer).AgentForceLeave)47 registerEndpoint("/v1/agent/health/service/id/", []string{"GET"}, (*HTTPServer).AgentHealthServiceByID)48 registerEndpoint("/v1/agent/health/service/name/", []string{"GET"}, (*HTTPServer).AgentHealthServiceByName)49 registerEndpoint("/v1/agent/check/register", []string{"PUT"}, (*HTTPServer).AgentRegisterCheck)50 registerEndpoint("/v1/agent/check/deregister/", []string{"PUT"}, (*HTTPServer).AgentDeregisterCheck)51 registerEndpoint("/v1/agent/check/pass/", []string{"PUT"}, (*HTTPServer).AgentCheckPass)52 registerEndpoint("/v1/agent/check/warn/", []string{"PUT"}, (*HTTPServer).AgentCheckWarn)53 registerEndpoint("/v1/agent/check/fail/", []string{"PUT"}, (*HTTPServer).AgentCheckFail)54 registerEndpoint("/v1/agent/check/update/", []string{"PUT"}, (*HTTPServer).AgentCheckUpdate)55 registerEndpoint("/v1/agent/connect/authorize", []string{"POST"}, (*HTTPServer).AgentConnectAuthorize)56 registerEndpoint("/v1/agent/connect/ca/roots", []string{"GET"}, (*HTTPServer).AgentConnectCARoots)57 registerEndpoint("/v1/agent/connect/ca/leaf/", []string{"GET"}, (*HTTPServer).AgentConnectCALeafCert)58 registerEndpoint("/v1/agent/service/register", []string{"PUT"}, (*HTTPServer).AgentRegisterService)59 registerEndpoint("/v1/agent/service/deregister/", []string{"PUT"}, (*HTTPServer).AgentDeregisterService)60 registerEndpoint("/v1/agent/service/maintenance/", []string{"PUT"}, (*HTTPServer).AgentServiceMaintenance)61 registerEndpoint("/v1/catalog/register", []string{"PUT"}, (*HTTPServer).CatalogRegister)62 registerEndpoint("/v1/catalog/connect/", []string{"GET"}, (*HTTPServer).CatalogConnectServiceNodes)63 registerEndpoint("/v1/catalog/deregister", []string{"PUT"}, (*HTTPServer).CatalogDeregister)64 registerEndpoint("/v1/catalog/datacenters", []string{"GET"}, (*HTTPServer).CatalogDatacenters)65 registerEndpoint("/v1/catalog/nodes", []string{"GET"}, (*HTTPServer).CatalogNodes)66 registerEndpoint("/v1/catalog/services", []string{"GET"}, (*HTTPServer).CatalogServices)67 registerEndpoint("/v1/catalog/service/", []string{"GET"}, (*HTTPServer).CatalogServiceNodes)68 registerEndpoint("/v1/catalog/node/", []string{"GET"}, (*HTTPServer).CatalogNodeServices)69 registerEndpoint("/v1/catalog/node-services/", []string{"GET"}, (*HTTPServer).CatalogNodeServiceList)70 registerEndpoint("/v1/config/", []string{"GET", "DELETE"}, (*HTTPServer).Config)71 registerEndpoint("/v1/config", []string{"PUT"}, (*HTTPServer).ConfigApply)72 registerEndpoint("/v1/connect/ca/configuration", []string{"GET", "PUT"}, (*HTTPServer).ConnectCAConfiguration)73 registerEndpoint("/v1/connect/ca/roots", []string{"GET"}, (*HTTPServer).ConnectCARoots)74 registerEndpoint("/v1/connect/intentions", []string{"GET", "POST"}, (*HTTPServer).IntentionEndpoint)75 registerEndpoint("/v1/connect/intentions/match", []string{"GET"}, (*HTTPServer).IntentionMatch)76 registerEndpoint("/v1/connect/intentions/check", []string{"GET"}, (*HTTPServer).IntentionCheck)77 registerEndpoint("/v1/connect/intentions/", []string{"GET", "PUT", "DELETE"}, (*HTTPServer).IntentionSpecific)78 registerEndpoint("/v1/coordinate/datacenters", []string{"GET"}, (*HTTPServer).CoordinateDatacenters)79 registerEndpoint("/v1/coordinate/nodes", []string{"GET"}, (*HTTPServer).CoordinateNodes)80 registerEndpoint("/v1/coordinate/node/", []string{"GET"}, (*HTTPServer).CoordinateNode)81 registerEndpoint("/v1/coordinate/update", []string{"PUT"}, (*HTTPServer).CoordinateUpdate)82 registerEndpoint("/v1/internal/federation-states", []string{"GET"}, (*HTTPServer).FederationStateList)83 registerEndpoint("/v1/internal/federation-states/mesh-gateways", []string{"GET"}, (*HTTPServer).FederationStateListMeshGateways)84 registerEndpoint("/v1/internal/federation-state/", []string{"GET"}, (*HTTPServer).FederationStateGet)85 registerEndpoint("/v1/discovery-chain/", []string{"GET", "POST"}, (*HTTPServer).DiscoveryChainRead)86 registerEndpoint("/v1/event/fire/", []string{"PUT"}, (*HTTPServer).EventFire)87 registerEndpoint("/v1/event/list", []string{"GET"}, (*HTTPServer).EventList)88 registerEndpoint("/v1/health/node/", []string{"GET"}, (*HTTPServer).HealthNodeChecks)89 registerEndpoint("/v1/health/checks/", []string{"GET"}, (*HTTPServer).HealthServiceChecks)90 registerEndpoint("/v1/health/state/", []string{"GET"}, (*HTTPServer).HealthChecksInState)91 registerEndpoint("/v1/health/service/", []string{"GET"}, (*HTTPServer).HealthServiceNodes)92 registerEndpoint("/v1/health/connect/", []string{"GET"}, (*HTTPServer).HealthConnectServiceNodes)93 registerEndpoint("/v1/internal/ui/nodes", []string{"GET"}, (*HTTPServer).UINodes)94 registerEndpoint("/v1/internal/ui/node/", []string{"GET"}, (*HTTPServer).UINodeInfo)95 registerEndpoint("/v1/internal/ui/services", []string{"GET"}, (*HTTPServer).UIServices)96 registerEndpoint("/v1/internal/acl/authorize", []string{"POST"}, (*HTTPServer).ACLAuthorize)97 registerEndpoint("/v1/kv/", []string{"GET", "PUT", "DELETE"}, (*HTTPServer).KVSEndpoint)98 registerEndpoint("/v1/operator/raft/configuration", []string{"GET"}, (*HTTPServer).OperatorRaftConfiguration)99 registerEndpoint("/v1/operator/raft/peer", []string{"DELETE"}, (*HTTPServer).OperatorRaftPeer)100 registerEndpoint("/v1/operator/keyring", []string{"GET", "POST", "PUT", "DELETE"}, (*HTTPServer).OperatorKeyringEndpoint)101 registerEndpoint("/v1/operator/autopilot/configuration", []string{"GET", "PUT"}, (*HTTPServer).OperatorAutopilotConfiguration)102 registerEndpoint("/v1/operator/autopilot/health", []string{"GET"}, (*HTTPServer).OperatorServerHealth)103 registerEndpoint("/v1/query", []string{"GET", "POST"}, (*HTTPServer).PreparedQueryGeneral)104 // specific prepared query endpoints have more complex rules for allowed methods, so105 // the prefix is registered with no methods.106 registerEndpoint("/v1/query/", []string{}, (*HTTPServer).PreparedQuerySpecific)107 registerEndpoint("/v1/session/create", []string{"PUT"}, (*HTTPServer).SessionCreate)108 registerEndpoint("/v1/session/destroy/", []string{"PUT"}, (*HTTPServer).SessionDestroy)109 registerEndpoint("/v1/session/renew/", []string{"PUT"}, (*HTTPServer).SessionRenew)110 registerEndpoint("/v1/session/info/", []string{"GET"}, (*HTTPServer).SessionGet)111 registerEndpoint("/v1/session/node/", []string{"GET"}, (*HTTPServer).SessionsForNode)112 registerEndpoint("/v1/session/list", []string{"GET"}, (*HTTPServer).SessionList)113 registerEndpoint("/v1/status/leader", []string{"GET"}, (*HTTPServer).StatusLeader)114 registerEndpoint("/v1/status/peers", []string{"GET"}, (*HTTPServer).StatusPeers)115 registerEndpoint("/v1/snapshot", []string{"GET", "PUT"}, (*HTTPServer).Snapshot)116 registerEndpoint("/v1/txn", []string{"PUT"}, (*HTTPServer).Txn)117}...

Full Screen

Full Screen

requestinfo_test.go

Source:requestinfo_test.go Github

copy

Full Screen

...20type fakeRL bool21func (fakeRL) Stop() {}22func (f fakeRL) TryAccept() bool { return bool(f) }23func (f fakeRL) Accept() {}24func TestGetAPIRequestInfo(t *testing.T) {25 namespaceAll := "" // TODO(sttts): solve import cycle when using metav1.NamespaceAll26 successCases := []struct {27 method string28 url string29 expectedVerb string30 expectedAPIPrefix string31 expectedAPIGroup string32 expectedAPIVersion string33 expectedNamespace string34 expectedResource string35 expectedSubresource string36 expectedName string37 expectedParts []string38 }{39 // resource paths40 {"GET", "/api/v1/namespaces", "list", "api", "", "v1", "", "namespaces", "", "", []string{"namespaces"}},41 {"GET", "/api/v1/namespaces/other", "get", "api", "", "v1", "other", "namespaces", "", "other", []string{"namespaces", "other"}},42 {"GET", "/api/v1/namespaces/other/pods", "list", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},43 {"GET", "/api/v1/namespaces/other/pods/foo", "get", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},44 {"HEAD", "/api/v1/namespaces/other/pods/foo", "get", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},45 {"GET", "/api/v1/pods", "list", "api", "", "v1", namespaceAll, "pods", "", "", []string{"pods"}},46 {"HEAD", "/api/v1/pods", "list", "api", "", "v1", namespaceAll, "pods", "", "", []string{"pods"}},47 {"GET", "/api/v1/namespaces/other/pods/foo", "get", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},48 {"GET", "/api/v1/namespaces/other/pods", "list", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},49 // special verbs50 {"GET", "/api/v1/proxy/namespaces/other/pods/foo", "proxy", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},51 {"GET", "/api/v1/proxy/namespaces/other/pods/foo/subpath/not/a/subresource", "proxy", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo", "subpath", "not", "a", "subresource"}},52 {"GET", "/api/v1/watch/pods", "watch", "api", "", "v1", namespaceAll, "pods", "", "", []string{"pods"}},53 {"GET", "/api/v1/pods?watch=true", "watch", "api", "", "v1", namespaceAll, "pods", "", "", []string{"pods"}},54 {"GET", "/api/v1/pods?watch=false", "list", "api", "", "v1", namespaceAll, "pods", "", "", []string{"pods"}},55 {"GET", "/api/v1/watch/namespaces/other/pods", "watch", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},56 {"GET", "/api/v1/namespaces/other/pods?watch=1", "watch", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},57 {"GET", "/api/v1/namespaces/other/pods?watch=0", "list", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},58 // subresource identification59 {"GET", "/api/v1/namespaces/other/pods/foo/status", "get", "api", "", "v1", "other", "pods", "status", "foo", []string{"pods", "foo", "status"}},60 {"GET", "/api/v1/namespaces/other/pods/foo/proxy/subpath", "get", "api", "", "v1", "other", "pods", "proxy", "foo", []string{"pods", "foo", "proxy", "subpath"}},61 {"PUT", "/api/v1/namespaces/other/finalize", "update", "api", "", "v1", "other", "namespaces", "finalize", "other", []string{"namespaces", "other", "finalize"}},62 {"PUT", "/api/v1/namespaces/other/status", "update", "api", "", "v1", "other", "namespaces", "status", "other", []string{"namespaces", "other", "status"}},63 // verb identification64 {"PATCH", "/api/v1/namespaces/other/pods/foo", "patch", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},65 {"DELETE", "/api/v1/namespaces/other/pods/foo", "delete", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},66 {"POST", "/api/v1/namespaces/other/pods", "create", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},67 // deletecollection verb identification68 {"DELETE", "/api/v1/nodes", "deletecollection", "api", "", "v1", "", "nodes", "", "", []string{"nodes"}},69 {"DELETE", "/api/v1/namespaces", "deletecollection", "api", "", "v1", "", "namespaces", "", "", []string{"namespaces"}},70 {"DELETE", "/api/v1/namespaces/other/pods", "deletecollection", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},71 {"DELETE", "/apis/extensions/v1/namespaces/other/pods", "deletecollection", "api", "extensions", "v1", "other", "pods", "", "", []string{"pods"}},72 // api group identification73 {"POST", "/apis/extensions/v1/namespaces/other/pods", "create", "api", "extensions", "v1", "other", "pods", "", "", []string{"pods"}},74 // api version identification75 {"POST", "/apis/extensions/v1beta3/namespaces/other/pods", "create", "api", "extensions", "v1beta3", "other", "pods", "", "", []string{"pods"}},76 }77 resolver := newTestRequestInfoResolver()78 for _, successCase := range successCases {79 req, _ := http.NewRequest(successCase.method, successCase.url, nil)80 apiRequestInfo, err := resolver.NewRequestInfo(req)81 if err != nil {82 t.Errorf("Unexpected error for url: %s %v", successCase.url, err)83 }84 if !apiRequestInfo.IsResourceRequest {85 t.Errorf("Expected resource request")86 }87 if successCase.expectedVerb != apiRequestInfo.Verb {88 t.Errorf("Unexpected verb for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedVerb, apiRequestInfo.Verb)89 }90 if successCase.expectedAPIVersion != apiRequestInfo.APIVersion {91 t.Errorf("Unexpected apiVersion for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedAPIVersion, apiRequestInfo.APIVersion)92 }93 if successCase.expectedNamespace != apiRequestInfo.Namespace {94 t.Errorf("Unexpected namespace for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedNamespace, apiRequestInfo.Namespace)95 }96 if successCase.expectedResource != apiRequestInfo.Resource {97 t.Errorf("Unexpected resource for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedResource, apiRequestInfo.Resource)98 }99 if successCase.expectedSubresource != apiRequestInfo.Subresource {100 t.Errorf("Unexpected resource for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedSubresource, apiRequestInfo.Subresource)101 }102 if successCase.expectedName != apiRequestInfo.Name {103 t.Errorf("Unexpected name for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedName, apiRequestInfo.Name)104 }105 if !reflect.DeepEqual(successCase.expectedParts, apiRequestInfo.Parts) {106 t.Errorf("Unexpected parts for url: %s, expected: %v, actual: %v", successCase.url, successCase.expectedParts, apiRequestInfo.Parts)107 }108 }109 errorCases := map[string]string{110 "no resource path": "/",111 "just apiversion": "/api/version/",112 "just prefix, group, version": "/apis/group/version/",113 "apiversion with no resource": "/api/version/",114 "bad prefix": "/badprefix/version/resource",115 "missing api group": "/apis/version/resource",116 }117 for k, v := range errorCases {118 req, err := http.NewRequest("GET", v, nil)119 if err != nil {120 t.Errorf("Unexpected error %v", err)121 }122 apiRequestInfo, err := resolver.NewRequestInfo(req)123 if err != nil {124 t.Errorf("%s: Unexpected error %v", k, err)125 }126 if apiRequestInfo.IsResourceRequest {127 t.Errorf("%s: expected non-resource request", k)128 }129 }130}131func TestGetNonAPIRequestInfo(t *testing.T) {132 tests := map[string]struct {133 url string134 expected bool135 }{136 "simple groupless": {"/api/version/resource", true},137 "simple group": {"/apis/group/version/resource/name/subresource", true},138 "more steps": {"/api/version/resource/name/subresource", true},139 "group list": {"/apis/batch/v1/job", true},140 "group get": {"/apis/batch/v1/job/foo", true},141 "group subresource": {"/apis/batch/v1/job/foo/scale", true},142 "bad root": {"/not-api/version/resource", false},143 "group without enough steps": {"/apis/extensions/v1beta1", false},144 "group without enough steps 2": {"/apis/extensions/v1beta1/", false},145 "not enough steps": {"/api/version", false},...

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 v1.Get()4}5import "fmt"6func main() {7 v2.Get()8}9import "fmt"10func main() {11 v3.Get()12}13import "fmt"14func main() {15 v4.Get()16}17import "fmt"18func main() {19 v5.Get()20}21import "fmt"22func main() {23 v6.Get()24}25import "fmt"26func main() {27 v7.Get()28}29import "fmt"30func main() {31 v8.Get()32}33import "fmt"34func main() {35 v9.Get()36}37import "fmt"38func main() {39 v10.Get()40}41import "fmt"42func main() {43 v11.Get()44}45import "fmt"46func main() {47 v12.Get()48}

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(v1.Get())4}5import (6func main() {7 fmt.Println(v2.Get())8}9import (10func main() {11 fmt.Println(v3.Get())12}13import (14func main() {15 fmt.Println(v4.Get())16}17import (18func main() {19 fmt.Println(v5.Get())20}21import (22func main() {23 fmt.Println(v6.Get())24}25import (26func main() {27 fmt.Println(v7.Get())28}29import (30func main() {31 fmt.Println(v8.Get())32}33import (34func main() {35 fmt.Println(v9.Get())36}37import (

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 v1.Get()5}6func Get() string {7}8 /usr/local/Cellar/go/1.7/libexec/src/v1 (from $GOROOT)9 /Users/username/Documents/go/src/v1 (from $GOPATH)10import (11func main() {12 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {13 fmt.Fprintf(w, "Hello, %q", r.URL.Path)14 })15 http.ListenAndServe(":8080", nil)16}

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "v1"3func main() {4 fmt.Println(a.Get())5}6type A struct {}7func (a A) Get() int {8}9type A struct {}10func (a A) Get() int {11}12import "fmt"13import "v2"14func main() {15 fmt.Println(a.Get())16}17The import path of the package is the path of the package as seen by the

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 obj := v1.V1{}4 fmt.Println(obj.Get())5}6import "fmt"7type V1 struct{}8func (v V1) Get() string {9}10import (11func main() {12 obj := v1.V1{}13 fmt.Println(obj.Get())14}15import "fmt"16type V1 struct{}17func (v V1) Get() string {18}19import (20func main() {21 obj := v1.V1{}22 fmt.Println(obj.Get())23}24import "package-name"25import "v1"26We can also import the sub-package in the main package by

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 v := v1.New(3, 4)4 fmt.Println(v.Get())5}6type Vector struct {7}8func New(x, y int) *Vector {9 return &Vector{x, y}10}11func (v *Vector) Set(x, y int) {12}13import (14func main() {15 v := v1.New(3, 4)16 v.Set(5, 6)17 fmt.Println(v)18}19&{5 6}20type Vector struct {21}22func New(x, y int) *Vector {23 return &Vector{x, y}24}25func (v *Vector) Set(x, y int) {26}27func (v *Vector) Scale(i int) {28}29import (30func main() {31 v := v1.New(3, 4)32 v.Scale(5)33 fmt.Println(v)34}35&{15 20}36type Vector struct {37}38func New(x, y int) *Vector {39 return &Vector{x, y}40}41func (v *Vector) Set(x, y int) {42}43func (v *Vector) Scale(i int) {44}45func (v *Vector) Add(v1 *Vector) {46}47import (48func main() {49 v := v1.New(3, 4)50 v1 := v1.New(5, 6)51 v.Add(v1)52 fmt.Println(v)53}54&{8 10}55import "

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(v1.Get())4}5import (6func main() {7 fmt.Println(v2.Get())8}9Output: cannot use v2.Get() (type int) as type string in argument to fmt.Println10If you want to import the v2 package, you need to change the import path. You can use the same import path, but you need to change the path to the package. For example, if the path to the v2 package is github.com/username/test/v2 , you can import it in the v2 package with the following import path:11import "github.com/username/test/v2/v2"12If you want to use the v2 package in the v2 package, you need to change the import path to the v2 package. For example, if the path to the v2 package is github.com/username/test/v2 , you can use it in the v2 package with the following import path:13import "github.com/username/test/v2"14If you want to import the v2 package in the v2 package, you need to change the import path to the v2 package. For example, if the path to the v2 package is github.com/username/test/v2 , you can import it in the v2 package with the following import path:15import "github.com/username/test/v2/v2"16If you want to import the v2 package in the v2 package, you need to change the import path to the v2 package. For example, if the path to the v2 package is github.com/username/test/v2 ,

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 v1 := a.V1{10, 20}4 fmt.Println(v1.Get())5}6import (7func main() {8 v2 := a.V2{10, 20}9 fmt.Println(v2.Get())10}11import (12func main() {13 v3 := a.V3{10, 20}14 fmt.Println(v3.Get())15}16import (17func main() {18 v4 := a.V4{10, 20}19 fmt.Println(v4.Get())20}21import (22func main() {23 v5 := a.V5{10, 20}24 fmt.Println(v5.Get())25}26import (27func main() {28 v6 := a.V6{10, 20}29 fmt.Println(v6.Get())30}31import (32func main() {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful