How to use WithPrefix method of types Package

Best Ginkgo code snippet using types.WithPrefix

etcd_client.go

Source:etcd_client.go Github

copy

Full Screen

...150 if ec.etcdCli == nil {151 return errors.New("Etcd client is nil.")152 }153 if cluster != nil {154 rsp, err := ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/ClusterName", clientv3.WithPrefix())155 if err != nil {156 return err157 }158 for _, kv := range rsp.Kvs {159 cluster.ClusterName = string(kv.Value)160 }161 rsp, err = ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/Expect", clientv3.WithPrefix())162 if err != nil {163 return err164 }165 for _, kv := range rsp.Kvs {166 if state, err := strconv.Atoi(string(kv.Value)); err == nil {167 cluster.Expect = clr.ExpectStatus(state)168 } else {169 return err170 }171 }172 rsp, err = ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/Network", clientv3.WithPrefix())173 if err != nil {174 return err175 }176 for _, kv := range rsp.Kvs {177 cluster.Network = string(kv.Value)178 }179 rsp, err = ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/certs", clientv3.WithPrefix())180 if err != nil {181 return err182 }183 for _, kv := range rsp.Kvs {184 json.Unmarshal(kv.Value, &cluster.certs)185 }186 rsp, err = ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/tokens", clientv3.WithPrefix())187 if err != nil {188 return err189 }190 for _, kv := range rsp.Kvs {191 json.Unmarshal(kv.Value, &cluster.tokens)192 }193 //rsp, err = ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/Ingresses", clientv3.WithPrefix())194 rsp, err = ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/Ingress", clientv3.WithPrefix())195 if err != nil {196 return err197 }198 for _, kv := range rsp.Kvs {199 json.Unmarshal(kv.Value, &cluster.Ingress)200 }201 ec.FetchConf(cluster)202 rsp, err = ec.etcdCli.Get(context.Background(), ec.getNodesPath(), clientv3.WithPrefix(), clientv3.WithKeysOnly())203 if err != nil {204 return err205 }206 keys := types.NewUnsafeSet()207 for _, kv := range rsp.Kvs {208 keySplits := strings.Split(strings.TrimPrefix(string(kv.Key), ec.getNodesPath()), "/")209 keys.Add(keySplits[1])210 }211 for _, nodeName := range keys.Values() {212 node := &KubeNode{213 Name: nodeName,214 cluster: cluster,215 }216 ec.FetchKubenode(node)217 cluster.AddNodeToSlice(node)218 }219 ec.FetchSharedata(cluster.shareData, cluster.KubeNodes)220 }221 return nil222}223func (ec *EtcdClient) DeleteCluster(cluster *Cluster) error {224 if ec.etcdCli == nil {225 return errors.New("Etcd client is nil.")226 }227 if cluster != nil {228 if _, err := ec.etcdCli.Delete(context.Background(), ec.getClusterPath(), clientv3.WithPrefix()); err != nil {229 return err230 }231 }232 return nil233}234//StoreSharedata add and update share data of cluster235func (ec *EtcdClient) StoreSharedata(shareData *ShareData) error {236 wg := new(sync.WaitGroup)237 err := ec._storeSharedata(context.Background(), wg, shareData)238 wg.Wait()239 return err240}241func (ec *EtcdClient) _storeSharedata(ctx context.Context, wg *sync.WaitGroup, shareData *ShareData) error {242 masterIps, err := json.Marshal(shareData.masterIPs.Values())243 if err != nil {244 log.Errorf("json Marshal error: %+v", err.Error())245 }246 ec.goPutEtcdExec(ctx, wg, ec.getClusterPath()+"/sharedata/masterips", string(masterIps))247 nodeIps, err := json.Marshal(shareData.nodeIps.Values())248 if err != nil {249 log.Errorf("json Marshal error: %+v", err.Error())250 }251 ec.goPutEtcdExec(ctx, wg, ec.getClusterPath()+"/sharedata/nodeips", string(nodeIps))252 ec.goPutEtcdExec(ctx, wg, ec.getClusterPath()+"/sharedata/etcdserver", shareData.etcdServer.String())253 return nil254}255func (ec *EtcdClient) FetchSharedata(shareData *ShareData, nodes []*KubeNode) error {256 if ec.etcdCli == nil {257 return nil258 }259 rsp, err := ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/sharedata/masterips", clientv3.WithPrefix())260 if err != nil {261 return err262 }263 var masterIpsValue []string264 for _, kv := range rsp.Kvs {265 json.Unmarshal(kv.Value, &masterIpsValue)266 }267 shareData.masterIPs = types.NewUnsafeSet(masterIpsValue...)268 rsp, err = ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/sharedata/nodeips", clientv3.WithPrefix())269 if err != nil {270 return err271 }272 var nodeIpsValue []string273 for _, kv := range rsp.Kvs {274 json.Unmarshal(kv.Value, &nodeIpsValue)275 }276 shareData.nodeIps = types.NewUnsafeSet(nodeIpsValue...)277 rsp, err = ec.etcdCli.Get(context.Background(), ec.getClusterPath()+"/sharedata/etcdserver", clientv3.WithPrefix())278 if err != nil {279 return err280 }281 for _, kv := range rsp.Kvs {282 shareData.etcdServer = bytes.NewBuffer(kv.Value)283 }284 for _, node := range nodes {285 for _, process := range node.Processes {286 if process.Type == Process_MASTERHC {287 shareData.masterWithHc = node288 break289 }290 }291 if shareData.masterWithHc != nil {292 break293 }294 }295 return nil296}297func (ec *EtcdClient) StoreConf(cluster *Cluster) error {298 wg := new(sync.WaitGroup)299 err := ec._storeConf(context.Background(), wg, cluster.Conf)300 wg.Wait()301 return err302}303func (ec *EtcdClient) _storeConf(ctx context.Context, wg *sync.WaitGroup, ckeConf *conf.CKEConf) error {304 var confPath string305 confPath = ec.getClusterPath() + "/Conf"306 confBytes, err := yaml.Marshal(ckeConf)307 if err != nil {308 log.Errorf("yaml Marshal error: %+v", err.Error())309 }310 ec.goPutEtcdExec(ctx, wg, confPath, string(confBytes))311 return nil312}313func (ec *EtcdClient) FetchConf(cluster *Cluster) error {314 var confPath string315 confPath = ec.getClusterPath() + "/Conf"316 rs, err := ec.etcdCli.Get(context.Background(), confPath, clientv3.WithPrefix())317 if err != nil {318 return err319 }320 cluster.Conf = &conf.CKEConf{}321 for _, kv := range rs.Kvs {322 yaml.Unmarshal(kv.Value, &cluster.Conf)323 }324 //设置端口325 cluster.gottyPort = *cluster.Conf.GetVariable("GOTTY_PORT")326 cluster.apiServerProxyPort = *cluster.Conf.GetVariable("API_PROXY_PORT")327 cluster.dashBoardProxyPort = *cluster.Conf.GetVariable("DASH_PROXY_PORT")328 cluster.gatewayManagePort = *cluster.Conf.GetVariable("MANAGE_PORT")329 return nil330}331//StoreKubeNode add and update kubenode332func (ec *EtcdClient) StoreKubeNode(node *KubeNode) error {333 if ec.etcdCli == nil {334 return errors.New("Etcd client is nil.")335 }336 wg := new(sync.WaitGroup)337 err := ec._storeKubeNode(context.Background(), wg, node)338 wg.Wait()339 return err340}341func (ec *EtcdClient) _storeKubeNode(ctx context.Context, wg *sync.WaitGroup, node *KubeNode) error {342 nodePath := ec.getNodePath(node)343 ec.goPutEtcdExec(ctx, wg, nodePath+"/Name", node.Name)344 ec.goPutEtcdExec(ctx, wg, nodePath+"/Type", string(node.Type))345 ec.goPutEtcdExec(ctx, wg, nodePath+"/Host", node.Host)346 if len(node.RealHost) > 0 {347 ec.goPutEtcdExec(ctx, wg, nodePath+"/RealHost", node.RealHost)348 }349 ec.goPutEtcdExec(ctx, wg, nodePath+"/NodeIP", node.NodeIP)350 ec.goPutEtcdExec(ctx, wg, nodePath+"/NodeID", node.NodeID)351 //ingresses, err := json.Marshal(node.Ingresses)352 ingress, err := json.Marshal(node.Ingress)353 if err != nil {354 log.Errorf("json Marshal error: %+v", err.Error())355 }356 //ec.goPutEtcdExec(ctx, wg, nodePath+"/Ingresses", string(ingresses))357 ec.goPutEtcdExec(ctx, wg, nodePath+"/Ingress", string(ingress))358 ec.goPutEtcdExec(ctx, wg, nodePath+"/Expect", strconv.Itoa(int(node.Expect)))359 for _, pro := range node.Processes {360 ec._storeProcess(ctx, wg, node, pro)361 }362 //存储reservation信息363 ec._storeRervation(ctx, wg, node, node.Reservation)364 ec._storeTask(ctx, wg, node, nil, node.Task)365 return nil366}367func (ec *EtcdClient) FetchKubenode(node *KubeNode) error {368 if ec.etcdCli == nil {369 return nil370 }371 nodePath := ec.getNodePath(node)372 rs, err := ec.etcdCli.Get(context.Background(), nodePath+"/Name", clientv3.WithPrefix())373 if err != nil {374 return err375 }376 for _, kv := range rs.Kvs {377 node.Name = string(kv.Value)378 }379 rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/Type", clientv3.WithPrefix())380 if err != nil {381 return err382 }383 for _, kv := range rs.Kvs {384 node.Type = KubeNodeType(kv.Value)385 }386 rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/Host", clientv3.WithPrefix())387 if err != nil {388 return err389 }390 for _, kv := range rs.Kvs {391 node.Host = string(kv.Value)392 }393 rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/RealHost", clientv3.WithPrefix())394 if err != nil {395 return err396 }397 for _, kv := range rs.Kvs {398 node.RealHost = string(kv.Value)399 }400 rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/NodeIP", clientv3.WithPrefix())401 if err != nil {402 return err403 }404 for _, kv := range rs.Kvs {405 node.NodeIP = string(kv.Value)406 }407 rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/NodeID", clientv3.WithPrefix())408 if err != nil {409 return err410 }411 for _, kv := range rs.Kvs {412 node.NodeID = string(kv.Value)413 }414 //rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/Ingresses", clientv3.WithPrefix())415 rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/Ingress", clientv3.WithPrefix())416 if err != nil {417 return err418 }419 for _, kv := range rs.Kvs {420 //json.Unmarshal(kv.Value, &node.Ingresses)421 json.Unmarshal(kv.Value, &node.Ingress)422 }423 rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/Expect", clientv3.WithPrefix())424 if err != nil {425 return err426 }427 for _, kv := range rs.Kvs {428 if state, err := strconv.Atoi(string(kv.Value)); err == nil {429 node.Expect = clr.ExpectStatus(state)430 } else {431 return err432 }433 }434 //设置node conf435 node.Conf = node.cluster.Conf.GetNodeConf(string(node.Type))436 //获取预留信息437 ec.FetchReservation(node)438 rs, err = ec.etcdCli.Get(context.Background(), nodePath+"/Processes", clientv3.WithPrefix())439 if err != nil {440 return err441 }442 keys := types.NewUnsafeSet()443 for _, kv := range rs.Kvs {444 keySplits := strings.Split(strings.TrimPrefix(string(kv.Key), nodePath+"/Processes"), "/")445 keys.Add(keySplits[1])446 }447 node.Processes = make([]*Process, 0)448 for _, proName := range keys.Values() {449 process := &Process{450 Name: proName,451 }452 err = ec.FetchProcess(node, process)453 if err != nil {454 return err455 }456 node.Processes = append(node.Processes, process)457 }458 node.Task = &cluster.Task{}459 if err = ec.FetchTask(node, nil, node.Task); err != nil {460 return err461 }462 return nil463}464func (ec *EtcdClient) DeleteKubenode(node *KubeNode) error {465 if ec.etcdCli == nil {466 return errors.New("Etcd client is nil.")467 }468 if _, err := ec.etcdCli.Delete(context.Background(), ec.getNodePath(node), clientv3.WithPrefix()); err != nil {469 log.Error("Deleted node error: ", err.Error())470 return err471 }472 log.Debug("Deleted node " + node.Name + "from storage.")473 return nil474}475func (ec *EtcdClient) StoreProcess(node *KubeNode, process *Process) error {476 wg := new(sync.WaitGroup)477 err := ec._storeProcess(context.Background(), wg, node, process)478 wg.Wait()479 return err480}481func (ec *EtcdClient) _storeProcess(ctx context.Context, wg *sync.WaitGroup, node *KubeNode, process *Process) error {482 processPath := ec.getProcessPath(node, process)483 ec.goPutEtcdExec(ctx, wg, processPath+"/Name", process.Name)484 ec.goPutEtcdExec(ctx, wg, processPath+"/Type", string(process.Type))485 //保存Resource信息486 pres, err := json.Marshal(process.Res)487 if err != nil {488 log.Errorf("json Marshal error: %+v", err.Error())489 }490 ec.goPutEtcdExec(ctx, wg, processPath+"/Res", string(pres))491 poption, err := json.Marshal(process.Options)492 if err != nil {493 log.Errorf("json Marshal error: %+v", err.Error())494 }495 ec.goPutEtcdExec(ctx, wg, processPath+"/Options", string(poption))496 ec.goPutEtcdExec(ctx, wg, processPath+"/Cmd", process.Cmd)497 pconfigjson, err := json.Marshal(process.ConfigJSON)498 if err != nil {499 log.Errorf("json Marshal error: %+v", err.Error())500 }501 ec.goPutEtcdExec(ctx, wg, processPath+"/ConfigJson", string(pconfigjson))502 ec.goPutEtcdExec(ctx, wg, processPath+"/Expect", strconv.Itoa(process.Expect.Int()) )503 ec._storeTask(ctx, wg, node, process, process.Task)504 return nil505}506func (ec *EtcdClient) FetchProcess(node *KubeNode, process *Process) error {507 if ec.etcdCli == nil {508 return errors.New("Etcd client is nil.")509 }510 processPath := ec.getProcessPath(node, process)511 rs, err := ec.etcdCli.Get(context.Background(), processPath+"/Name", clientv3.WithPrefix())512 if err != nil {513 return err514 }515 for _, kv := range rs.Kvs {516 process.Name = string(kv.Value)517 }518 rs, err = ec.etcdCli.Get(context.Background(), processPath+"/Type", clientv3.WithPrefix())519 if err != nil {520 return err521 }522 for _, kv := range rs.Kvs {523 process.Type = ProcessType(kv.Value)524 }525 rs, err = ec.etcdCli.Get(context.Background(), processPath+"/Res", clientv3.WithPrefix())526 if err != nil {527 return err528 }529 for _, kv := range rs.Kvs {530 json.Unmarshal(kv.Value, &process.Res)531 }532 rs, err = ec.etcdCli.Get(context.Background(), processPath+"/Options", clientv3.WithPrefix())533 if err != nil {534 return err535 }536 for _, kv := range rs.Kvs {537 process.Options = []string{}538 json.Unmarshal(kv.Value, &process.Options)539 }540 rs, err = ec.etcdCli.Get(context.Background(), processPath+"/Cmd", clientv3.WithPrefix())541 if err != nil {542 return err543 }544 for _, kv := range rs.Kvs {545 process.Cmd = string(kv.Value)546 }547 rs, err = ec.etcdCli.Get(context.Background(), processPath+"/ConfigJson", clientv3.WithPrefix())548 if err != nil {549 return err550 }551 for _, kv := range rs.Kvs {552 json.Unmarshal(kv.Value, &process.ConfigJSON)553 }554 rs, err = ec.etcdCli.Get(context.Background(), processPath+"/Expect", clientv3.WithPrefix())555 if err != nil {556 return err557 }558 for _, kv := range rs.Kvs {559 expect, err := strconv.Atoi(string(kv.Value))560 if err != nil {561 return err562 }563 process.Expect = clr.ExpectStatus(expect)564 }565 process.Task = &cluster.Task{}566 ec.FetchTask(node, process, process.Task)567 return nil568}569func (ec *EtcdClient) StoreTask(node *KubeNode, process *Process, task *cluster.Task) error {570 wg := new(sync.WaitGroup)571 err := ec._storeTask(context.Background(), wg, node, process, task)572 wg.Wait()573 return err574}575func (ec *EtcdClient) _storeTask(ctx context.Context, wg *sync.WaitGroup, node *KubeNode, process *Process, task *cluster.Task) error {576 //store task Info and Status 存储任务的status577 //针对kube node中的wrapper task578 var taskPath string579 if process == nil {580 taskPath = ec.getNodePath(node) + "/Task"581 } else {582 taskPath = ec.getProcessPath(node, process) + "/Task"583 }584 taskInfoPath := taskPath + "/Info"585 taskStatusPath := taskPath + "/Status"586 //info587 ec.goPutEtcdExec(context.Background(), wg, taskInfoPath+"/Name", task.Info.Name)588 ec.goPutEtcdExec(context.Background(), wg, taskInfoPath+"/Type", task.Info.Type)589 if task.Info.Host != nil {590 ec.goPutEtcdExec(context.Background(), wg, taskInfoPath+"/Host", *task.Info.Host)591 }592 k8sTask, ok := task.Info.Body.(*kubernetes.K8STask)593 if !ok {594 log.Error("TaskInfo Body is not a K8STask")595 } else {596 taskBytes, err := proto.Marshal(k8sTask)597 if err != nil {598 log.Errorf("json Marshal error: %+v", err.Error())599 } else {600 ec.goPutEtcdExec(context.Background(), wg, taskInfoPath+"/Info", string(taskBytes))601 }602 }603 taskInfoRes, err := json.Marshal(task.Info.Res)604 if err != nil {605 log.Errorf("json Marshal error: %+v", err.Error())606 }607 ec.goPutEtcdExec(context.Background(), wg, taskInfoPath+"/Res", string(taskInfoRes))608 taskInfoExecutor, err := json.Marshal(task.Info.Executor)609 if err != nil {610 log.Errorf("json Marshal error: %+v", err.Error())611 }612 ec.goPutEtcdExec(context.Background(), wg, taskInfoPath+"/Executor", string(taskInfoExecutor))613 taskInfoState, err := json.Marshal(task.Info.State)614 if err != nil {615 log.Errorf("json Marshal error: %+v", err.Error())616 }617 ec.goPutEtcdExec(context.Background(), wg, taskInfoPath+"/State", string(taskInfoState))618 //status619 taskStatus, err := json.Marshal(task.Status)620 if err != nil {621 log.Errorf("json Marshal error: %+v", err.Error())622 }623 ec.goPutEtcdExec(context.Background(), wg, taskStatusPath, string(taskStatus))624 return nil625}626func (ec *EtcdClient) FetchTask(node *KubeNode, process *Process, task *cluster.Task) error {627 //fetch task Info and Status 读取任务的status628 var taskPath string629 if process == nil {630 taskPath = ec.getNodePath(node) + "/Task"631 } else {632 taskPath = ec.getProcessPath(node, process) + "/Task"633 }634 taskInfoPath := taskPath + "/Info"635 taskStatusPath := taskPath + "/Status"636 //info637 task.Info = &cluster.TaskInfo{638 Reservation: node.Reservation,639 }640 rs, err := ec.etcdCli.Get(context.Background(), taskInfoPath+"/Name", clientv3.WithPrefix())641 if err != nil {642 return err643 }644 for _, kv := range rs.Kvs {645 task.Info.Name = string(kv.Value)646 }647 rs, err = ec.etcdCli.Get(context.Background(), taskInfoPath+"/Type", clientv3.WithPrefix())648 if err != nil {649 return err650 }651 for _, kv := range rs.Kvs {652 task.Info.Type = string(kv.Value)653 }654 rs, err = ec.etcdCli.Get(context.Background(), taskInfoPath+"/Host", clientv3.WithPrefix())655 if err != nil {656 return err657 }658 for _, kv := range rs.Kvs {659 str := string(kv.Value)660 task.Info.Host = &str661 }662 rs, err = ec.etcdCli.Get(context.Background(), taskInfoPath+"/Info", clientv3.WithPrefix())663 if err != nil {664 return err665 }666 for _, kv := range rs.Kvs {667 k8sTask := &kubernetes.K8STask{}668 err := proto.Unmarshal(kv.Value, k8sTask)669 if err != nil {670 return err671 }672 task.Info.Body = k8sTask673 }674 rs, err = ec.etcdCli.Get(context.Background(), taskInfoPath+"/Res", clientv3.WithPrefix())675 if err != nil {676 return err677 }678 for _, kv := range rs.Kvs {679 json.Unmarshal(kv.Value, &task.Info.Res)680 }681 rs, err = ec.etcdCli.Get(context.Background(), taskInfoPath+"/Executor", clientv3.WithPrefix())682 if err != nil {683 return err684 }685 for _, kv := range rs.Kvs {686 json.Unmarshal(kv.Value, &task.Info.Executor)687 }688 rs, err = ec.etcdCli.Get(context.Background(), taskInfoPath+"/State", clientv3.WithPrefix())689 if err != nil {690 return err691 }692 for _, kv := range rs.Kvs {693 json.Unmarshal(kv.Value, &task.Info.State)694 }695 //status696 task.Status = &cluster.TaskStatus{}697 rs, err = ec.etcdCli.Get(context.Background(), taskStatusPath, clientv3.WithPrefix())698 if err != nil {699 return err700 }701 for _, kv := range rs.Kvs {702 json.Unmarshal(kv.Value, &task.Status)703 }704 return nil705}706func (ec *EtcdClient) StoreReservation(node *KubeNode, reservation *clr.Reservation) error {707 wg := new(sync.WaitGroup)708 err := ec._storeRervation(context.Background(), wg, node, reservation)709 wg.Wait()710 return err711}712func (ec *EtcdClient) _storeRervation(ctx context.Context, wg *sync.WaitGroup, node *KubeNode, reservation *clr.Reservation) error {713 var reservationPath string714 reservationPath = ec.getNodePath(node) + "/Reservation"715 reservBytes, err := json.Marshal(reservation)716 if err != nil {717 log.Errorf("json Marshal error: %+v", err.Error())718 }719 ec.goPutEtcdExec(ctx, wg, reservationPath, string(reservBytes))720 for _, pro := range node.Processes {721 ec._storeProcess(ctx, wg, node, pro)722 }723 return nil724}725func (ec *EtcdClient) FetchReservation(node *KubeNode) error {726 var reservationPath string727 reservationPath = ec.getNodePath(node) + "/Reservation"728 rs, err := ec.etcdCli.Get(context.Background(), reservationPath, clientv3.WithPrefix())729 if err != nil {730 return err731 }732 node.Reservation = &clr.Reservation{}733 for _, kv := range rs.Kvs {734 json.Unmarshal(kv.Value, &node.Reservation)735 }736 node.Reservation.GetUsedResource = node.getUsedResource737 return nil738}...

Full Screen

Full Screen

store.go

Source:store.go Github

copy

Full Screen

...71}72func (s *FusisStore) Watch() {73 ticker := time.Tick(1 * time.Second)74 notify := false75 svcCh := s.kv.Watch(context.TODO(), s.key("services"), clientv3.WithPrefix())76 dstCh := s.kv.Watch(context.TODO(), s.key("destinations"), clientv3.WithPrefix())77 for {78 select {79 case <-svcCh:80 notify = true81 case <-dstCh:82 notify = true83 case <-ticker:84 if !notify {85 continue86 }87 notify = false88 fstate, err := s.GetState()89 if err != nil {90 logrus.Error(errors.Wrap(err, "[store] couldn't get state"))91 }92 for _, ch := range s.watchChannels {93 ch <- fstate94 }95 }96 }97}98func (s *FusisStore) GetState() (state.State, error) {99 fstate, _ := state.New()100 opts := append([]clientv3.OpOption{}, clientv3.WithPrefix(), clientv3.WithSort(clientv3.SortByKey, clientv3.SortDescend))101 svcGet := clientv3.OpGet(s.key("services"), opts...)102 dstGet := clientv3.OpGet(s.key("destinations"), opts...)103 checkGet := clientv3.OpGet(s.key("checks"), opts...)104 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)105 resp, err := s.kv.Txn(ctx).Then(svcGet, dstGet, checkGet).Commit()106 cancel()107 if err != nil {108 return nil, errors.Wrap(err, "[store] Get data from etcd failed")109 }110 for _, r := range resp.Responses {111 for _, pair := range r.GetResponseRange().Kvs {112 key := string(pair.Key)113 switch {114 case strings.Contains(key, s.key("services")):115 svc := types.Service{}116 if err := json.Unmarshal(pair.Value, &svc); err != nil {117 return nil, errors.Wrapf(err, "[store] Unmarshal %s failed", pair.Value)118 }119 fstate.AddService(svc)120 case strings.Contains(key, s.key("destinations")):121 dst := types.Destination{}122 if err := json.Unmarshal(pair.Value, &dst); err != nil {123 return nil, errors.Wrapf(err, "[store] Unmarshal %s failed", pair.Value)124 }125 fstate.AddDestination(dst)126 case strings.Contains(key, s.key("checks")):127 spec := types.CheckSpec{}128 if err := json.Unmarshal(pair.Value, &spec); err != nil {129 return nil, errors.Wrapf(err, "[store] Unmarshal %s failed", pair.Value)130 }131 fstate.AddCheck(spec)132 }133 }134 }135 return fstate, nil136}137func (s *FusisStore) GetServices() ([]types.Service, error) {138 svcs := []types.Service{}139 resp, err := s.kv.Get(context.TODO(), s.key("services"), clientv3.WithPrefix())140 if err != nil {141 return svcs, errors.Wrap(err, "[store] Get services failed")142 }143 for _, pair := range resp.Kvs {144 svc := types.Service{}145 if err := json.Unmarshal(pair.Value, &svc); err != nil {146 return svcs, errors.Wrapf(err, "[store] Unmarshal %s failed", pair.Value)147 }148 svcs = append(svcs, svc)149 }150 return svcs, nil151}152func (s *FusisStore) GetService(name string) (*types.Service, error) {153 resp, err := s.kv.Get(context.TODO(), s.key("services", name), clientv3.WithPrefix())154 if err != nil {155 return nil, errors.Wrap(err, "[store] Get services failed")156 }157 if len(resp.Kvs) == 0 {158 return nil, types.ErrServiceNotFound159 }160 kv := resp.Kvs[0]161 svc := &types.Service{}162 if err := json.Unmarshal(kv.Value, &svc); err != nil {163 return nil, errors.Wrapf(err, "[store] unmarshal %s failed", kv.Value)164 }165 return svc, nil166}167func (s *FusisStore) GetDestinations(svc *types.Service) ([]types.Destination, error) {168 dsts := []types.Destination{}169 resp, err := s.kv.Get(context.TODO(), s.key("destinations", svc.GetId()), clientv3.WithPrefix())170 if err != nil {171 return dsts, errors.Wrap(err, "[store] Get destinations failed")172 }173 for _, pair := range resp.Kvs {174 dst := types.Destination{}175 if err := json.Unmarshal(pair.Value, &dst); err != nil {176 return dsts, errors.Wrapf(err, "[store] Unmarshal %s failed", pair.Value)177 }178 dsts = append(dsts, dst)179 }180 return dsts, nil181}182//183// AddService adds a new services to store. It validates the name184// uniqueness and the IPVS uniqueness by saving the IPVS key185// in the store, which consists in a combination of address, port186// and protocol.187func (s *FusisStore) AddService(svc *types.Service) error {188 svcKey := s.key("services", svc.GetId())189 ipvsKey := s.key("ipvs-ids", "services", svc.IpvsId())190 // Validating service191 if err := s.validateService(svc); err != nil {192 return err193 }194 value, err := json.Marshal(svc)195 if err != nil {196 return errors.Wrapf(err, "[store] Error marshaling service: %v", svc)197 }198 svcCmp := notFound(svcKey)199 ipvsCmp := notFound(ipvsKey)200 svcPut := clientv3.OpPut(svcKey, string(value))201 ipvsPut := clientv3.OpPut(ipvsKey, "true")202 resp, err := s.kv.Txn(context.TODO()).203 If(svcCmp, ipvsCmp).204 Then(svcPut, ipvsPut).205 Commit()206 if err != nil {207 return errors.Wrapf(err, "[store] Error sending service to Etcd: %v", svc)208 }209 // resp.Succeeded means the compare clause was true210 if resp.Succeeded == false {211 return types.ErrValidation{Type: "service", Errors: map[string]string{"ipvs": "service must be unique"}}212 }213 return nil214}215func (s *FusisStore) DeleteService(svc *types.Service) error {216 // Deleting service217 svcKey := s.key("services", svc.GetId())218 ipvsSvcKey := s.key("ipvs-ids", "services", svc.IpvsId())219 svcDel := clientv3.OpDelete(svcKey, clientv3.WithPrefix())220 ipvsSvcDel := clientv3.OpDelete(ipvsSvcKey, clientv3.WithPrefix())221 svcCmp := clientv3.Compare(clientv3.ModRevision(svcKey), ">", 0)222 ipvsSvcCmp := clientv3.Compare(clientv3.ModRevision(ipvsSvcKey), ">", 0)223 // Deleting destinations224 dstKey := s.key("destinations", svc.GetId())225 ipvsDstKey := s.key("ipvs-ids", "destinations", svc.GetId())226 dstDel := clientv3.OpDelete(dstKey, clientv3.WithPrefix())227 ipvsDstDel := clientv3.OpDelete(ipvsDstKey, clientv3.WithPrefix())228 resp, err := s.kv.Txn(context.TODO()).229 If(svcCmp, ipvsSvcCmp).230 Then(svcDel, ipvsSvcDel, dstDel, ipvsDstDel).231 Commit()232 if err != nil {233 return errors.Wrapf(err, "[store] Error deleting service from Etcd: %v", svc)234 }235 if resp.Succeeded == false {236 return types.ErrServiceNotFound237 }238 return nil239}240func (s *FusisStore) AddDestination(svc *types.Service, dst *types.Destination) error {241 dstKey := s.key("destinations", svc.GetId(), dst.GetId())242 ipvsKey := s.key("ipvs-ids", "destinations", svc.GetId(), dst.IpvsId())243 // Validating destination244 if err := s.validateDestination(dst); err != nil {245 return err246 }247 // Persisting destination248 value, err := json.Marshal(dst)249 if err != nil {250 return errors.Wrapf(err, "[store] error marshaling destination: %v", dst)251 }252 dstCmp := notFound(dstKey)253 ipvsCmp := notFound(ipvsKey)254 dstPut := clientv3.OpPut(dstKey, string(value))255 ipvsPut := clientv3.OpPut(ipvsKey, "true")256 resp, err := s.kv.Txn(context.TODO()).257 If(dstCmp, ipvsCmp).258 Then(dstPut, ipvsPut).259 Commit()260 if err != nil {261 return errors.Wrapf(err, "[store] Error sending destination to Etcd: %v", svc)262 }263 // resp.Succeeded means the compare clause was true264 if resp.Succeeded == false {265 return types.ErrValidation{Type: "destination", Errors: map[string]string{"ipvs": "destination must be unique"}}266 }267 return nil268}269func (s *FusisStore) DeleteDestination(svc *types.Service, dst *types.Destination) error {270 dstKey := s.key("destinations", svc.GetId(), dst.GetId())271 ipvsKey := s.key("ipvs-ids", "destinations", svc.GetId(), dst.IpvsId())272 dstDel := clientv3.OpDelete(dstKey, clientv3.WithPrefix())273 ipvsDel := clientv3.OpDelete(ipvsKey, clientv3.WithPrefix())274 dstCmp := notFound(dstKey)275 ipvsCmp := notFound(ipvsKey)276 resp, err := s.kv.Txn(context.TODO()).277 If(dstCmp, ipvsCmp).278 Else(dstDel, ipvsDel).279 Commit()280 if err != nil {281 return errors.Wrapf(err, "[store] Error deleting destination from Etcd: %v", svc)282 }283 // resp.Succeeded means the compare clause was true284 if resp.Succeeded {285 return types.ErrDestinationNotFound286 }287 return nil288}289func (s *FusisStore) AddCheck(spec types.CheckSpec) error {290 checkKey := s.key("checks", spec.ServiceID)291 // Persisting destination292 value, err := json.Marshal(spec)293 if err != nil {294 return errors.Wrapf(err, "[store] error marshaling spec: %#v", spec)295 }296 _, err = s.kv.Put(context.TODO(), checkKey, string(value))297 if err != nil {298 return errors.Wrapf(err, "[store] Error sending check to Etcd: %#v", spec)299 }300 return nil301}302func (s *FusisStore) GetCheck(serviceID string) (*types.CheckSpec, error) {303 checkKey := s.key("checks", serviceID)304 resp, err := s.kv.Get(context.TODO(), checkKey, clientv3.WithPrefix())305 if err != nil {306 return nil, errors.Wrapf(err, "[store] Error getting check from Etcd: %#v", checkKey)307 }308 if len(resp.Kvs) == 0 {309 return nil, types.ErrCheckNotFound310 }311 kv := resp.Kvs[0]312 check := &types.CheckSpec{}313 if err := json.Unmarshal(kv.Value, &check); err != nil {314 return nil, errors.Wrapf(err, "[store] unmarshal %s failed", kv.Value)315 }316 return check, nil317}318func (s *FusisStore) DeleteCheck(spec types.CheckSpec) error {...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

1package main2import (3 "context"4 "net/http"5 "path/filepath"6 "time"7 "github.com/Ptt-official-app/go-openbbsmiddleware/api"8 "github.com/Ptt-official-app/go-openbbsmiddleware/cron"9 "github.com/Ptt-official-app/go-openbbsmiddleware/queue"10 "github.com/Ptt-official-app/go-openbbsmiddleware/types"11 "github.com/appleboy/graceful"12 "github.com/gin-gonic/gin"13 log "github.com/sirupsen/logrus"14)15func withPrefix(path string) string {16 return types.API_PREFIX + path17}18func initGin() (*gin.Engine, error) {19 router := gin.Default()20 // options21 router.OPTIONS("/*path", api.OptionsWrapper)22 // index23 router.GET(withPrefix(api.INDEX_R), api.IndexWrapper)24 router.GET(withPrefix(api.GET_USER_VISIT_COUNT_R), api.GetUserVisitCountWrapper)25 router.GET(withPrefix(api.GET_VERSION_R), api.GetVersionWrapper)26 // register/login27 router.POST(withPrefix(api.REGISTER_CLIENT_R), api.RegisterClientWrapper)28 router.POST(withPrefix(api.REGISTER_USER_R), api.RegisterUserWrapper)29 router.POST(withPrefix(api.LOGIN_R), api.LoginWrapper)30 router.POST(withPrefix(api.ATTEMPT_REGISTER_USER_R), api.AttemptRegisterUserWrapper)31 router.POST(withPrefix(api.CHECK_EXISTS_USER_R), api.CheckExistsUserWrapper)32 router.POST(withPrefix(api.LOGOUT_R), api.LogoutWrapper)33 // board34 router.GET(withPrefix(api.LOAD_GENERAL_BOARDS_R), api.LoadGeneralBoardsWrapper)35 router.GET(withPrefix(api.GET_BOARD_DETAIL_R), api.GetBoardDetailWrapper)36 router.GET(withPrefix(api.GET_BOARD_SUMMARY_R), api.GetBoardSummaryWrapper)37 router.GET(withPrefix(api.LOAD_POPULAR_BOARDS_R), api.LoadPopularBoardsWrapper)38 router.GET(withPrefix(api.LOAD_GENERAL_BOARDS_BY_CLASS_R), api.LoadGeneralBoardsByClassWrapper)39 router.GET(withPrefix(api.LOAD_AUTO_COMPLETE_BOARDS_R), api.LoadAutoCompleteBoardsWrapper)40 router.POST(withPrefix(api.CREATE_BOARD_R), api.CreateBoardWrapper)41 router.GET(withPrefix(api.LOAD_CLASS_BOARDS_R), api.LoadClassBoardsWrapper)42 // article43 router.GET(withPrefix(api.LOAD_GENERAL_ARTICLES_R), api.LoadGeneralArticlesWrapper)44 router.GET(withPrefix(api.LOAD_BOTTOM_ARTICLES_R), api.LoadBottomArticlesWrapper)45 router.GET(withPrefix(api.GET_ARTICLE_R), api.GetArticleDetailWrapper)46 router.GET(withPrefix(api.GET_ARTICLE_BLOCKS_R), api.GetArticleBlocksWrapper)47 router.GET(withPrefix(api.LOAD_POPULAR_ARTICLES_R), api.LoadPopularArticlesWrapper)48 router.POST(withPrefix(api.CREATE_ARTICLE_R), api.CreateArticleWrapper)49 router.GET(withPrefix(api.CROSS_POST_R), api.CrossPostWrapper)50 router.POST(withPrefix(api.EDIT_ARTICLE_R), api.EditArticleDetailWrapper)51 router.POST(withPrefix(api.REPLY_COMMENTS_R), api.ReplyCommentsWrapper)52 router.POST(withPrefix(api.DELETE_COMMENTS_R), api.DeleteCommentsWrapper)53 router.POST(withPrefix(api.DELETE_ARTICLES_R), api.DeleteArticlesWrapper)54 // manual55 router.GET(withPrefix(api.LOAD_MAN_ARTICLES_R), api.LoadManArticlesWrapper)56 router.GET(withPrefix(api.GET_MAN_ARTICLE_R), api.GetManArticleDetailWrapper)57 router.GET(withPrefix(api.GET_MAN_ARTICLE_BLOCKS_R), api.GetManArticleBlocksWrapper)58 // user59 router.GET(withPrefix(api.GET_USER_INFO_R), api.GetUserInfoWrapper)60 router.GET(withPrefix(api.LOAD_FAVORITE_BOARDS_R), api.LoadFavoriteBoardsWrapper)61 router.GET(withPrefix(api.LOAD_USER_ARTICLES_R), api.LoadUserArticlesWrapper)62 router.POST(withPrefix(api.CHANGE_PASSWD_R), api.ChangePasswdWrapper)63 router.POST(withPrefix(api.ATTEMPT_CHANGE_EMAIL_R), api.AttemptChangeEmailWrapper)64 router.POST(withPrefix(api.CHANGE_EMAIL_R), api.ChangeEmailWrapper)65 router.POST(withPrefix(api.ATTEMPT_SET_ID_EMAIL_R), api.AttemptSetIDEmailWrapper)66 router.POST(withPrefix(api.SET_ID_EMAIL_R), api.SetIDEmailWrapper)67 router.GET(withPrefix(api.GET_USER_ID_R), api.GetUserIDWrapper)68 // comments69 router.GET(withPrefix(api.LOAD_ARTICLE_COMMENTS_R), api.LoadArticleCommentsWrapper)70 router.GET(withPrefix(api.LOAD_USER_COMMENTS_R), api.LoadUserCommentsWrapper)71 router.POST(withPrefix(api.CREATE_COMMENT_R), api.CreateCommentWrapper)72 // ranks73 router.POST(withPrefix(api.CREATE_RANK_R), api.CreateRankWrapper)74 // html75 router.GET(api.ROOT_HTML_R, api.IndexHTMLWrapper)76 router.GET(api.INDEX_HTML_R, api.IndexHTMLWrapper)77 router.GET(api.REGISTER_HTML_R, api.RegisterHTMLWrapper)78 router.GET(api.LOGIN_HTML_R, api.LoginHTMLWrapper)79 router.GET(api.USER_HTML_R, api.UserHTMLWrapper)80 router.GET(api.USER_CHANGE_PASSWD_HTML_R, api.UserChangePasswdHTMLWrapper)81 router.GET(api.USER_ATTEMPT_CHANGE_EMAIL_HTML_R, api.UserAttemptChangeEmailHTMLWrapper)82 router.GET(api.USER_CHANGE_EMAIL_HTML_R, api.UserChangeEmailHTMLWrapper)83 router.GET(api.USER_ATTEMPT_SET_ID_EMAIL_HTML_R, api.UserAttemptSetIDEmailHTMLWrapper)84 router.GET(api.USER_SET_ID_EMAIL_HTML_R, api.UserSetIDEmailHTMLWrapper)85 router.Static("/static", filepath.Join(types.STATIC_DIR, "static"))86 staticFiles := []string{87 "asset-manifest.json",88 "favicon.ico",89 "logo192.png",90 "logo512.png",91 "manifest.json",92 "robots.txt",93 }94 for _, each := range staticFiles {95 router.StaticFile("/"+each, filepath.Join(types.STATIC_DIR, each))96 }97 router.NoRoute(api.AllHTMLWrapper)98 return router, nil99}100func main() {101 err := initMain()102 if err != nil {103 log.Fatalf("unable to initMain: e: %v", err)104 return105 }106 if err := queue.Start(); err != nil {107 log.Fatal(err)108 }109 r, err := initGin()110 if err != nil {111 log.Fatal(err)112 }113 s := &http.Server{114 Addr: types.HTTP_HOST,115 Handler: r,116 }117 g := graceful.NewManager()118 g.AddShutdownJob(func() error {119 queue.Close()120 return nil121 })122 // retry load general boards123 g.AddRunningJob(cron.RetryLoadGeneralBoards)124 // retry load general articles125 g.AddRunningJob(cron.RetryLoadGeneralArticles)126 // retry load article details127 g.AddRunningJob(cron.RetryLoadArticleDetails)128 // retry to calculate user visit count129 g.AddRunningJob(cron.RetryCalculateUserVisit)130 // retry load man articles131 g.AddRunningJob(cron.RetryLoadManArticles)132 // retry load man article details133 g.AddRunningJob(cron.RetryLoadManArticleDetails)134 g.AddRunningJob(func(ctx context.Context) error {135 <-ctx.Done()136 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)137 defer cancel()138 return s.Shutdown(ctx)139 })140 g.AddRunningJob(func(ctx context.Context) error {141 if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {142 return err143 }144 return nil145 })146 <-g.Done()147}...

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(strings.HasPrefix("Golang", "Go"))4 fmt.Println(strings.HasPrefix("Golang", "go"))5}6import (7func main() {8 fmt.Println(strings.HasPrefix("Golang", ""))9 fmt.Println(strings.HasPrefix("Golang", "Golang"))10}11import (12func main() {13 fmt.Println(strings.HasPrefix("", ""))14 fmt.Println(strings.HasPrefix("", "Go"))15}16import (17func main() {18 fmt.Println(strings.HasPrefix("Golang", "Golang is a programming language"))19 fmt.Println(strings.HasPrefix("Golang", "Golang"))20}21import (22func main() {23 fmt.Println(strings.HasPrefix("Golang", "Golang is a programming language"))24 fmt.Println(strings.HasPrefix("Golang", "Golang"))25}26import (27func main() {28 fmt.Println(strings.HasPrefix("Golang", "Golang is a programming language"))29 fmt.Println(strings.HasPrefix("Golang", "Golang"))30}31import (32func main() {33 fmt.Println(strings.HasPrefix("Golang", "Golang is a programming language"))34 fmt.Println(strings.HasPrefix("Golang", "Golang"))35}36import (37func main() {38 fmt.Println(strings.HasPrefix("Golang", "Golang is a programming language"))39 fmt.Println(strings.HasPrefix("Golang", "G

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(strings.HasPrefix("Golang is awesome!", "Golang"))4 fmt.Println(strings.HasPrefix("Golang is awesome!", "is awesome!"))5}6func HasSuffix(s, suffix string) bool7import (8func main() {9 fmt.Println(strings.HasSuffix("Golang is awesome!", "awesome!"))10 fmt.Println(strings.HasSuffix("Golang is awesome!", "Golang"))11}12func Contains(s, substr string) bool13import (14func main() {15 fmt.Println(strings.Contains("Golang is awesome!", "Golang"))16 fmt.Println(strings.Contains("Golang is awesome!", "is awesome!"))17}18func ContainsAny(s, chars string) bool19import (20func main() {21 fmt.Println(strings.ContainsAny("Golang is awesome!", "

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 pkg, err := config.Check("example", nil, nil, &info)4 if err != nil {5 fmt.Println(err)6 }7 typ := pkg.Scope().Lookup("T").Type()8 typ2 := types.NewPointer(typ)9 typ3 := types.NewSlice(typ2)10 typ4 := types.WithPrefix(typ3, "my")11 fmt.Println(typ4)12}13Related Posts: Golang - types.NewSlice() Method14Golang - types.NewPointer() Method15Golang - types.NewSignature() Method16Golang - types.NewStruct() Method17Golang - types.NewTuple() Method18Golang - types.NewVar() Method19Golang - types.NewNamed() Method20Golang - types.NewMap() Method21Golang - types.NewInterface() Method22Golang - types.NewChan() Method23Golang - types.NewArray() Method24Golang - types.NewBasic() Method25Golang - types.NewInterfaceType() Method26Golang - types.NewNamedType() Method27Golang - types.NewPointer() Method28Golang - types.NewSignature() Method29Golang - types.NewSlice() Method30Golang - types.NewStruct() Method31Golang - types.NewTuple() Method32Golang - types.NewVar() Method33Golang - types.NewChan() Method34Golang - types.NewArray() Method35Golang - types.NewBasic() Method36Golang - types.NewInterfaceType() Method37Golang - types.NewNamedType() Method38Golang - types.NewPointer() Method39Golang - types.NewSignature() Method40Golang - types.NewSlice() Method41Golang - types.NewStruct() Method42Golang - types.NewTuple() Method43Golang - types.NewVar() Method44Golang - types.NewChan() Method45Golang - types.NewArray() Method46Golang - types.NewBasic() Method

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 s := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}4 sort.Strings(s)5 i := sort.SearchStrings(s, "x")6 fmt.Println("Index of searched value: ", i)7 fmt.Println("Value at index: ", s[i])8}9import (10func main() {11 s := []int{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}12 sort.Ints(s)13 i := sort.SearchInts(s, 15)14 fmt.Println("Index of searched value: ", i)15 fmt.Println("Value at index: ", s[i])16}17import (18func main() {

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1func main() {2 fmt.Println(types.WithPrefix("hello", "pre"))3}4func main() {5 fmt.Println(types.WithPrefix("hello", "pre"))6}7func main() {8 fmt.Println(types.WithPrefix("hello", "pre"))9}10func main() {11 fmt.Println(types.WithPrefix("hello", "pre"))12}13func main() {14 fmt.Println(types.WithPrefix("hello", "pre"))15}16func main() {17 fmt.Println(types.WithPrefix("hello", "pre"))18}19func main() {20 fmt.Println(types.WithPrefix("hello", "pre"))21}22func main() {23 fmt.Println(types.WithPrefix("hello", "pre"))24}25func main() {26 fmt.Println(types.WithPrefix("hello", "pre"))27}28func main() {29 fmt.Println(types.WithPrefix("hello", "pre"))30}31func main() {32 fmt.Println(types.WithPrefix("hello", "pre"))

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(filepath.Join("usr", "bin", "local"))4 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin"))5 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local"))6 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local"))7 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local", "local"))8 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local", "local", "local"))9 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local", "local", "local", "local"))10 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local", "local", "local", "local", "local"))11 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local", "local", "local", "local", "local", "local"))12 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local", "local", "local", "local", "local", "local", "local"))13 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local", "local", "local", "local", "local", "local", "local", "local"))14 fmt.Println(filepath.Join("usr", "bin", "local", "/usr/local/bin", "local", "local", "local", "local", "local", "local", "local", "local", "

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 address := common.HexToAddress("0x1234567890123456789012345678901234567890")4 addressWithPrefix := address.WithPrefix()5 fmt.Println("Address with prefix:")6 fmt.Println(addressWithPrefix)7}8import (9func main() {10 address := common.HexToAddress("0x1234567890123456789012345678901234567890")11 fmt.Println("Address:")12 fmt.Println(address)13}14import (15func main() {16 address := common.HexToAddress("0x1234567890123456789012345678901234567890")17 fmt.Println("Is Hex Address:")18 fmt.Println(address.IsHexAddress())19}20import (21func main() {22 address := common.HexToAddress("0x1234567890123456789012345678901234567890")23 fmt.Println("Is Hex:")24 fmt.Println(address.IsHex())25}26import (27func main() {28 address := common.HexToAddress("0x1234567890123456789012345678901234567890")

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(strings.HasPrefix("Golang is awesome", "Golang"))4}5Example 2: Using HasPrefix() method of strings package6import (7func main() {8 fmt.Println(strings.HasPrefix("Golang is awesome", "Golang"))9}10Example 3: Using HasPrefix() method of strings package11import (12func main() {13 fmt.Println(strings.HasPrefix("Golang is awesome", "golang"))14}15Example 4: Using HasPrefix() method of strings package16import (17func main() {18 fmt.Println(strings.HasPrefix("Golang is awesome", ""))19}20Example 5: Using HasPrefix() method of strings package21import (22func main() {23 fmt.Println(strings.HasPrefix("", ""))24}25Recommended Posts: Go | strings.TrimPrefix() method26Go | strings.TrimSuffix() method27Go | strings.Trim() method28Go | strings.Title() method29Go | strings.ToLower() method30Go | strings.ToUpper() method31Go | strings.TrimSpace() method32Go | strings.TrimRight() method33Go | strings.TrimLeft() method34Go | strings.Split() method35Go | strings.SplitAfter() method36Go | strings.SplitAfterN() method37Go | strings.SplitN() method38Go | strings.ReplaceAll() method39Go | strings.Replace() method40Go | strings.Repeat() method41Go | strings.ReplaceAll() method42Go | strings.Replace() method43Go | strings.Repeat() method44Go | strings.Trim() method45Go | strings.Title() method46Go | strings.ToLower() method47Go | strings.ToUpper() method48Go | strings.TrimSpace() method49Go | strings.TrimRight() method50Go | strings.TrimLeft() method

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var types = []string{"image/png", "text/plain", "image/jpeg", "image/gif"}4 fmt.Println("pngs:", pngs)5 fmt.Println("txts:", txts)6 fmt.Println("jpgs:", jpgs)7 fmt.Println("gifs:", gifs)8}

Full Screen

Full Screen

WithPrefix

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p := filepath.Join("C:", "Users", "Rohit", "Desktop", "test.txt")4 fmt.Println("Path: ", p)5 dir := filepath.Dir(p)6 fmt.Println("Directory: ", dir)7 file := filepath.Base(p)8 fmt.Println("File: ", file)9 ext := filepath.Ext(p)10 fmt.Println("Extension: ", ext)11 vol := filepath.VolumeName(p)12 fmt.Println("Volume: ", vol)13 fileName := filepath.Base(p)14 fileName = fileName[:len(fileName)-len(ext)]15 fmt.Println("File Name: ", fileName)16 dir = filepath.Dir(p)17 dir = filepath.Join(dir, "Prefix")18 fmt.Println("Directory with prefix: ", dir)19}20Go | filepath.Walk() method21Go | filepath.WalkDir() method22Go | filepath.Walk() method23Go | filepath.WalkDir() method24Go | filepath.Walk() method25Go | filepath.WalkDir() method26Go | filepath.Walk() method

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 Ginkgo 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