Best Gauge code snippet using conn.get
dashboard_apis.go
Source:dashboard_apis.go
...18// ToSlot int `json:"to"`19// NewGroupId int `json:"new_group"`20// }21// func apiGetProxyDebugVars() (int, string) {22// m := getAllProxyDebugVars()23// if m == nil {24// return 500, "get proxy debug var error"25// }26// b, err := json.MarshalIndent(m, " ", " ")27// if err != nil {28// log.Warning(err)29// return 500, err.Error()30// }31// return 200, string(b)32// }33// func apiOverview() (int, string) {34// conn := CreateZkConn()35// defer conn.Close()36// // get all server groups37// groups, err := models.ServerGroups(conn, productName)38// if err != nil {39// log.Warning("get server groups error, maybe there is no any server groups? err:", err)40// return 500, err.Error()41// }42// var instances []string43// for _, group := range groups {44// for _, srv := range group.Servers {45// if srv.Type == "master" {46// instances = append(instances, srv.Addr)47// }48// }49// }50// var info map[string]interface{} = make(map[string]interface{})51// info["product"] = productName52// info["ops"] = proxiesSpeed53// var redisInfos []map[string]string = make([]map[string]string, 0)54// if len(instances) > 0 {55// for _, instance := range instances {56// info, err := utils.GetRedisStat(instance)57// if err != nil {58// log.Error(err)59// }60// redisInfos = append(redisInfos, info)61// }62// }63// info["redis_infos"] = redisInfos64// b, err := json.MarshalIndent(info, " ", " ")65// return 200, string(b)66// }67// func apiGetServerGroupList() (int, string) {68// conn := CreateZkConn()69// defer conn.Close()70// groups, err := models.ServerGroups(conn, productName)71// if err != nil {72// log.Warning(err)73// return 500, err.Error()74// }75// b, err := json.MarshalIndent(groups, " ", " ")76// return 200, string(b)77// }78// func apiRedisStat(param martini.Params) (int, string) {79// addr := param["addr"]80// info, err := utils.GetRedisStat(addr)81// if err != nil {82// return 500, err.Error()83// }84// b, _ := json.MarshalIndent(info, " ", " ")85// return 200, string(b)86// }87// func apiDoMigrate(taskForm MigrateTaskForm, param martini.Params) (int, string) {88// // do migrate async89// taskForm.Percent = 090// taskForm.Status = "pending"91// taskForm.CreateAt = strconv.FormatInt(time.Now().Unix(), 10)92// u, err := uuid.NewV4()93// if err != nil {94// return 500, err.Error()95// }96// taskForm.Id = u.String()97// task := &MigrateTask{98// MigrateTaskForm: taskForm,99// stopChan: make(chan struct{}),100// }101// lck.Lock()102// pendingMigrateTask.PushBack(task)103// lck.Unlock()104// return jsonRetSucc()105// }106// var isRebalancing bool107// var rebalanceLck = sync.Mutex{}108// func changeRebalanceStat(b bool) {109// rebalanceLck.Lock()110// defer rebalanceLck.Unlock()111// isRebalancing = b112// }113// func isOnRebalancing() bool {114// rebalanceLck.Lock()115// defer rebalanceLck.Unlock()116// return isRebalancing117// }118// func apiRebalanceStatus(param martini.Params) (int, string) {119// ret := map[string]interface{}{120// "is_rebalancing": isRebalancing,121// }122// b, _ := json.MarshalIndent(ret, " ", " ")123// return 200, string(b)124// }125// func apiRebalance(param martini.Params) (int, string) {126// if isOnRebalancing() {127// return 500, "rebalancing..."128// }129// go func() {130// changeRebalanceStat(true)131// defer changeRebalanceStat(false)132// conn := CreateZkConn()133// defer conn.Close()134// if err := Rebalance(conn, 0); err != nil {135// log.Warning(err.Error())136// }137// }()138// return jsonRetSucc()139// }140// func apiGetMigrateTasks() (int, string) {141// lck.RLock()142// defer lck.RUnlock()143// var tasks []*MigrateTask144// for e := pendingMigrateTask.Front(); e != nil; e = e.Next() {145// tasks = append(tasks, e.Value.(*MigrateTask))146// }147// b, _ := json.MarshalIndent(tasks, " ", " ")148// return 200, string(b)149// }150// func apiRemovePendingMigrateTask(param martini.Params) (int, string) {151// lck.Lock()152// defer lck.Unlock()153// id := param["id"]154// if removePendingMigrateTask(id) == true {155// return jsonRetSucc()156// }157// return 500, "remove task error"158// }159// func apiStopMigratingTask(param martini.Params) (int, string) {160// lck.RLock()161// defer lck.RUnlock()162// if curMigrateTask != nil {163// curMigrateTask.Status = "stopping"164// curMigrateTask.stopChan <- struct{}{}165// }166// return jsonRetSucc()167// }168// func apiGetServerGroup(param martini.Params) (int, string) {169// id := param["id"]170// groupId, err := strconv.Atoi(id)171// if err != nil {172// log.Warning(err)173// return 500, err.Error()174// }175// conn := CreateZkConn()176// defer conn.Close()177// group, err := models.GetGroup(conn, productName, groupId)178// if err != nil {179// log.Warning(err)180// return 500, err.Error()181// }182// b, err := json.MarshalIndent(group, " ", " ")183// return 200, string(b)184// }185// func apiMigrateStatus() (int, string) {186// conn := CreateZkConn()187// defer conn.Close()188// migrateSlots, err := models.GetMigratingSlots(conn, productName)189// if err != nil {190// log.Warning("get slots info error, maybe init slots first? err: ", err)191// return 500, err.Error()192// }193// b, err := json.MarshalIndent(map[string]interface{}{194// "migrate_slots": migrateSlots,195// "migrate_task": curMigrateTask,196// }, " ", " ")197// return 200, string(b)198// }199// func apiGetRedisSlotInfo(param martini.Params) (int, string) {200// addr := param["addr"]201// slotId, err := strconv.Atoi(param["id"])202// if err != nil {203// log.Warning(err)204// return 500, err.Error()205// }206// slotInfo, err := utils.SlotsInfo(addr, slotId, slotId)207// if err != nil {208// log.Warning(err)209// return 500, err.Error()210// }211// out, _ := json.MarshalIndent(map[string]interface{}{212// "keys": slotInfo[slotId],213// "slot_id": slotId,214// }, " ", " ")215// return 200, string(out)216// }217// func apiGetRedisSlotInfoFromGroupId(param martini.Params) (int, string) {218// groupId, err := strconv.Atoi(param["group_id"])219// if err != nil {220// log.Warning(err)221// return 500, err.Error()222// }223// slotId, err := strconv.Atoi(param["slot_id"])224// if err != nil {225// log.Warning(err)226// return 500, err.Error()227// }228// conn := CreateZkConn()229// defer conn.Close()230// g, err := models.GetGroup(conn, productName, groupId)231// if err != nil {232// log.Warning(err)233// return 500, err.Error()234// }235// s, err := g.Master(conn)236// if err != nil {237// log.Warning(err)238// return 500, err.Error()239// }240// if s == nil {241// log.Warning("this group has no master server")242// return 500, "this group has no master server"243// }244// slotInfo, err := utils.SlotsInfo(s.Addr, slotId, slotId)245// if err != nil {246// log.Warning(err)247// return 500, err.Error()248// }249// out, _ := json.MarshalIndent(map[string]interface{}{250// "keys": slotInfo[slotId],251// "slot_id": slotId,252// "group_id": groupId,253// "addr": s.Addr,254// }, " ", " ")255// return 200, string(out)256// }257// func apiRemoveServerGroup(param martini.Params) (int, string) {258// conn := CreateZkConn()259// defer conn.Close()260// lock := utils.GetZkLock(conn, productName)261// lock.Lock(fmt.Sprintf("remove group %s", param["id"]))262// defer func() {263// err := lock.Unlock()264// if err != nil {265// log.Warning(err)266// }267// }()268// groupId, _ := strconv.Atoi(param["id"])269// serverGroup := models.NewServerGroup(productName, groupId)270// if err := serverGroup.Remove(conn); err != nil {271// log.Warning(err)272// return 500, err.Error()273// }274// return jsonRetSucc()275// }276// // create new server group277// func apiAddServerGroup(newGroup models.ServerGroup) (int, string) {278// conn := CreateZkConn()279// defer conn.Close()280// lock := utils.GetZkLock(conn, productName)281// lock.Lock(fmt.Sprintf("add group %+v", newGroup))282// defer func() {283// err := lock.Unlock()284// if err != nil {285// log.Warning(err)286// }287// }()288// newGroup.ProductName = productName289// exists, err := newGroup.Exists(conn)290// if err != nil {291// log.Warning(err)292// return 500, err.Error()293// }294// if exists {295// return jsonRet(map[string]interface{}{296// "ret": 0,297// "msg": "group already exists",298// })299// }300// err = newGroup.Create(conn)301// if err != nil {302// log.Warning(err)303// return 500, err.Error()304// }305// return jsonRetSucc()306// }307// // add redis server to exist server group308// func apiAddServerToGroup(server models.Server, param martini.Params) (int, string) {309// groupId, _ := strconv.Atoi(param["id"])310// conn := CreateZkConn()311// defer conn.Close()312// lock := utils.GetZkLock(conn, productName)313// lock.Lock(fmt.Sprintf("add server to group, %+v", server))314// defer func() {315// err := lock.Unlock()316// if err != nil {317// log.Warning(err)318// }319// }()320// // check group exists first321// serverGroup := models.NewServerGroup(productName, groupId)322// exists, err := serverGroup.Exists(conn)323// if err != nil {324// log.Warning(err)325// return 500, err.Error()326// }327// if !exists {328// return jsonRetFail(-1, "group not exists")329// }330// if err := serverGroup.AddServer(conn, &server); err != nil {331// log.Warning(err)332// return 500, err.Error()333// }334// return jsonRetSucc()335// }336// func apiPromoteServer(server models.Server, param martini.Params) (int, string) {337// conn := CreateZkConn()338// defer conn.Close()339// lock := utils.GetZkLock(conn, productName)340// lock.Lock(fmt.Sprintf("promote server %+v", server))341// defer func() {342// err := lock.Unlock()343// if err != nil {344// log.Warning(err)345// }346// }()347// group, err := models.GetGroup(conn, productName, server.GroupId)348// if err != nil {349// log.Warning(err)350// return 500, err.Error()351// }352// err = group.Promote(conn, server.Addr)353// if err != nil {354// log.Warning(err)355// return 500, err.Error()356// }357// return jsonRetSucc()358// }359// func apiRemoveServerFromGroup(server models.Server, param martini.Params) (int, string) {360// groupId, _ := strconv.Atoi(param["id"])361// conn := CreateZkConn()362// defer conn.Close()363// lock := utils.GetZkLock(conn, productName)364// lock.Lock(fmt.Sprintf("remove server from group, %+v", server))365// defer func() {366// err := lock.Unlock()367// if err != nil {368// log.Warning(err)369// }370// }()371// serverGroup := models.NewServerGroup(productName, groupId)372// err := serverGroup.RemoveServer(conn, server)373// if err != nil {374// log.Warning(err)375// return 500, err.Error()376// }377// return jsonRetSucc()378// }379// func apiSetProxyStatus(proxy models.ProxyInfo, param martini.Params) (int, string) {380// conn := CreateZkConn()381// defer conn.Close()382// err := models.SetProxyStatus(conn, productName, proxy.Id, proxy.State)383// if err != nil {384// log.Warning(err)385// return 500, err.Error()386// }387// return jsonRetSucc()388// }389// func apiGetProxyList(param martini.Params) (int, string) {390// conn := CreateZkConn()391// defer conn.Close()392// proxies, err := models.ProxyList(conn, productName, nil)393// if err != nil {394// log.Warning(err)395// return 500, err.Error()396// }397// b, err := json.MarshalIndent(proxies, " ", " ")398// return 200, string(b)399// }400// func apiGetSlots() (int, string) {401// conn := CreateZkConn()402// defer conn.Close()403// slots, err := models.Slots(conn, productName)404// if err != nil {405// log.Warning("get slot info error, maybe init slots first? err:", err)406// return 500, err.Error()407// }408// b, err := json.MarshalIndent(slots, " ", " ")409// return 200, string(b)410// }411// func apiSlotRangeSet(task RangeSetTask) (int, string) {412// conn := CreateZkConn()413// defer conn.Close()414// lock := utils.GetZkLock(conn, productName)415// lock.Lock(fmt.Sprintf("set slot range, %+v", task))416// defer func() {417// err := lock.Unlock()418// if err != nil {419// log.Warning(err)...
client_conn_pool.go
Source:client_conn_pool.go
...34 keys map[*ClientConn][]string35 addConnCalls map[string]*addConnCall // in-flight addConnIfNeede calls36}37func (p *clientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) {38 return p.getClientConn(req, addr, dialOnMiss)39}40const (41 dialOnMiss = true42 noDialOnMiss = false43)44// shouldTraceGetConn reports whether getClientConn should call any45// ClientTrace.GetConn hook associated with the http.Request.46//47// This complexity is needed to avoid double calls of the GetConn hook48// during the back-and-forth between net/http and x/net/http2 (when the49// net/http.Transport is upgraded to also speak http2), as well as support50// the case where x/net/http2 is being used directly.51func (p *clientConnPool) shouldTraceGetConn(st clientConnIdleState) bool {52 // If our Transport wasn't made via ConfigureTransport, always53 // trace the GetConn hook if provided, because that means the54 // http2 package is being used directly and it's the one55 // dialing, as opposed to net/http.56 if _, ok := p.t.ConnPool.(noDialClientConnPool); !ok {57 return true58 }59 // Otherwise, only use the GetConn hook if this connection has60 // been used previously for other requests. For fresh61 // connections, the net/http package does the dialing.62 return !st.freshConn63}64func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) {65 if isConnectionCloseRequest(req) && dialOnMiss {66 // It gets its own connection.67 traceGetConn(req, addr)68 const singleUse = true69 cc, err := p.t.dialClientConn(addr, singleUse)70 if err != nil {71 return nil, err72 }73 return cc, nil74 }75 p.mu.Lock()76 for _, cc := range p.conns[addr] {77 if st := cc.idleState(); st.canTakeNewRequest {78 if p.shouldTraceGetConn(st) {79 traceGetConn(req, addr)80 }81 p.mu.Unlock()82 return cc, nil83 }84 }85 if !dialOnMiss {86 p.mu.Unlock()87 return nil, ErrNoCachedConn88 }89 traceGetConn(req, addr)90 call := p.getStartDialLocked(addr)91 p.mu.Unlock()92 <-call.done93 return call.res, call.err94}95// dialCall is an in-flight Transport dial call to a host.96type dialCall struct {97 p *clientConnPool98 done chan struct{} // closed when done99 res *ClientConn // valid after done is closed100 err error // valid after done is closed101}102// requires p.mu is held.103func (p *clientConnPool) getStartDialLocked(addr string) *dialCall {104 if call, ok := p.dialing[addr]; ok {105 // A dial is already in-flight. Don't start another.106 return call107 }108 call := &dialCall{p: p, done: make(chan struct{})}109 if p.dialing == nil {110 p.dialing = make(map[string]*dialCall)111 }112 p.dialing[addr] = call113 go call.dial(addr)114 return call115}116// run in its own goroutine.117func (c *dialCall) dial(addr string) {118 const singleUse = false // shared conn119 c.res, c.err = c.p.t.dialClientConn(addr, singleUse)120 close(c.done)121 c.p.mu.Lock()122 delete(c.p.dialing, addr)123 if c.err == nil {124 c.p.addConnLocked(addr, c.res)125 }126 c.p.mu.Unlock()127}128// addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't129// already exist. It coalesces concurrent calls with the same key.130// This is used by the http1 Transport code when it creates a new connection. Because131// the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know132// the protocol), it can get into a situation where it has multiple TLS connections.133// This code decides which ones live or die.134// The return value used is whether c was used.135// c is never closed.136func (p *clientConnPool) addConnIfNeeded(key string, t *Transport, c *tls.Conn) (used bool, err error) {137 p.mu.Lock()138 for _, cc := range p.conns[key] {139 if cc.CanTakeNewRequest() {140 p.mu.Unlock()141 return false, nil142 }143 }144 call, dup := p.addConnCalls[key]145 if !dup {146 if p.addConnCalls == nil {147 p.addConnCalls = make(map[string]*addConnCall)148 }149 call = &addConnCall{150 p: p,151 done: make(chan struct{}),152 }153 p.addConnCalls[key] = call154 go call.run(t, key, c)155 }156 p.mu.Unlock()157 <-call.done158 if call.err != nil {159 return false, call.err160 }161 return !dup, nil162}163type addConnCall struct {164 p *clientConnPool165 done chan struct{} // closed when done166 err error167}168func (c *addConnCall) run(t *Transport, key string, tc *tls.Conn) {169 cc, err := t.NewClientConn(tc)170 p := c.p171 p.mu.Lock()172 if err != nil {173 c.err = err174 } else {175 p.addConnLocked(key, cc)176 }177 delete(p.addConnCalls, key)178 p.mu.Unlock()179 close(c.done)180}181func (p *clientConnPool) addConn(key string, cc *ClientConn) {182 p.mu.Lock()183 p.addConnLocked(key, cc)184 p.mu.Unlock()185}186// p.mu must be held187func (p *clientConnPool) addConnLocked(key string, cc *ClientConn) {188 for _, v := range p.conns[key] {189 if v == cc {190 return191 }192 }193 if p.conns == nil {194 p.conns = make(map[string][]*ClientConn)195 }196 if p.keys == nil {197 p.keys = make(map[*ClientConn][]string)198 }199 p.conns[key] = append(p.conns[key], cc)200 p.keys[cc] = append(p.keys[cc], key)201}202func (p *clientConnPool) MarkDead(cc *ClientConn) {203 p.mu.Lock()204 defer p.mu.Unlock()205 for _, key := range p.keys[cc] {206 vv, ok := p.conns[key]207 if !ok {208 continue209 }210 newList := filterOutClientConn(vv, cc)211 if len(newList) > 0 {212 p.conns[key] = newList213 } else {214 delete(p.conns, key)215 }216 }217 delete(p.keys, cc)218}219func (p *clientConnPool) closeIdleConnections() {220 p.mu.Lock()221 defer p.mu.Unlock()222 // TODO: don't close a cc if it was just added to the pool223 // milliseconds ago and has never been used. There's currently224 // a small race window with the HTTP/1 Transport's integration225 // where it can add an idle conn just before using it, and226 // somebody else can concurrently call CloseIdleConns and227 // break some caller's RoundTrip.228 for _, vv := range p.conns {229 for _, cc := range vv {230 cc.closeIfIdle()231 }232 }233}234func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn {235 out := in[:0]236 for _, v := range in {237 if v != exclude {238 out = append(out, v)239 }240 }241 // If we filtered it out, zero out the last item to prevent242 // the GC from seeing it.243 if len(in) != len(out) {244 in[len(in)-1] = nil245 }246 return out247}248// noDialClientConnPool is an implementation of http2.ClientConnPool249// which never dials. We let the HTTP/1.1 client dial and use its TLS250// connection instead.251type noDialClientConnPool struct{ *clientConnPool }252func (p noDialClientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) {253 return p.getClientConn(req, addr, noDialOnMiss)254}...
redis.go
Source:redis.go
1// Package redis 建ç«redisè¿æ¥æ± 2package redis3import (4 "log"5 "time"6 etcdStruct "github.com/hellozouyou/easy-mall/pkg/structure/etcd"7 "github.com/gomodule/redigo/redis"8)9// sprint from https://github.com/hopehook/golang-db10// ConnPool is RDS struct11type ConnPool struct {12 Pool redis.Pool13}14// Client redis çæ¬å°è¿æ¥15var Client *ConnPool16// Init init redis17func Init(config *etcdStruct.Redis) {18 Client = InitRedisPool(config.Host, config.Password, config.Database, config.MaxOpenConns, config.MaxIdleConns)19}20// InitRedisPool func init RDS fd21func InitRedisPool(host, password string, database, maxOpenConns, maxIdleConns int) *ConnPool {22 r := &ConnPool{}23 r.Pool = redis.Pool{24 MaxActive: maxOpenConns, // max number of connections25 MaxIdle: maxIdleConns,26 IdleTimeout: 120 * time.Second,27 Dial: func() (redis.Conn, error) {28 c, err := redis.Dial("tcp", host)29 if err != nil {30 return nil, err31 }32 if len(password) > 0 {33 if _, err := c.Do("AUTH", password); err != nil {34 c.Close()35 return nil, err36 }37 }38 if _, err := c.Do("select", database); err != nil {39 c.Close()40 return nil, err41 }42 return c, err43 },44 TestOnBorrow: func(c redis.Conn, t time.Time) error {45 _, err := c.Do("PING")46 return err47 },48 }49 if _, err := r.Do("PING"); err != nil {50 log.Panicln("Init redis pool failed.", err.Error())51 }52 return r53}54// GetConn pool55func (p *ConnPool) GetConn() redis.Conn {56 conn := p.Pool.Get()57 if conn.Err() != nil {58 log.Printf("GetConn redis fail, %v", conn.Err())59 time.Sleep(1)60 for {61 // ç´å°è·åæå62 conn = p.Pool.Get()63 if conn.Err() == nil {64 break65 }66 }67 }68 return conn69}70// Close pool71func (p *ConnPool) Close() error {72 err := p.Pool.Close()73 return err74}75// Do commands76func (p *ConnPool) Do(command string, args ...interface{}) (interface{}, error) {77 conn := p.GetConn()78 defer conn.Close()79 return conn.Do(command, args...)80}81// Set for value82func (p *ConnPool) Set(key string, value interface{}) (interface{}, error) {83 conn := p.GetConn()84 defer conn.Close()85 return conn.Do("SET", key, value)86}87// SetEx 设置带æææçvalue88func (p *ConnPool) SetEx(key string, seconds int64, value interface{}) (interface{}, error) {89 conn := p.GetConn()90 defer conn.Close()91 return conn.Do("SETEX", key, seconds, value)92}93// GetString for string94func (p *ConnPool) GetString(key string) (string, error) {95 conn := p.GetConn()96 defer conn.Close()97 return redis.String(conn.Do("GET", key))98}99// GetBytes for bytes100func (p *ConnPool) GetBytes(key string) ([]byte, error) {101 conn := p.GetConn()102 defer conn.Close()103 return redis.Bytes(conn.Do("GET", key))104}105// GetInt for int106func (p *ConnPool) GetInt(key string) (int, error) {107 conn := p.GetConn()108 defer conn.Close()109 return redis.Int(conn.Do("GET", key))110}111// GetInt64 for int64112func (p *ConnPool) GetInt64(key string) (int64, error) {113 conn := p.GetConn()114 defer conn.Close()115 return redis.Int64(conn.Do("GET", key))116}117// GetUint64 for uint64118func (p *ConnPool) GetUint64(key string) (uint64, error) {119 conn := p.GetConn()120 defer conn.Close()121 return redis.Uint64(conn.Do("GET", key))122}123// Del for key124func (p *ConnPool) Del(key string) (interface{}, error) {125 conn := p.GetConn()126 defer conn.Close()127 return conn.Do("DEL", key)128}129// Expire for key130func (p *ConnPool) Expire(key string, seconds int64) (interface{}, error) {131 conn := p.GetConn()132 defer conn.Close()133 return conn.Do("EXPIRE", key, seconds)134}135// Keys for key136func (p *ConnPool) Keys(pattern string) ([]string, error) {137 conn := p.GetConn()138 defer conn.Close()139 return redis.Strings(conn.Do("KEYS", pattern))140}141// KeysByteSlices for key142func (p *ConnPool) KeysByteSlices(pattern string) ([][]byte, error) {143 conn := p.GetConn()144 defer conn.Close()145 return redis.ByteSlices(conn.Do("KEYS", pattern))146}147// SetHashMap for hash map148func (p *ConnPool) SetHashMap(key string, fieldValue map[string]interface{}) (interface{}, error) {149 conn := p.GetConn()150 defer conn.Close()151 return conn.Do("HMSET", redis.Args{}.Add(key).AddFlat(fieldValue)...)152}153// GetHashMapString for hash map154func (p *ConnPool) GetHashMapString(key string) (map[string]string, error) {155 conn := p.GetConn()156 defer conn.Close()157 return redis.StringMap(conn.Do("HGETALL", key))158}159// GetHashMapInt for hash map160func (p *ConnPool) GetHashMapInt(key string) (map[string]int, error) {161 conn := p.GetConn()162 defer conn.Close()163 return redis.IntMap(conn.Do("HGETALL", key))164}165// GetHashMapInt64 for hash map166func (p *ConnPool) GetHashMapInt64(key string) (map[string]int64, error) {167 conn := p.GetConn()168 defer conn.Close()169 return redis.Int64Map(conn.Do("HGETALL", key))170}171// INCR å° key ä¸å¨åçæ°åå¼å¢ä¸ï¼å¦æ key ä¸åå¨ï¼é£ä¹ key çå¼ä¼å
被åå§å为 0 ï¼ç¶ååæ§è¡ INCR æä½ã172func (p *ConnPool) INCR(key string) (int, error) {173 conn := p.GetConn()174 defer conn.Close()175 return redis.Int(conn.Do("INCR", key))176}...
get
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer resp.Body.Close()7 fmt.Println(resp.Status)8}9import (10func main() {11 if err != nil {12 log.Fatal(err)13 }14 defer resp.Body.Close()15 body, err := ioutil.ReadAll(resp.Body)16 if err != nil {17 log.Fatal(err)18 }19 fmt.Println(string(body))20}21import (22func main() {23 if err != nil {24 log.Fatal(err)25 }26 defer resp.Body.Close()27 body, err := ioutil.ReadAll(resp.Body)28 if err != nil {29 log.Fatal(err)30 }31 fmt.Println(string(body))32}33import (34func main() {35 if err != nil {36 log.Fatal(err)37 }38 defer resp.Body.Close()39 body, err := ioutil.ReadAll(resp.Body)40 if err != nil {41 log.Fatal(err)42 }43 fmt.Println(string(body))44}45import (46func main() {
get
Using AI Code Generation
1import (2type conn struct {3}4func (c *conn) get() string {5 response, err := http.Get(c.url)6 if err != nil {7 fmt.Println("Error in get method")8 }9 defer response.Body.Close()10 body, err := ioutil.ReadAll(response.Body)11 if err != nil {12 fmt.Println("Error in get method")13 }14 return string(body)15}16func (c *conn) post() string {17 response, err := http.Post(c.url, "application/x-www-form-urlencoded", nil)18 if err != nil {19 fmt.Println("Error in post method")20 }21 defer response.Body.Close()22 body, err := ioutil.ReadAll(response.Body)23 if err != nil {24 fmt.Println("Error in post method")25 }26 return string(body)27}28func (c *conn) put() string {29 client := &http.Client{}30 request, err := http.NewRequest("PUT", c.url, nil)31 if err != nil {32 fmt.Println("Error in put method")33 }34 response, err := client.Do(request)35 if err != nil {36 fmt.Println("Error in put method")37 }38 defer response.Body.Close()39 body, err := ioutil.ReadAll(response.Body)40 if err != nil {41 fmt.Println("Error in put method")42 }43 return string(body)44}45func (c *conn) delete() string {46 client := &http.Client{}47 request, err := http.NewRequest("DELETE", c.url, nil)48 if err != nil {49 fmt.Println("Error in delete method")50 }51 response, err := client.Do(request)52 if err != nil {53 fmt.Println("Error in delete method")54 }55 defer response.Body.Close()56 body, err := ioutil.ReadAll(response.Body)57 if err != nil {58 fmt.Println("Error in delete method")59 }60 return string(body)61}62func main() {63 c := conn{64 }65 fmt.Println("Get method response:", c.get())66 fmt.Println("Post method response:", c.post())67 fmt.Println("Put method response:", c.put())
get
Using AI Code Generation
1import (2func main() {3 conn := conn.Conn{Conn: "Hello World"}4 fmt.Println(conn.Get())5}6import (7func main() {8 conn := conn.Conn{Conn: "Hello World"}9 fmt.Println(conn.Get())10}11import (12func main() {13 conn := conn.Conn{Conn: "Hello World"}14 fmt.Println(conn.Get())15}16For example, you can create another Go file named 2.go and import the conn package in it. You can also
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!