text
stringlengths
11
4.05M
package main import ( "go/scanner" "go/token" "io/ioutil" "os" ) type TokenSet map[string]struct{} // GoTokens gets the tokens from set of source files. func GoTokens(srcpaths []string) (toks TokenSet, err error) { tokc := make(chan []string) errc := make(chan error) fs := token.NewFileSet() files := 0 for _, path := range srcpaths { st, serr := os.Stat(path) if serr != nil { break } f := fs.AddFile(path, fs.Base(), int(st.Size())) go func(tf *token.File) { s, e := fileTokens(tf) tokc <- s errc <- e }(f) files++ } toks = make(TokenSet) for i := 0; i < files; i++ { if curToks := <-tokc; curToks != nil { for _, tok := range curToks { toks[tok] = struct{}{} toks[tok+"s"] = struct{}{} } } if curErr := <-errc; curErr != nil { err = curErr } } return toks, err } func fileTokens(tf *token.File) (toks []string, err error) { src, err := ioutil.ReadFile(tf.Name()) if err != nil { return nil, err } s := &scanner.Scanner{} s.Init(tf, src, nil, 0) tokmap := make(TokenSet) for { _, tok, lit := s.Scan() if tok == token.EOF { break } if tok == token.STRING { // XXX: what if strings are misspelled? lit = lit[1 : len(lit)-1] } tokmap[lit] = struct{}{} } for k := range tokmap { toks = append(toks, k) } return toks, nil }
// Copyright 2013 Benjamin Gentil. All rights reserved. // license can be found in the LICENSE file (MIT License) package zlang import ( "fmt" "strings" "unicode" "unicode/utf8" ) const ( LeftBlockDelim = '{' RightBlockDelim = '}' LeftParentDelim = '(' RightParentDelim = ')' ParamDelim = ',' StringDelim = '"' EscapeCar = '\\' Comment = "//" LeftBlockComment = "/*" RightBlockComment = "*/" ) // For error reporting type Position struct { name string line int char int } type LexItem struct { Token Token Val string } func (i LexItem) String() string { switch { case i.Token == TOK_EOF: return "EOF" case i.Token == TOK_ERROR: return i.Val case len(i.Val) > 10: return fmt.Sprintf("%.10q...", i.Val) } return fmt.Sprintf("%q", i.Val) } const eof = -1 // lexer holds the state of the scanner. type Lexer struct { name string // the position to be reported in case of error input string // the string being scanned. pos int // current position in the input. start int // start position of this item. width int // width of last rune read from input. } // Initialize the lexer func NewLexer(name, input string) *Lexer { return &Lexer{ name: name, input: input, pos: 0, start: 0, width: 1, } } // get the line number for error reporting func (l *Lexer) lineNumber() int { return 1 + strings.Count(l.input[:l.pos], "\n") } // Report an error func (l *Lexer) emit_error(format string, args ...interface{}) LexItem { return LexItem{TOK_ERROR, fmt.Sprintf(format, args...)} } func (l *Lexer) emit(t Token) LexItem { value := l.getVal() l.start = l.pos return LexItem{t, value} } func (l *Lexer) getVal() string { return l.input[l.start:l.pos] } // get next rune of the input func (l *Lexer) getRune() (r rune) { if l.pos >= len(l.input) { l.width = 0 return eof } r, l.width = utf8.DecodeRuneInString(l.input[l.pos:]) l.pos += l.width return r } // seek next rune but doesn't consume it func (l *Lexer) peekRune() rune { r := l.getRune() l.pos -= l.width return r } // ignore the current string, used for space and tabs func (l *Lexer) ignore() { l.start = l.pos } // Parser will call NextItem until item's token is TOK_EOF or TOK_ERROR func (l *Lexer) NextItem() LexItem { lastRune := ' ' for isSpace(lastRune) { l.ignore() // don't emit space token lastRune = l.getRune() } // identifier starts with a letter if isLetter(lastRune) || lastRune == POINTER_CHAR { for isAlphaNumeric(l.peekRune()) { lastRune = l.getRune() } return l.emit(resolveIdentifier(l.getVal())) } if isDigit(lastRune) { isFloat := false // parse hexa if lastRune == '0' && l.peekRune() == 'x' { l.getRune() // get the x for isHexa(l.peekRune()) { lastRune = l.getRune() } return l.emit(TOK_BYTE) } for isDigitOrDot(l.peekRune()) { lastRune = l.getRune() if lastRune == '.' { if !isFloat { isFloat = true } else { // more than 1 dot return l.emit_error("misformated float %s", l.getVal()) } } } if !isFloat { return l.emit(TOK_INT) } return l.emit(TOK_FLOAT) } if isEndOfLine(lastRune) { return l.emit(TOK_ENDL) } // parse a string if lastRune == StringDelim { l.ignore() // skip opening " for { nextRune := l.peekRune() if nextRune == StringDelim && lastRune != EscapeCar { s := l.emit(TOK_STRING) lastRune = l.getRune() // get the closing " return s } if nextRune == eof { return l.emit_error("unclosed string %s", l.getVal()) } lastRune = l.getRune() } } // parse a multiline comment if lastRune == '/' && l.peekRune() == '*' { lastRune = l.getRune() // position on * for { lastRune = l.getRune() nextRune := l.peekRune() if lastRune == '*' && nextRune == '/' { lastRune = l.getRune() // get the closing / return l.emit(TOK_COMMENT) } if nextRune == eof { return l.emit_error("unclosed comment %s", l.getVal()) } } } // parse a single line comment if lastRune == '/' && l.peekRune() == '/' { for !isEndOfLine(l.peekRune()) && lastRune != eof { lastRune = l.getRune() } return l.emit(TOK_COMMENT) } if tok_op := resolveOperator(string(lastRune)); tok_op != TOK_ERROR { return l.emit(tok_op) } if tok_del := resolveDelimiter(string(lastRune)); tok_del != TOK_ERROR { return l.emit(tok_del) } if lastRune == eof { return l.emit(TOK_EOF) } return l.emit_error("unknown token with value '%s' last rune = 0x%x", l.getVal(), lastRune) } // isSpace reports whether r is a space character. func isSpace(r rune) bool { return r == ' ' || r == '\t' } // isEndOfLine reports whether r is an end-of-line character. func isEndOfLine(r rune) bool { return r == '\r' || r == '\n' } // isAlphaNumeric reports whether r is an alphabetic, digit, or underscore. func isAlphaNumeric(r rune) bool { return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) } // isAlphaNumeric reports whether r is an alphabetic, digit, or underscore. func isLetter(r rune) bool { return unicode.IsLetter(r) } // isDigit reports whether r is a digit func isDigit(r rune) bool { return unicode.IsDigit(r) } // isDigit reports whether r is a digit or a dot (float) func isDigitOrDot(r rune) bool { return unicode.IsDigit(r) || r == '.' } // isHexa reports whether r is hexa func isHexa(r rune) bool { return strings.ContainsRune("0123456789ABCDEFabcdef", r) }
package main import ( "log" "logindemo/config" "logindemo/controler" "logindemo/db" "net/http" "github.com/gorilla/mux" ) func main() { db.Connect() handleRequests() } func handleRequests() { r := mux.NewRouter() r.HandleFunc("/api/register", controler.SignUpUser).Methods("POST") r.HandleFunc("/api/login", controler.LoginUser).Methods("POST") r.HandleFunc("/api/users", controler.AllUsers).Methods("GET") serveMux := http.NewServeMux() serveMux.Handle("/", r) log.Println("Starting server...") config, err := config.GetConfig() if err != nil { println(err.Error()) } else { log.Panic(http.ListenAndServe(config.Production.PORT, serveMux)) } }
package store import ( goredis "github.com/go-redis/redis" "time" ) var LogDB redisClient type redisClient interface { ZAdd(key string, val string) error ZRange(keys []string) (map[string][]string, error) LPush(key, val string) error LRange(key string) ([]string, error) Close() error } type redis struct { client *goredis.Client } func NewRedis(addr string) redisClient { cli := goredis.NewClient(&goredis.Options{ Addr: addr, Password: "", DB: 0, }) return &redis{ client: cli, } } func (r *redis) ZAdd(key string, val string) error { cmd := r.client.ZAdd(key, goredis.Z{ Score: float64(time.Now().UnixNano()), Member: val, }) return cmd.Err() } func (r *redis) ZRange(keys []string) (map[string][]string, error) { res := make(map[string][]string) for _, key := range keys { cmd := r.client.ZRange(key, 0, -1) if cmd.Err() != nil { return nil, cmd.Err() } res[key] = cmd.Val() } return res, nil } func (r *redis) LPush(key, val string) error { cmd := r.client.LPush(key, val) return cmd.Err() } func (r *redis) LRange(key string) ([]string, error) { cmd := r.client.LRange(key, 0, -1) return cmd.Result() } func (r *redis) Close() error { return r.client.Close() }
package binance_test import ( "github.com/ramezanius/crypex/exchange/binance" "github.com/ramezanius/crypex/exchange/tests" ) func (suite *binanceSuite) TestSubscribeReports() { suite.NoError(suite.exchange.SubscribeReports()) suite.TestOrders() tests.Wait() suite.NoError(suite.exchange.UnsubscribeReports()) } func (suite *binanceSuite) TestSubscribeCandles() { params := binance.CandlesParams{ Snapshot: true, Period: binance.Period1Minute, Symbol: binance.BNB + binance.BTC, } suite.NoError(suite.exchange.SubscribeCandles(params)) tests.Wait() suite.NoError(suite.exchange.UnsubscribeCandles(params)) suite.Run("Fail", func() { params := binance.CandlesParams{ Period: binance.Period1Minute, Symbol: binance.USD + binance.BTC, } suite.NoError(suite.exchange.SubscribeCandles(params)) }) }
package daos import ( wm "github.com/constant-money/constant-web-api/models" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) type CollateralLoanDAO struct { db *gorm.DB } // InitCollateralLoanDAO : func InitCollateralLoanDAO(database *gorm.DB) *CollateralLoanDAO { return &CollateralLoanDAO{ db: database, } } func (cl *CollateralLoanDAO) Update(tx *gorm.DB, model *wm.CollateralLoan) error { if err := tx.Save(model).Error; err != nil { return errors.Wrap(err, "tx.Update.CollateralLoan") } return nil } func (cl *CollateralLoanDAO) FindAllPending(lastIndex uint, limit int) ([]*wm.CollateralLoan, error) { var ( collateralLoans []*wm.CollateralLoan ) query := cl.db.Table("collateral_loans").Preload("Collateral"). Where("status = ? AND id > ?", wm.CollateralLoanStatusPending, lastIndex). Order("id asc"). Limit(limit) if err := query.Find(&collateralLoans).Error; err != nil { return nil, errors.Wrap(err, "db.Find") } return collateralLoans, nil } func (cl *CollateralLoanDAO) FindAllPayingByDate(dayNumber uint, page int, limit int) ([]*wm.CollateralLoan, error) { var ( collateralLoans []*wm.CollateralLoan offset = page*limit - limit ) // HOUR(next_pay_at) = HOUR(now()) query := cl.db.Raw(`SELECT * FROM collateral_loans WHERE status = ? AND YEAR(next_pay_at) = YEAR(now() + interval ? day) AND MONTH(next_pay_at) = MONTH(now() + interval ? day) AND DAY(next_pay_at) = DAY(now() + interval ? day) LIMIT ? OFFSET ?`, wm.CollateralLoanStatusPayingInterest, dayNumber, dayNumber, dayNumber, limit, offset) if err := query.Scan(&collateralLoans).Error; err != nil { return nil, errors.Wrap(err, "db.Find") } return collateralLoans, nil } func (cl *CollateralLoanDAO) FindAllPayingInterestByDay(dayNumber int, page int, limit int) ([]*wm.CollateralLoan, error) { var ( collateralLoans []*wm.CollateralLoan offset = page*limit - limit ) query := cl.db.Raw(`SELECT * FROM collateral_loans WHERE status = ? AND YEAR(next_pay_at) <= YEAR(now() - interval ? day) AND MONTH(next_pay_at) <= MONTH(now() - interval ? day) AND DAY(next_pay_at) <= DAY(now() - interval ? day) LIMIT ? OFFSET ?`, wm.CollateralLoanStatusAccepted, dayNumber, dayNumber, dayNumber, limit, offset) if err := query.Scan(&collateralLoans).Error; err != nil { return nil, errors.Wrap(err, "db.Find") } return collateralLoans, nil } func (cl *CollateralLoanDAO) FindAllDowntrend(amount uint64, page int, limit int) ([]*wm.CollateralLoan, error) { var ( collateralLoans []*wm.CollateralLoan offset = page*limit - limit ) query := cl.db.Table("collateral_loans").Preload("Collateral").Preload("CollateralLoanTransactions"). Joins("JOIN collateral_loan_transactions ON collateral_loan_transactions.collateral_loan_id=collateral_loans.id"). Where(` (status = ? OR status = ?) AND collateral_loan_transactions.collateral_rate >= ? AND collateral_loan_transactions.type = ? `, wm.CollateralLoanStatusPayingInterest, wm.CollateralLoanStatusAccepted, amount, wm.CollateralLoanTransactionTypeReceive). Order("id desc"). Limit(limit). Offset(offset) if err := query.Find(&collateralLoans).Error; err != nil { return nil, errors.Wrap(err, "db.Find") } return collateralLoans, nil } func (cl *CollateralLoanDAO) FindAllCollect(page int, limit int) ([]*wm.CollateralLoan, error) { var ( models []*wm.CollateralLoan offset = page*limit - limit ) query := cl.db.Table("collateral_loans").Preload("Collateral").Preload("CollateralLoanInterestRate").Order("id asc"). Limit(limit).Offset(offset). Where(`collect_status = ? AND status != ?`, wm.CollateralLoanCollectStatusPending, wm.CollateralLoanStatusPending) if err := query.Find(&models).Error; err != nil { return nil, errors.Wrap(err, "db.Find") } return models, nil }
package main import ( "Fit-Time-Backend/controllers" "log" "net/http" ) func main() { // List of Routes http.HandleFunc("/", controllers.Hello) // Starts the http server err := http.ListenAndServe(":8090", nil) if err != nil { log.Println(err.Error()) } }
package p01 // Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func qs(a []int, left, right int) { if left >= right { return } i, j := left, right p := a[left] for i < j { for i < j && a[j] >= p { j-- } if i < j { a[i] = a[j] } for i < j && a[i] <= p { i++ } if i < j { a[j] = a[i] } } a[i] = p qs(a, left, i-1) qs(a, i+1, right) }
package robotmsg import ( "fmt" "github.com/grearter/rpa-agent/api" "github.com/sirupsen/logrus" ) // List 获取未Pulled的消息列表 func List() (messageAPIs []*api.RobotMessage, err error) { sql := fmt.Sprintf("SELECT * from %s WHERE pulled = false", tableName) rows, err := sqliteDB.Query(sql) if err != nil { logrus.Error("sqlite query err: %s, sql: %s", err.Error(), sql) return } for rows.Next() { m := &api.RobotMessage{ ID: 0, RobotID: "", Process: "", Level: "", Ct: 0, Content: "", Pulled: false, } if err := rows.Scan(&m.ID, &m.RobotID, &m.Process, &m.Level, &m.Ct, &m.Content, &m.Pulled); err != nil { logrus.Errorf("rows.Scan err: %s", err.Error()) return nil, err } messageAPIs = append(messageAPIs, m) } return }
package main import ( "fmt" ) func main() { si := []int{1, 2, 3, 4, 5, 6, 82} si2 := []int{1, 22, 3, 4, 76, 82} fmt.Println(funcao1(si...)) fmt.Println(funcao2(si2)) } func funcao1(x ...int) int { total := 0 for _, v := range x { total += v } return total } func funcao2(x []int) int { total := 0 for _, v := range x { total += v } return total }
package subscription import ( "context" watchv1 "github.com/syncromatics/kafmesh/internal/protos/kafmesh/watch/v1" "github.com/pkg/errors" "google.golang.org/grpc" ) // ClientFactory generates WatchClients for a pod type ClientFactory struct{} // Client gets a Watch client for an address func (f *ClientFactory) Client(ctx context.Context, url string) (Watcher, error) { con, err := grpc.DialContext(ctx, url, grpc.WithInsecure()) if err != nil { return nil, errors.Wrap(err, "failed to dial service") } go func() { <-ctx.Done() con.Close() }() return watchv1.NewWatchAPIClient(con), nil }
package server import ( "fmt" "log" "net" "net/http" _ "net/http/pprof" "runtime" "sync" "github.com/danmrichards/udpecho/internal/utils" ) // EchoServer is a UDP server that echos packets back to the sender. type EchoServer struct { c net.PacketConn workers int done chan struct{} wg sync.WaitGroup ps *http.Server } // Option is a functional option that modifies the echo server. type Option func(*EchoServer) // WithProfile enables HTTP profiling. func WithProfiling(addr string) Option { return func(es *EchoServer) { es.ps = &http.Server{ Addr: addr, } } } // NewEchoServer returns a new echo server configured with the given options. func NewEchoServer(addr string, opts ...Option) (es *EchoServer, err error) { // Configure to create as many workers as we have available threads. Leaving // 1 free for the main thread. Attempt to parallelise as much as we can. es = &EchoServer{ workers: runtime.GOMAXPROCS(0) - 1, done: make(chan struct{}), } for _, o := range opts { o(es) } // Free up a thread for profiling if enabled. if es.ps != nil { es.workers-- } es.c, err = net.ListenPacket("udp", addr) if err != nil { return nil, fmt.Errorf("listen: %w", err) } return es, nil } // Server starts the echo server. func (e *EchoServer) Serve() { // Start the profiling server if required. if e.ps != nil { e.wg.Add(1) go func() { defer e.wg.Done() log.Println("profiling:", e.ps.ListenAndServe()) }() } for i := 0; i < e.workers; i++ { e.wg.Add(1) go e.recv() } } // Stop stops the echo server. func (e *EchoServer) Stop() error { close(e.done) if err := e.c.Close(); err != nil { return err } // Stop the profiling server if required. if e.ps != nil { if err := e.ps.Close(); err != nil { return err } } e.wg.Wait() return nil } func (e *EchoServer) recv() { defer e.wg.Done() buf := make([]byte, 1024) for !utils.IsDone(e.done) { n, s, err := e.c.ReadFrom(buf) if err != nil { if utils.IsDone(e.done) { // Ignore the error if we've closed the connection. return } log.Println("read UDP:", err) return } if _, err = e.c.WriteTo(buf[:n], s); err != nil { log.Println("write UDP:", err) } } }
package main // EQR ... var EQR fc = func(en bool, args ...interface{}) []interface{} { return []interface{}{en && (args[0].(float64) == args[1].(float64))} } // GTR ... var GTR fc = func(en bool, args ...interface{}) []interface{} { return []interface{}{en && (args[0].(float64) > args[1].(float64))} } // LTR ... var LTR = func(en bool, args ...interface{}) []interface{} { return []interface{}{en && (args[0].(float64) < args[1].(float64))} } // GER ... var GER = func(en bool, args ...interface{}) []interface{} { return []interface{}{en && (args[0].(float64) >= args[1].(float64))} } // LER ... var LER = func(en bool, args ...interface{}) []interface{} { return []interface{}{en && (args[0].(float64) <= args[1].(float64))} }
package container type Container struct { Id string Root string Config *Config }
/* it's a-me! Today's task is simple: write a program, or a function that displays the idle small Mario sprite, from Super Mario Bros, on NES, over a blue background. Any kind of entry is valid as long as it displays those 12 * 16 pixels anywhere on the screen / window / browser. (EDIT: the displayed image can be scaled up if your language can't do pixel art. You can also output ASCII art or HTML art, but using the right colors.) Image (zoomed 400%): You must use the following colors: blue: #6B8CFF red: #B13425 green/brown: #6A6B04 orange: #E39D25 Shortest program (in number of characters) wins! Standard loopholes apply (especially, no network connexion allowed), but hardcoding and displaying an image file in your program is allowed. (entries using this trick will be rank separately) Here we go! */ package main import ( "bytes" "encoding/base64" "image" "image/color" "image/draw" "image/png" "os" ) func main() { png.Encode(os.Stdout, mario()) } func mario() *image.RGBA { const data = `iVBORw0KGgoAAAANSUhEUgAAAAwAAAAQAgMAAABfD3aUAAAADFBMVEX///+IcADYKAD8mDiryfk1AAAAAXRSTlMAQObYZgAAAExJREFUeF4NyKsNgDAYRtEbSE19g+pW/cchTdgBLEjyGUaAfTAoBKE87KESeM24diOWm5gzTUnU74HrIQwJk3HuI49WLi34biLwO/YBwCQWPKWzdq0AAAAASUVORK5CYII=` b, _ := base64.StdEncoding.DecodeString(data) m, _ := png.Decode(bytes.NewReader(b)) r := m.Bounds() p := image.NewRGBA(r) draw.Draw(p, r, m, image.ZP, draw.Src) for y := r.Min.Y; y < r.Max.Y; y++ { for x := r.Min.X; x < r.Max.X; x++ { c := p.RGBAAt(x, y) if c == (color.RGBA{}) { p.SetRGBA(x, y, color.RGBA{0x6b, 0x8c, 0xff, 0xff}) } } } return p }
package actions import ( "errors" "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" ) func GetCategoryTreeById(categoryId int64) (*model.CategoryTree, error) { query := connect.QueryMySQL{ QueryString: "WHERE parent_id=?", Args: []interface{}{categoryId}, } resolveChan := make(chan interface{}, 2) rejectChan := make(chan error) go func() { data, err := factories.FindCategory(&query) if err != nil { rejectChan <- err } else { resolveChan <- data } }() go func() { category, err := factories.FindCategoryById(categoryId) if err != nil { rejectChan <- err } resolveChan <- category }() var list []*model.Category var category *model.Category for i := 0; i < 2; i++ { select { case data := <-resolveChan: switch val := data.(type) { case *model.Category: category = val if category == nil { return nil, errors.New("category does not exists") } case []*model.Category: list = val } case err := <-rejectChan: return nil, err } } categoryTree := model.CategoryTree{ Category: category, } if len(list) > 0 { _, categoryTree.Children = factories.GetCategoryChildren(list, *categoryTree.Id) } return &categoryTree, nil }
package redix import ( "fmt" "github.com/garyburd/redigo/redis" ) type Connx struct { readWho string // "src" , "dest srcConn redis.Conn destConn redis.Conn } func NewConnx(srcConn redis.Conn, destConn redis.Conn, readWho string) *Connx { return &Connx{ readWho: readWho, srcConn: srcConn, destConn: destConn, } } func (c *Connx) Close() error { e1 := c.srcConn.Close() e2 := c.destConn.Close() if e1 == nil && e2 == nil { return nil } return fmt.Errorf("close err, dest err: %v src err: %v", e1, e2) } func (c *Connx) Err() error { return fmt.Errorf("dest err: %v, src err: %v", c.destConn.Err(), c.srcConn.Err()) } func (c *Connx) Do(commandName string, args ...interface{}) (reply interface{}, err error) { if isRead(commandName) { switch c.readWho { case "src": return c.srcConn.Do(commandName, args...) case "dest": return c.destConn.Do(commandName, args...) default: return c.srcConn.Do(commandName, args...) } } rs1, e := c.srcConn.Do(commandName, args...) rs2, e := c.destConn.Do(commandName, args...) switch c.readWho { case "src": return rs1, e case "dest": return rs2, e default: return rs1, e } } func (c *Connx) Send(commandName string, args ...interface{}) error { e1 := c.destConn.Send(commandName, args...) e2 := c.srcConn.Send(commandName, args...) if e1 == nil && e2 == nil { return nil } return fmt.Errorf("send err: dest err:%v src err: %v", e1, e2) } func (c *Connx) Flush() error { e1 := c.destConn.Flush() e2 := c.srcConn.Flush() if e1 == nil && e2 == nil { return nil } return fmt.Errorf("send err: dest err:%v src err: %v", e1, e2) } func (c *Connx) Receive() (reply interface{}, err error) { switch c.readWho { case "src": return c.srcConn.Receive() case "dest": return c.destConn.Receive() default: return c.srcConn.Receive() } }
package utils import ( _ "github.com/denisenkom/go-mssqldb" "github.com/jmoiron/sqlx" ) var Db *sqlx.DB //init函数先于main函数执行,初始化操作 func init() { var err error // connStr := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;", server, user, password, port, database) Db, err = sqlx.Open(`sqlserver`, `server=127.0.0.1;user id=sa;password=;port=1433;database=bings2;`) if err != nil { panic("连接错误") } if err = Db.Ping(); err != nil { panic("运行错误") } }
// Copyright 2019-2023 The sakuracloud_exporter Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package collector import ( "context" "errors" "testing" "time" "github.com/prometheus/client_golang/prometheus" "github.com/sacloud/iaas-api-go" "github.com/sacloud/iaas-api-go/types" "github.com/sacloud/sakuracloud_exporter/platform" "github.com/stretchr/testify/require" ) type dummyLocalRouterClient struct { find []*iaas.LocalRouter findErr error health *iaas.LocalRouterHealth healthErr error monitor *iaas.MonitorLocalRouterValue monitorErr error } func (d *dummyLocalRouterClient) Find(ctx context.Context) ([]*iaas.LocalRouter, error) { return d.find, d.findErr } func (d *dummyLocalRouterClient) Health(ctx context.Context, id types.ID) (*iaas.LocalRouterHealth, error) { return d.health, d.healthErr } func (d *dummyLocalRouterClient) Monitor(ctx context.Context, id types.ID, end time.Time) (*iaas.MonitorLocalRouterValue, error) { return d.monitor, d.monitorErr } func TestLocalRouterCollector_Describe(t *testing.T) { initLoggerAndErrors() c := NewLocalRouterCollector(context.Background(), testLogger, testErrors, &dummyLocalRouterClient{}) descs := collectDescs(c) require.Len(t, descs, len([]*prometheus.Desc{ c.Up, c.LocalRouterInfo, c.SwitchInfo, c.NetworkInfo, c.PeerInfo, c.PeerUp, c.StaticRouteInfo, c.ReceiveBytesPerSec, c.SendBytesPerSec, })) } func TestLocalRouterCollector_Collect(t *testing.T) { initLoggerAndErrors() c := NewLocalRouterCollector(context.Background(), testLogger, testErrors, nil) monitorTime := time.Unix(1, 0) cases := []struct { name string in platform.LocalRouterClient wantLogs []string wantErrCounter float64 wantMetrics []*collectedMetric }{ { name: "collector returns error", in: &dummyLocalRouterClient{ findErr: errors.New("dummy"), }, wantLogs: []string{`level=WARN msg="can't list localRouters" err=dummy`}, wantErrCounter: 1, wantMetrics: nil, }, { name: "empty result", in: &dummyLocalRouterClient{}, wantMetrics: nil, }, { name: "a local router", in: &dummyLocalRouterClient{ find: []*iaas.LocalRouter{ { ID: 101, Name: "local-router", Tags: types.Tags{"tag1", "tag2"}, Description: "desc", Availability: types.Availabilities.Available, Switch: &iaas.LocalRouterSwitch{ Code: "201", Category: "cloud", ZoneID: "is1a", }, Interface: &iaas.LocalRouterInterface{ VirtualIPAddress: "192.0.2.1", IPAddress: []string{"192.0.2.11", "192.0.2.12"}, NetworkMaskLen: 24, VRID: 100, }, StaticRoutes: []*iaas.LocalRouterStaticRoute{ { Prefix: "10.0.0.0/24", NextHop: "192.0.2.101", }, { Prefix: "10.0.1.0/24", NextHop: "192.0.2.102", }, }, }, }, }, wantMetrics: []*collectedMetric{ { desc: c.Up, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", }), }, { desc: c.LocalRouterInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "tags": ",tag1,tag2,", "description": "desc", }), }, { desc: c.SwitchInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "code": "201", "category": "cloud", "zone_id": "is1a", }), }, { desc: c.NetworkInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "vip": "192.0.2.1", "ipaddress1": "192.0.2.11", "ipaddress2": "192.0.2.12", "nw_mask_len": "24", "vrid": "100", }), }, { desc: c.StaticRouteInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "route_index": "0", "prefix": "10.0.0.0/24", "next_hop": "192.0.2.101", }), }, { desc: c.StaticRouteInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "route_index": "1", "prefix": "10.0.1.0/24", "next_hop": "192.0.2.102", }), }, }, }, { name: "a local router with peers", in: &dummyLocalRouterClient{ find: []*iaas.LocalRouter{ { ID: 101, Name: "local-router", Tags: types.Tags{"tag1", "tag2"}, Description: "desc", Availability: types.Availabilities.Available, Peers: []*iaas.LocalRouterPeer{ { ID: 201, SecretKey: "dummy", Enabled: true, Description: "desc201", }, { ID: 202, SecretKey: "dummy", Enabled: true, Description: "desc202", }, }, }, }, health: &iaas.LocalRouterHealth{ Peers: []*iaas.LocalRouterHealthPeer{ { ID: 201, Status: "UP", Routes: []string{"10.0.0.0/24"}, }, { ID: 202, Status: "UP", Routes: []string{"10.0.1.0/24"}, }, }, }, }, wantMetrics: []*collectedMetric{ { desc: c.Up, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", }), }, { desc: c.LocalRouterInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "tags": ",tag1,tag2,", "description": "desc", }), }, { desc: c.PeerUp, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "peer_index": "0", "peer_id": "201", }), }, { desc: c.PeerUp, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "peer_index": "1", "peer_id": "202", }), }, { desc: c.PeerInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "peer_index": "0", "peer_id": "201", "enabled": "1", "description": "desc201", }), }, { desc: c.PeerInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "peer_index": "1", "peer_id": "202", "enabled": "1", "description": "desc202", }), }, }, }, { name: "a local router with activities", in: &dummyLocalRouterClient{ find: []*iaas.LocalRouter{ { ID: 101, Name: "local-router", Tags: types.Tags{"tag1", "tag2"}, Description: "desc", Availability: types.Availabilities.Available, }, }, monitor: &iaas.MonitorLocalRouterValue{ Time: monitorTime, ReceiveBytesPerSec: 10, SendBytesPerSec: 20, }, }, wantMetrics: []*collectedMetric{ { desc: c.Up, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", }), }, { desc: c.LocalRouterInfo, metric: createGaugeMetric(1, map[string]string{ "id": "101", "name": "local-router", "tags": ",tag1,tag2,", "description": "desc", }), }, { desc: c.ReceiveBytesPerSec, metric: createGaugeWithTimestamp(10*8, map[string]string{ "id": "101", "name": "local-router", }, monitorTime), }, { desc: c.SendBytesPerSec, metric: createGaugeWithTimestamp(20*8, map[string]string{ "id": "101", "name": "local-router", }, monitorTime), }, }, }, } for _, tc := range cases { initLoggerAndErrors() c.logger = testLogger c.errors = testErrors c.client = tc.in collected, err := collectMetrics(c, "local_router") require.NoError(t, err) require.Equal(t, tc.wantLogs, collected.logged) require.Equal(t, tc.wantErrCounter, *collected.errors.Counter.Value) requireMetricsEqual(t, tc.wantMetrics, collected.collected) } }
package storage import ( "encoding/json" "fmt" "testing" "time" "github.com/stretchr/testify/suite" "go-gcs/src/config" "go-gcs/src/entity" "go-gcs/src/service" "go-gcs/src/service/googlecloud/storageprovider" ) type GoogleCloudStorageSuite struct { suite.Suite sp *service.Container } func (suite *GoogleCloudStorageSuite) SetupSuite() { cf := config.MustRead("../../../config/testing.json") suite.sp = service.New(cf) } func TestGoogleCloudStorageSuite(t *testing.T) { suite.Run(t, new(GoogleCloudStorageSuite)) } func (suite *GoogleCloudStorageSuite) TestSignURL() { path := "test/" fileName := "cat.jpg" contentType := "image/jpeg" method := "PUT" expires := time.Now().Add(time.Second * 60) url, err := SignURL(suite.sp, path, fileName, contentType, method, expires) suite.NoError(err) suite.NotEqual("", url) } func (suite *GoogleCloudStorageSuite) TestCreateGCSSingleSignedUrl() { userId := "myAwesomeId" fileName := "cat.jpg" contentType := "image/jpeg" payload := entity.SinglePayload{ To: "myAwesomeBuddyId", } p, err := json.MarshalIndent(payload, "", " ") suite.NotNil(p) suite.NoError(err) signedUrl, err := CreateGCSSingleSignedUrl(suite.sp, userId, fileName, contentType, string(p)) suite.NotNil(signedUrl) suite.NoError(err) } func (suite *GoogleCloudStorageSuite) TestCreateGCSGroupSignedUrl() { userId := "myAwesomeId" fileName := "cat.jpg" contentType := "image/jpeg" payload := entity.GroupPayload{ GroupId: "myAwesomeGroupId", } p, err := json.MarshalIndent(payload, "", " ") suite.NotNil(p) suite.NoError(err) signedUrl, err := CreateGCSGroupSignedUrl(suite.sp, userId, fileName, contentType, string(p)) suite.NotNil(signedUrl) suite.NoError(err) } func (suite *GoogleCloudStorageSuite) TestResizeGCSImage() { bucket := suite.sp.GoogleCloudStorage.Config.Bucket path := "test/cat.jpg" filePath := "../../../test/image/cat.jpg" err := suite.sp.GoogleCloudStorage.Upload(bucket, path, filePath) suite.NoError(err) url := fmt.Sprintf("%s/%s/%s", storageprovider.GoogleCloudStoragePublicBaseUrl, bucket, path) contentType := "image/jpeg" ri, err := ResizeGCSImage(suite.sp, url, contentType) suite.NotNil(ri) suite.NoError(err) }
package frontend import ( "encoding/json" "io/ioutil" "net/http" "path/filepath" "github.com/jim-minter/rp/pkg/api" ) func (f *frontend) postOpenShiftClusterCredentials(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Content-Type") != "application/json" { api.WriteError(w, http.StatusUnsupportedMediaType, api.CloudErrorCodeUnsupportedMediaType, "", "The content media type '%s' is not supported. Only 'application/json' is supported.", r.Header.Get("Content-Type")) return } body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, 1048576)) if err != nil { api.WriteError(w, http.StatusUnsupportedMediaType, api.CloudErrorCodeInvalidResource, "", "The resource definition is invalid.") return } if !json.Valid(body) { api.WriteError(w, http.StatusBadRequest, api.CloudErrorCodeInvalidRequestContent, "", "The request content was invalid and could not be deserialized: %q.", err) return } f.get(w, r, filepath.Dir(r.URL.Path), "OpenShiftClusterCredentials") }
package queue import l "list" // Queue implements a basic queue // Enqueue / Dequeue type Queue struct { list l.List } // Enqueue enqueues a value func (q *Queue) Enqueue(value int) { q.list.InsertAt(value, 1) } // Dequeue dequeues a value func (q *Queue) Dequeue() int { dequeued := q.Back() q.list.DeleteAt(q.list.Length()) return dequeued } // Front returns value at front func (q *Queue) Front() int { return q.list.GetAt(1) } // Back returns value at back func (q *Queue) Back() int { return q.list.GetAt(q.list.Length()) }
/* * @lc app=leetcode.cn id=154 lang=golang * * [154] 寻找旋转排序数组中的最小值 II */ package solution // @lc code=start func findMin(nums []int) int { head, tail := 0, len(nums)-1 for head < tail { mid := (head + tail) / 2 if nums[mid] < nums[tail] { tail = mid } else if nums[mid] > nums[tail] { head = mid + 1 } else { tail-- } } return nums[head] } // @lc code=end
package usecase import ( "errors" "github.com/huf0813/pembukuan_tk/entity" "github.com/huf0813/pembukuan_tk/repository/sqlite" ) type CustomerUseCase struct { CustomerRepo sqlite.CustomerRepo } type CustomerUseCaseInterface interface { GetCustomers() ([]entity.Customer, error) AddCustomerValidation(name, phone, email, address string) error AddCustomer(name, phone, email, address string) (*entity.Customer, error) EditCustomerValidation(name, phone, email, address string, customerID int) error EditCustomer(name, phone, email, address string, customerID int) (*entity.Customer, error) } func (cuc *CustomerUseCase) GetCustomers() ([]entity.Customer, error) { result, err := cuc.CustomerRepo.GetCustomers() if err != nil { return nil, err } return result, nil } func (cuc *CustomerUseCase) AddCustomerValidation(name, phone, email, address string) error { if name == "" || phone == "" || email == "" || address == "" { return errors.New("fields cannot be empty") } return nil } func (cuc *CustomerUseCase) AddCustomer(name, phone, email, address string) (*entity.Customer, error) { if err := cuc.AddCustomerValidation(name, phone, email, address); err != nil { return nil, err } result, err := cuc.CustomerRepo.AddCustomer(name, phone, email, address) if err != nil { return nil, err } return result, nil } func (cuc *CustomerUseCase) EditCustomerValidation(name, phone, email, address string, customerID int) error { if name == "" || phone == "" || email == "" || address == "" || customerID == 0 { return errors.New("fields cannot be empty") } return nil } func (cuc *CustomerUseCase) EditCustomer(name, phone, email, address string, customerID int) (*entity.Customer, error) { if err := cuc.EditCustomerValidation(name, phone, email, address, customerID); err != nil { return nil, err } result, err := cuc.CustomerRepo.EditCustomer(name, phone, email, address, customerID) if err != nil { return nil, err } return result, nil } func (cuc *CustomerUseCase) DeleteCustomer(customerID int) (string, error) { result, err := cuc.CustomerRepo.DeleteCustomer(customerID) if err != nil { return "", err } return result, nil }
package system_test import ( "testing" "github.com/kumahq/kuma/pkg/test" ) func TestSystem(t *testing.T) { test.RunSpecs(t, "System Suite") }
package main import "fmt" // struct pengganti class pada OOP type Siswa struct { nama, kelas string umur int } // menambahkan method ke struct func (s Siswa) getNama() (nama string) { // (s Siswa) menandakan method ini milik Siswa nama = fmt.Sprintf("Nama Saya %v \n", s.nama); // dan variabel s menjadi cara mengakses properti struct return; } func (s Siswa) getKelas() (kelas string) { kelas = fmt.Sprintf("Saya kelas %v \n", s.kelas); return; } func (s Siswa) setNama(nama string) { // properti struct tidak bisa diubah lewat method dan hanya berpengaruh pada struct yang dimethod tersebut s.nama = nama; } func (s *Siswa) setKelas(kelas string) { // jadi kalau ingin merubah nilai propertinya, wajib pakai pointer atau bintang dinama structnya seperti yg disamping s.kelas = kelas; } func main() { var madam = Siswa{"Madam Retno", "XII-1", 12}; var madam2 = struct { // penulisan struct secara langsung di variabel nama string kelas string }{ nama: "Madam", kelas: "satu", }; fmt.Println(madam2.nama); fmt.Println(madam2.kelas); fmt.Println(madam.getNama()); fmt.Println(madam.getKelas()); madam.setNama("Madam Baru"); // yang ini tidak berpengaruh karena tidak pakai pointer fmt.Println(madam.getNama()); madam.setKelas("XII Baru"); // yang berpengaruh karena tidak pakai pointer fmt.Println(madam.getKelas()); }
// Copyright (c) 2020 Zededa, Inc. // SPDX-License-Identifier: Apache-2.0 package utils import ( "errors" "fmt" "os" "github.com/lf-edge/eve/pkg/pillar/base" "github.com/lf-edge/eve/pkg/pillar/cas" "github.com/lf-edge/eve/pkg/pillar/containerd" "github.com/lf-edge/eve/pkg/pillar/diskmetrics" "github.com/lf-edge/eve/pkg/pillar/zfs" ) // GetVolumeSize returns the actual and maximum size of the volume // plus a DiskType and a DirtyFlag func GetVolumeSize(log *base.LogObject, casClient cas.CAS, fileLocation string) (uint64, uint64, string, bool, error) { info, err := os.Stat(fileLocation) if err != nil { return 0, 0, "", false, fmt.Errorf("GetVolumeSize failed for %s: %v", fileLocation, err) } // Assume this is a container if info.IsDir() { var size uint64 snapshotID := containerd.GetSnapshotID(fileLocation) su, err := casClient.SnapshotUsage(snapshotID, true) if err == nil { size = uint64(su) } else { // we did not create snapshot yet log.Warnf("GetVolumeSize: Failed get snapshot usage: %s for %s. Error %s", snapshotID, fileLocation, err) size, err = diskmetrics.SizeFromDir(log, fileLocation) } return size, size, "CONTAINER", false, err } if info.Mode()&os.ModeDevice != 0 { //Assume this is zfs device imgInfo, err := zfs.GetZFSVolumeInfo(fileLocation) if err != nil { errStr := fmt.Sprintf("GetVolumeSize/GetZFSInfo failed for %s: %v", fileLocation, err) return 0, 0, "", false, errors.New(errStr) } return imgInfo.ActualSize, imgInfo.VirtualSize, imgInfo.Format, imgInfo.DirtyFlag, nil } imgInfo, err := diskmetrics.GetImgInfo(log, fileLocation) if err != nil { errStr := fmt.Sprintf("GetVolumeSize/GetImgInfo failed for %s: %v", fileLocation, err) return 0, 0, "", false, errors.New(errStr) } return imgInfo.ActualSize, imgInfo.VirtualSize, imgInfo.Format, imgInfo.DirtyFlag, nil }
package back import ( "log" ) const ( SC_URL = "https://docs.google.com/spreadsheets/d/1ud6IZFjoT0Hyvh6TjbGq7czDezs9M3ODqEKysQ04h8E/pub?gid=0&single=true&output=csv" ) func SiteCopy() ([][]string, error) { data, err := readCSVFromUrl(SC_URL) if err != nil { log.Println(err) return nil, err } return data, nil }
package service import ( "io" "project/app/admin/models" "project/app/admin/models/bo" "project/app/admin/models/cache" "project/app/admin/models/dto" cache2 "project/common/cache" "project/utils" "go.uber.org/zap" ) type Dept struct { } func (d *Dept) SelectDeptList(de *dto.SelectDeptDto, orderData []bo.Order) (data *bo.SelectDeptListBo, err error) { // 声明所需变量,开辟空间 data = new(bo.SelectDeptListBo) deptList := new([]bo.RecordDept) dept := new(models.SysDept) sysDeptList := new([]models.SysDept) var count int64 // 数据查询 判断条件 tag := de.Name != "" || de.StartTime != 0 || de.EndTime != 0 // 进dao层 if tag { // 模糊查询直接过数据库 sysDeptList, count, err = dept.SelectDeptListByNameTime(de, orderData) } else { // 非模糊查询先过缓存 *deptList, err = cache.GetRedisDeptByPid(de.Pid) if err == nil && len(*deptList) > 0 { // 封装paging data.Orders = orderData data.Current = de.Current data.Total = len(*deptList) data.Size = de.Size data.Pages = utils.PagesCount(data.Total, de.Size) data.Records = *deptList return } // 缓存有问题 if err != nil { zap.L().Error("GetRedisDeptByPid failed", zap.Error(err)) err = nil } _ = cache.DeleteRedisDeptByPid(de.Pid) sysDeptList, count, err = dept.SelectDeptListByPid(de, orderData) } // 数据库错误 if err != nil { zap.L().Error("SelectDeptDao Select failed", zap.Error(err)) return } // 封装bo数据传输对象 if len(*sysDeptList) > 0 { deptList = modelToBo(sysDeptList) // 子部门缓存 if !tag { _ = cache.DeleteRedisDeptByPid(de.Pid) err = cache.SetRedisDeptByPid(de.Pid, deptList) if err != nil { zap.L().Error("SetRedisDeptByPid failed", zap.Error(err)) err = nil } err = cache.SetRedisDeptList(deptList) if err != nil { zap.L().Error("SetRedisDeptList failed", zap.Error(err)) err = nil } } // 封装paging data.Orders = orderData data.Current = de.Current data.Total = int(count) data.Size = de.Size data.Pages = utils.PagesCount(data.Total, de.Size) data.Records = *deptList } return } // 新增部门 func (d *Dept) InsertDept(de *dto.InsertDeptDto, userId int) (count int64, err error) { // 实例化 dept := new(models.SysDept) dept.DeptSort = de.DeptSort dept.Enabled = utils.StrBoolIntoByte(de.Enabled) dept.Pid = *de.Pid dept.Name = de.Name dept.SubCount = *de.SubCount dept.CreateBy = userId dept.UpdateBy = userId // 判断该部门是否存在 count, err = dept.GetDeptByPidName() if count > 0 { zap.L().Error("InsertDept Failed 该部门已存在不能创建") return } // 删除缓存 err = cache.DeleteRedisDeptByPid(*de.Pid) if err != nil { return } // 存入数据库 err = dept.InsertDept() return } // 修改部门 func (d *Dept) UpdateDept(de *dto.UpdateDeptDto) (count int64, err error) { dept := new(models.SysDept) var pids []int var ids []int // 查看部门是否存在 dept.ID = de.ID err = dept.GetDeptById() if err != nil { zap.L().Error("UpdateDept GetDeptById Failed", zap.Error(err)) return } // 查看要修改的部门是否存在 dept.Pid = *de.Pid dept.Name = de.Name count, err = dept.GetDeptByPidName() if err != nil { zap.L().Error("UpdateDept GetDeptByPidName Failed", zap.Error(err)) return } if count > 0 { zap.L().Error("UpdateDept Failed 该部门已存在不能更改") return } ids, err = dept.GetDeptUserListById() if err != nil { zap.L().Error("UpdateDept GetDeptUserListById Failed", zap.Error(err)) return } // 删除缓存 err = cache.DelAllUserCenterCache() if err != nil { zap.L().Error("UpdateDept DelAllUserCenterCache Failed", zap.Error(err)) return } err = cache.DelAllUserRecordsCache() if err != nil { zap.L().Error("UpdateDept DelAllUserRecordsCache Failed", zap.Error(err)) return } err = cache2.DelUserCacheById(cache2.KeyUserDept, &ids) if err != nil { zap.L().Error("UpdateDept DelUserCacheById Failed", zap.Error(err)) return } pids = append(pids, *de.Pid) pids = append(pids, dept.Pid) err = cache.DeleteRedisDeptByPids(pids) if err != nil { zap.L().Error("DeleteDept GetPidList Failed", zap.Error(err)) return } err = cache.DeleteRedisDeptByPid(*de.Pid) if err != nil { zap.L().Error("DeleteDept GetPidList Failed", zap.Error(err)) return } err = cache.DeleteRedisDeptById(de.ID) if err != nil { zap.L().Error("DeleteDept GetPidList Failed", zap.Error(err)) return } // 持久层 err = dept.UpdateDept(de) return } // 删除部门 func (d *Dept) DeleteDept(ids *[]int, userId int) (count int64, err error) { dept := new(models.SysDept) // 获取pid集合 pids, err := dept.GetPidList(ids) if err != nil { zap.L().Error("DeleteDept GetPidList Failed", zap.Error(err)) return } // 删除缓存 err = cache.DeleteRedisDeptByPids(*pids) if err != nil { zap.L().Error("DeleteDept DeleteRedisDeptByPids Failed", zap.Error(err)) return } err = cache.DeleteRedisDeptByPids(*ids) if err != nil { zap.L().Error("DeleteDept DeleteRedisDeptByPids Failed", zap.Error(err)) return } err = cache.DeleteRedisDeptByIds(*ids) if err != nil { zap.L().Error("DeleteDept DeleteRedisDeptByIds Failed", zap.Error(err)) return } count, err = dept.DeleteDept(ids, userId) return } func (d *Dept) SuperiorDept(ids *[]int) (deptList *[]bo.RecordDept, err error) { // 数据查询 deptList = new([]bo.RecordDept) sysDeptList := new([]models.SysDept) dept := new(models.SysDept) // 非模糊查询先过缓存 *deptList, err = cache.GetRedisDeptByPid(0) if err == nil && len(*deptList) > 0 { return } // 缓存有问题 if err != nil { zap.L().Error("GetRedisDeptByPid failed", zap.Error(err)) err = nil } _ = cache.DeleteRedisDeptByPid(0) sysDeptList, err = dept.SuperiorDept(ids) if err != nil { return } // 封装bo数据传输对象 if len(*sysDeptList) > 0 { deptList = modelToBo(sysDeptList) // 子部门缓存 _ = cache.DeleteRedisDeptByPid(0) err = cache.SetRedisDeptByPid(0, deptList) if err != nil { zap.L().Error("SetRedisDeptByPid failed", zap.Error(err)) err = nil } err = cache.SetRedisDeptList(deptList) if err != nil { zap.L().Error("SetRedisDeptList failed", zap.Error(err)) err = nil } } return } func (d *Dept) DownloadDeptList(dt *dto.SelectDeptDto, orderJson []bo.Order) (content io.ReadSeeker, err error) { var res []interface{} dept := new(models.SysDept) // 数据库查询数据 sysDeptList, err := dept.DownloadDept(dt, orderJson) // 返回文件数据 for _, dept := range sysDeptList { res = append(res, &bo.DownloadDeptList{ Name: dept.Name, Enabled: utils.ByteEnabledToString(dept.Enabled), CreateTime: utils.UnixTimeToString(dept.CreateTime), }) } // 生成excel content = utils.ToExcel([]string{`部门名称`, `部门状态`, `创建日期`}, res) return } func modelToBo(sysDeptList *[]models.SysDept) (deptList *[]bo.RecordDept) { var r bo.RecordDept deptList = new([]bo.RecordDept) for _, value := range *sysDeptList { r.ID = value.ID r.Pid = value.Pid r.Name = value.Name r.Label = value.Name r.Enabled = utils.ByteIntoBool(value.Enabled) if value.SubCount > 0 { r.HasChildren = true r.Leaf = false } else { r.HasChildren = false r.Leaf = true } r.CreateTime = value.CreateTime r.CreateBy = value.CreateBy r.UpdateTime = value.UpdateTime r.UpdateBy = value.UpdateBy // append *deptList = append(*deptList, r) } return }
package gosnowth import ( "bytes" "testing" ) func TestScanMetricName(t *testing.T) { t.Parallel() cases := []struct { input string // input tok scanToken // token lit string // metric name literal }{ { input: "testing", tok: tokenMetric, lit: "testing", }, { input: "testing*", tok: tokenMetric, lit: "testing*", }, { input: "testing|ST[blah:blah]", tok: tokenMetric, lit: "testing", }, { input: "t|esting|ST[blah:blah]", tok: tokenMetric, lit: "t|esting", }, { input: "t|Sesting|ST[blah:blah]", tok: tokenMetric, lit: "t|Sesting", }, { input: "tel|a|M|Ssting|ST[blah:blah]", tok: tokenMetric, lit: "tel|a|M|Ssting", }, { input: "testing|ST[blah:blah]", tok: tokenMetric, lit: "testing", }, { input: "testing|MT{test:test}", tok: tokenMetric, lit: "testing", }, { input: "testing|ST[blah:blah]|MT{test:test}", tok: tokenMetric, lit: "testing", }, } for _, c := range cases { buf := bytes.NewBufferString(c.input) s := newMetricScanner(buf) tok, lit, err := s.scanMetricName() if err != nil { t.Fatal(err) } if tok != c.tok { t.Error("failed to find the metric ident") } if lit != c.lit { t.Error("incorrect literal scanned: ", c.lit, lit) } } } func TestScanTagSep(t *testing.T) { t.Parallel() stBuf := bytes.NewBufferString("|ST[blah:blah]") s := newMetricScanner(stBuf) tok, lit, err := s.peekTagSep() if err != nil { t.Fatal(err) } if tok != tokenStreamTag { t.Error("expected stream tag separator") } if lit != "|ST" { t.Error("incorrect literal scanned: ", lit) } tok, lit, err = s.scanTagSep() if err != nil { t.Fatal(err) } if tok != tokenStreamTag { t.Error("expected stream tag separator") } if lit != "|ST" { t.Error("incorrect literal scanned: ", lit) } mtBuf := bytes.NewBufferString("|MT{blah:blah}") s = newMetricScanner(mtBuf) tok, lit, err = s.peekTagSep() if err != nil { t.Fatal(err) } if tok != tokenMeasurementTag { t.Error("expected measurement tag separator") } if lit != "|MT" { t.Error("incorrect literal scanned: ", lit) } tok, lit, err = s.scanTagSep() if err != nil { t.Fatal(err) } if tok != tokenMeasurementTag { t.Error("expected measurement tag separator") } if lit != "|MT" { t.Error("incorrect literal scanned: ", lit) } } func TestMetricParser(t *testing.T) { t.Parallel() cases := []struct { input string // input numST int // number of derived stream tags numMT int // number of derived measurement tags lit string // metric name literal }{ { input: "testing", numST: 0, numMT: 0, lit: "testing", }, { input: "testing*", numST: 0, numMT: 0, lit: "testing*", }, { input: "testing|ST[blah:blah]", numST: 1, numMT: 0, lit: "testing", }, { input: "t|esting|ST[blah:blah]", numST: 1, numMT: 0, lit: "t|esting", }, { input: "t|Sesting|ST[blah:blah]", numST: 1, numMT: 0, lit: "t|Sesting", }, { input: "tel|a|M|Ssting|ST[blah:blah]", numST: 1, numMT: 0, lit: "tel|a|M|Ssting", }, { input: "testing|ST[blah:blah]", numST: 1, numMT: 0, lit: "testing", }, { input: "testing|ST[blah:blah,blah1:blah,blah2:blah]", numST: 3, numMT: 0, lit: "testing", }, { input: `testing|ST[b"QUFB":blah,blah1:b"QkJCQgo=",b"YWFh":b"YmJi"]`, numST: 3, numMT: 0, lit: "testing", }, { input: "testing|ST[blah:blah:blah:blah]", numST: 1, numMT: 0, lit: "testing", }, { input: "testing|ST[blah:blah]|ST[blah:blah]", numST: 2, numMT: 0, lit: "testing", }, { input: "testing|MT{blah:blah}", numST: 0, numMT: 1, lit: "testing", }, { input: "testing|ST[blah:blah]|MT{blah:blah}", numST: 1, numMT: 1, lit: "testing", }, { input: "testing|ST[blah:blah]|MT{blah:blah}|ST[blah:blah]", numST: 2, numMT: 1, lit: "testing", }, { input: `testing|ST["blah:|ST[]":blah]|MT{blah:",}:|MTblah"}`, numST: 1, numMT: 1, lit: "testing", }, { input: `testing|ST["blah:|ST[]":blah]|MT{blah:",}:|MTblah"}`, numST: 1, numMT: 1, lit: "testing", }, { input: `testing|ST["b:|ST[]":b]|MT{b:",}:|MTb"}|ST[a:b]|MT{c:d}`, numST: 2, numMT: 2, lit: "testing", }, { input: `testing|ST["quote\"slash\\":bar]`, numST: 1, numMT: 0, lit: "testing", }, { input: `testing|ST["quote\"slash\\":bar]|MT{"q\\\"\\:":bar}`, numST: 1, numMT: 1, lit: "testing", }, } for _, c := range cases { buf := bytes.NewBufferString(c.input) p := NewMetricParser(buf) metricName, err := p.Parse() if err != nil { t.Fatal("failed to parse the metric name", err) } if metricName.Name != c.lit { t.Error("incorrect literal scanned: ", c.lit, metricName.Name) } if metricName.CanonicalName != c.input { t.Error("incorrect canonical: ", c.input, metricName.CanonicalName) } if len(metricName.StreamTags) != c.numST { t.Error("incorrect number of stream tags: ", c.numST, len(metricName.StreamTags)) } if len(metricName.MeasurementTags) != c.numMT { t.Error("incorrect number of measurement tags: ", c.numMT, len(metricName.MeasurementTags)) } } } func TestMetricParserComplex(t *testing.T) { t.Parallel() mn, err := ParseMetricName("test|ST[sri:sri:spc:compute::" + "stackable-cloud:vm/0bce9aef-8186-44c9-a73d-33723173b2c6]") if err != nil { t.Fatal("failed to parse the metric name") } if mn.Name != "test" { t.Errorf("Expected name: test, got: %v", mn.Name) } exp := "sri:spc:compute::stackable-cloud:vm" + "/0bce9aef-8186-44c9-a73d-33723173b2c6" if mn.StreamTags[0].Value != exp { t.Errorf("Expected stream tag value: %v, got: %v", exp, mn.StreamTags[0].Value) } }
package middleware import ( "fmt" "github.com/juju/errgo" "log" "net/http" "os" "runtime/debug" ) type Recovery struct { Logger *log.Logger } func NewRecovery() *Recovery { return &Recovery{ Logger: log.New(os.Stdout, "[klask] ", 0), } } func (self *Recovery) ServeHTTP( res http.ResponseWriter, req *http.Request, next http.HandlerFunc, ) { defer func() { err := recover() if err == nil { return } res.WriteHeader(http.StatusInternalServerError) stack := debug.Stack() // send stack to server logger format := "PANIC: %s\n%s" self.Logger.Printf(format, err, stack) // respond with more informative stack for err != nil { switch e := err.(type) { case *errgo.Err: fmt.Fprintf(res, "in %s\n", e.Location()) if msg := e.Message(); len(msg) > 0 { fmt.Fprintf(res, " %s\n", e.Message()) } err = e.Underlying() case error: fmt.Fprintf(res, "%s", e.Error()) err = nil } } return }() next(res, req) }
package second import "fmt" type GetName interface { getName() string } type Student struct { Name string Age int ID string } type Teacher struct { Name string } func (s Student) getName() string { return s.Name + "@gmail.com" } func (t Teacher) getName() string { return t.Name + "@gmail.com" } //export secondIntf func SecondIntf() { s := Student{ Name: "Parit", Age: 29, ID: "123ty", } t := Teacher{ Name: "Sharma", } str := GetName.getName(s) fmt.Println("Student :", str) str = GetName.getName(t) fmt.Println("Teacher :", str) }
// Copyright 2023 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package asyncloaddata import ( "testing" "github.com/stretchr/testify/require" ) func TestProgressMarshalUnmarshal(t *testing.T) { p := NewProgress(true) require.Nil(t, p.PhysicalImportProgress) p.SourceFileSize = 123 p.LoadedFileSize.Store(456) p.LoadedRowCnt.Store(789) s := p.String() require.Equal(t, `{"SourceFileSize":123,"LoadedFileSize":456,"LoadedRowCnt":789}`, s) s2 := `{"SourceFileSize":111,"LoadedFileSize":222,"LoadedRowCnt":333}` p2, err := ProgressFromJSON([]byte(s2)) require.NoError(t, err) require.Equal(t, int64(111), p2.SourceFileSize) require.Equal(t, int64(222), p2.LoadedFileSize.Load()) require.Equal(t, uint64(333), p2.LoadedRowCnt.Load()) p = NewProgress(false) require.Nil(t, p.LogicalImportProgress) p.SourceFileSize = 123 p.ReadRowCnt.Store(790) p.EncodeFileSize.Store(100) p.LoadedRowCnt.Store(789) s = p.String() require.Equal(t, `{"SourceFileSize":123,"ReadRowCnt":790,"EncodeFileSize":100,"LoadedRowCnt":789}`, s) s2 = `{"SourceFileSize":111,"ReadRowCnt":790,"EncodeFileSize":222,"LoadedRowCnt":333}` p2, err = ProgressFromJSON([]byte(s2)) require.NoError(t, err) require.Equal(t, int64(111), p2.SourceFileSize) require.Equal(t, uint64(790), p2.ReadRowCnt.Load()) require.Equal(t, int64(222), p2.EncodeFileSize.Load()) require.Equal(t, uint64(333), p2.LoadedRowCnt.Load()) }
package solutions import "math" /* * @lc app=leetcode id=7 lang=golang * * [7] Reverse Integer */ /* Your runtime beats 100 % of golang submissions Your memory usage beats 56.43 % of golang submissions (2.1 MB) */ // @lc code=start func reverse(x int) int { sum := 0 for x != 0 { n := x % 10 if sum > math.MaxInt32/10 || (sum == math.MaxInt32/10 && n > 7) || (sum < math.MinInt32/10) || (sum == math.MinInt32/10 && n < -8) { return 0 } sum = sum*10 + n x /= 10 } return sum } // @lc code=end
package main import "fmt" // 59. 螺旋矩阵 II // 给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 // 示例: // 输入: 3 // 输出: // [ // [ 1, 2, 3 ], // [ 8, 9, 4 ], // [ 7, 6, 5 ] // ] // https://leetcode-cn.com/problems/spiral-matrix-ii/ func main() { fmt.Println(generateMatrix(3)) fmt.Println(generateMatrix2(3)) } // 法一:暴力法 func generateMatrix(n int) (result [][]int) { result = make([][]int, n) for k := range result { result[k] = make([]int, n) } max := n * n left, right, top, bottom := 0, n-1, 0, n-1 num := 1 for num <= max { // left=>right for i := left; i <= right; i, num = i+1, num+1 { result[top][i] = num } top++ // top => bottom for i := top; i <= bottom; i, num = i+1, num+1 { result[i][right] = num } right-- // right=>left for i := right; i >= left; i, num = i-1, num+1 { result[bottom][i] = num } bottom-- // bottom=>top for i := bottom; i >= top; i, num = i-1, num+1 { result[i][left] = num } left++ } return result } // 法二:归纳法 func generateMatrix2(n int) (result [][]int) { result = make([][]int, n) for k := range result { result[k] = make([]int, n) } max := n * n num := 1 i, j := 0, 0 di, dj := 0, 1 // result[i][j]距下一个点的距离 for num <= max { result[i][j] = num nexti, nextj := (i+di)%n, (j+dj)%n if nextj < 0 { // handle bottom=>top index out of range nextj += n } // left=>right di:0,dj:1 // top => bottom di:1,dj:0 // right=>left di:0,dj:-1 // bottom=>top di:-1,dj:0 if result[nexti][nextj] > 0 { // 说明本行或本列已经处理完毕 di, dj = dj, -di } i += di j += dj num++ } return result }
// Copyright 2020 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package parser_test import ( "testing" "github.com/pingcap/tidb/parser" "github.com/pingcap/tidb/parser/ast" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/parser/mysql" "github.com/stretchr/testify/require" ) func TestParseHint(t *testing.T) { testCases := []struct { input string mode mysql.SQLMode output []*ast.TableOptimizerHint errs []string }{ { input: "", errs: []string{`Optimizer hint syntax error at line 1 `}, }, { input: "MEMORY_QUOTA(8 MB) MEMORY_QUOTA(6 GB)", output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("MEMORY_QUOTA"), HintData: int64(8 * 1024 * 1024), }, { HintName: model.NewCIStr("MEMORY_QUOTA"), HintData: int64(6 * 1024 * 1024 * 1024), }, }, }, { input: "QB_NAME(qb1) QB_NAME(`qb2`), QB_NAME(TRUE) QB_NAME(\"ANSI quoted\") QB_NAME(_utf8), QB_NAME(0b10) QB_NAME(0x1a)", mode: mysql.ModeANSIQuotes, output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("QB_NAME"), QBName: model.NewCIStr("qb1"), }, { HintName: model.NewCIStr("QB_NAME"), QBName: model.NewCIStr("qb2"), }, { HintName: model.NewCIStr("QB_NAME"), QBName: model.NewCIStr("TRUE"), }, { HintName: model.NewCIStr("QB_NAME"), QBName: model.NewCIStr("ANSI quoted"), }, { HintName: model.NewCIStr("QB_NAME"), QBName: model.NewCIStr("_utf8"), }, { HintName: model.NewCIStr("QB_NAME"), QBName: model.NewCIStr("0b10"), }, { HintName: model.NewCIStr("QB_NAME"), QBName: model.NewCIStr("0x1a"), }, }, }, { input: "QB_NAME(1)", errs: []string{`Optimizer hint syntax error at line 1 `}, }, { input: "QB_NAME('string literal')", errs: []string{`Optimizer hint syntax error at line 1 `}, }, { input: "QB_NAME(many identifiers)", errs: []string{`Optimizer hint syntax error at line 1 `}, }, { input: "QB_NAME(@qb1)", errs: []string{`Optimizer hint syntax error at line 1 `}, }, { input: "QB_NAME(b'10')", errs: []string{ `Cannot use bit-value literal`, `Optimizer hint syntax error at line 1 `, }, }, { input: "QB_NAME(x'1a')", errs: []string{ `Cannot use hexadecimal literal`, `Optimizer hint syntax error at line 1 `, }, }, { input: "JOIN_FIXED_ORDER() BKA()", errs: []string{ `Optimizer hint JOIN_FIXED_ORDER is not supported`, `Optimizer hint BKA is not supported`, }, }, { input: "HASH_JOIN() TIDB_HJ(@qb1) INL_JOIN(x, `y y`.z) MERGE_JOIN(w@`First QB`)", output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("HASH_JOIN"), }, { HintName: model.NewCIStr("TIDB_HJ"), QBName: model.NewCIStr("qb1"), }, { HintName: model.NewCIStr("INL_JOIN"), Tables: []ast.HintTable{ {TableName: model.NewCIStr("x")}, {DBName: model.NewCIStr("y y"), TableName: model.NewCIStr("z")}, }, }, { HintName: model.NewCIStr("MERGE_JOIN"), Tables: []ast.HintTable{ {TableName: model.NewCIStr("w"), QBName: model.NewCIStr("First QB")}, }, }, }, }, { input: "USE_INDEX_MERGE(@qb1 tbl1 x, y, z) IGNORE_INDEX(tbl2@qb2) USE_INDEX(tbl3 PRIMARY) FORCE_INDEX(tbl4@qb3 c1)", output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("USE_INDEX_MERGE"), Tables: []ast.HintTable{{TableName: model.NewCIStr("tbl1")}}, QBName: model.NewCIStr("qb1"), Indexes: []model.CIStr{model.NewCIStr("x"), model.NewCIStr("y"), model.NewCIStr("z")}, }, { HintName: model.NewCIStr("IGNORE_INDEX"), Tables: []ast.HintTable{{TableName: model.NewCIStr("tbl2"), QBName: model.NewCIStr("qb2")}}, }, { HintName: model.NewCIStr("USE_INDEX"), Tables: []ast.HintTable{{TableName: model.NewCIStr("tbl3")}}, Indexes: []model.CIStr{model.NewCIStr("PRIMARY")}, }, { HintName: model.NewCIStr("FORCE_INDEX"), Tables: []ast.HintTable{{TableName: model.NewCIStr("tbl4"), QBName: model.NewCIStr("qb3")}}, Indexes: []model.CIStr{model.NewCIStr("c1")}, }, }, }, { input: "USE_INDEX(@qb1 tbl1 partition(p0) x) USE_INDEX_MERGE(@qb2 tbl2@qb2 partition(p0, p1) x, y, z)", output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("USE_INDEX"), Tables: []ast.HintTable{{ TableName: model.NewCIStr("tbl1"), PartitionList: []model.CIStr{model.NewCIStr("p0")}, }}, QBName: model.NewCIStr("qb1"), Indexes: []model.CIStr{model.NewCIStr("x")}, }, { HintName: model.NewCIStr("USE_INDEX_MERGE"), Tables: []ast.HintTable{{ TableName: model.NewCIStr("tbl2"), QBName: model.NewCIStr("qb2"), PartitionList: []model.CIStr{model.NewCIStr("p0"), model.NewCIStr("p1")}, }}, QBName: model.NewCIStr("qb2"), Indexes: []model.CIStr{model.NewCIStr("x"), model.NewCIStr("y"), model.NewCIStr("z")}, }, }, }, { input: `SET_VAR(sbs = 16M) SET_VAR(fkc=OFF) SET_VAR(os="mcb=off") set_var(abc=1) set_var(os2='mcb2=off')`, output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("SET_VAR"), HintData: ast.HintSetVar{ VarName: "sbs", Value: "16M", }, }, { HintName: model.NewCIStr("SET_VAR"), HintData: ast.HintSetVar{ VarName: "fkc", Value: "OFF", }, }, { HintName: model.NewCIStr("SET_VAR"), HintData: ast.HintSetVar{ VarName: "os", Value: "mcb=off", }, }, { HintName: model.NewCIStr("set_var"), HintData: ast.HintSetVar{ VarName: "abc", Value: "1", }, }, { HintName: model.NewCIStr("set_var"), HintData: ast.HintSetVar{ VarName: "os2", Value: "mcb2=off", }, }, }, }, { input: "USE_TOJA(TRUE) IGNORE_PLAN_CACHE() USE_CASCADES(TRUE) QUERY_TYPE(@qb1 OLAP) QUERY_TYPE(OLTP) NO_INDEX_MERGE() RESOURCE_GROUP(rg1)", output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("USE_TOJA"), HintData: true, }, { HintName: model.NewCIStr("IGNORE_PLAN_CACHE"), }, { HintName: model.NewCIStr("USE_CASCADES"), HintData: true, }, { HintName: model.NewCIStr("QUERY_TYPE"), QBName: model.NewCIStr("qb1"), HintData: model.NewCIStr("OLAP"), }, { HintName: model.NewCIStr("QUERY_TYPE"), HintData: model.NewCIStr("OLTP"), }, { HintName: model.NewCIStr("NO_INDEX_MERGE"), }, { HintName: model.NewCIStr("RESOURCE_GROUP"), HintData: "rg1", }, }, }, { input: "READ_FROM_STORAGE(@foo TIKV[a, b], TIFLASH[c, d]) HASH_AGG() SEMI_JOIN_REWRITE() READ_FROM_STORAGE(TIKV[e])", output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("READ_FROM_STORAGE"), HintData: model.NewCIStr("TIKV"), QBName: model.NewCIStr("foo"), Tables: []ast.HintTable{ {TableName: model.NewCIStr("a")}, {TableName: model.NewCIStr("b")}, }, }, { HintName: model.NewCIStr("READ_FROM_STORAGE"), HintData: model.NewCIStr("TIFLASH"), QBName: model.NewCIStr("foo"), Tables: []ast.HintTable{ {TableName: model.NewCIStr("c")}, {TableName: model.NewCIStr("d")}, }, }, { HintName: model.NewCIStr("HASH_AGG"), }, { HintName: model.NewCIStr("SEMI_JOIN_REWRITE"), }, { HintName: model.NewCIStr("READ_FROM_STORAGE"), HintData: model.NewCIStr("TIKV"), Tables: []ast.HintTable{ {TableName: model.NewCIStr("e")}, }, }, }, }, { input: "unknown_hint()", errs: []string{`Optimizer hint syntax error at line 1 `}, }, { input: "set_var(timestamp = 1.5)", errs: []string{ `Cannot use decimal number`, `Optimizer hint syntax error at line 1 `, }, }, { input: "set_var(timestamp = _utf8mb4'1234')", // Optimizer hint doesn't recognize _charset'strings'. errs: []string{`Optimizer hint syntax error at line 1 `}, }, { input: "set_var(timestamp = 9999999999999999999999999999999999999)", errs: []string{ `integer value is out of range`, `Optimizer hint syntax error at line 1 `, }, }, { input: "time_range('2020-02-20 12:12:12',456)", errs: []string{ `Optimizer hint syntax error at line 1 `, }, }, { input: "time_range(456,'2020-02-20 12:12:12')", errs: []string{ `Optimizer hint syntax error at line 1 `, }, }, { input: "TIME_RANGE('2020-02-20 12:12:12','2020-02-20 13:12:12')", output: []*ast.TableOptimizerHint{ { HintName: model.NewCIStr("TIME_RANGE"), HintData: ast.HintTimeRange{ From: "2020-02-20 12:12:12", To: "2020-02-20 13:12:12", }, }, }, }, } for _, tc := range testCases { output, errs := parser.ParseHint("/*+"+tc.input+"*/", tc.mode, parser.Pos{Line: 1}) require.Lenf(t, errs, len(tc.errs), "input = %s,\n... errs = %q", tc.input, errs) for i, err := range errs { require.Errorf(t, err, "input = %s, i = %d", tc.input, i) require.Containsf(t, err.Error(), tc.errs[i], "input = %s, i = %d", tc.input, i) } require.Equalf(t, tc.output, output, "input = %s,\n... output = %q", tc.input, output) } }
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01800104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.018.001.04 Document"` Message *RequestForOrderStatusReportV04 `xml:"ReqForOrdrStsRpt"` } func (d *Document01800104) AddMessage() *RequestForOrderStatusReportV04 { d.Message = new(RequestForOrderStatusReportV04) return d.Message } // Scope // The RequestForOrderStatusReport message is sent by an instructing party, for example, an investment manager or its authorised representative, to the executing party, for example, a transfer agent, to request the status of one or more order instructions or order cancellation requests. // Usage // The RequestForOrderStatusReport message is used to request the status of: // - one or several individual order instructions, or, // - one or several order messages, or // - one or several individual order cancellation requests, or, // - one or several order cancellation request messages. // The response to a RequestForOrderStatusReport message is the OrderInstructionStatusReport message or OrderCancellationStatusReport message. // If the RequestForOrderStatusReport message is used to request the status of several individual order instructions or one or more order instruction messages, then the instructing party may receive several OrderInstructionStatusReport messages from the executing party. // If the RequestForOrderStatusReport message is used to request the status of several individual order cancellation requests or one or more order cancellation messages, then the instructing party may receive several OrderCancellationStatusReport messages from the executing party. // When the RequestForOrderStatusReport is used to request the status of one or more individual orders or order cancellations, each individual order is identified with its order reference. The investment account and/or financial instrument related to the order can also be identified. The message identification of the message in which the individual order was conveyed may also be quoted in PreviousReference. // When the RequestForOrderStatusReport is used to request the status of an order message or an order cancellations request message, then the message identification of the order or cancellation message is identified in PreviousReference. // The RequestForOrderStatusReport message may not be used to request the status of an investment account, a transfer or the status of a financial instrument. type RequestForOrderStatusReportV04 struct { // Reference that uniquely identifies the message from a business application standpoint. MessageIdentification *iso20022.MessageIdentification1 `xml:"MsgId"` // Information to identify the order(s) for which the status is requested. RequestDetails []*iso20022.MessageAndBusinessReference10 `xml:"ReqDtls"` // Additional information that cannot be captured in the structured elements and/or any other specific block. Extension []*iso20022.Extension1 `xml:"Xtnsn,omitempty"` } func (r *RequestForOrderStatusReportV04) AddMessageIdentification() *iso20022.MessageIdentification1 { r.MessageIdentification = new(iso20022.MessageIdentification1) return r.MessageIdentification } func (r *RequestForOrderStatusReportV04) AddRequestDetails() *iso20022.MessageAndBusinessReference10 { newValue := new(iso20022.MessageAndBusinessReference10) r.RequestDetails = append(r.RequestDetails, newValue) return newValue } func (r *RequestForOrderStatusReportV04) AddExtension() *iso20022.Extension1 { newValue := new(iso20022.Extension1) r.Extension = append(r.Extension, newValue) return newValue }
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package envbinding import ( "encoding/json" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" ) // GetEnvBindingPolicy extract env-binding policy with given policy name, if policy name is empty, the first env-binding policy will be used func GetEnvBindingPolicy(app *v1beta1.Application, policyName string) (*v1alpha1.EnvBindingSpec, error) { for _, policy := range app.Spec.Policies { if (policy.Name == policyName || policyName == "") && policy.Type == v1alpha1.EnvBindingPolicyType { envBindingSpec := &v1alpha1.EnvBindingSpec{} err := json.Unmarshal(policy.Properties.Raw, envBindingSpec) return envBindingSpec, err } } return nil, nil } // GetEnvBindingPolicyStatus extract env-binding policy status with given policy name, if policy name is empty, the first env-binding policy will be used func GetEnvBindingPolicyStatus(app *v1beta1.Application, policyName string) (*v1alpha1.EnvBindingStatus, error) { for _, policyStatus := range app.Status.PolicyStatus { if (policyStatus.Name == policyName || policyName == "") && policyStatus.Type == v1alpha1.EnvBindingPolicyType { envBindingStatus := &v1alpha1.EnvBindingStatus{} if policyStatus.Status != nil { err := json.Unmarshal(policyStatus.Status.Raw, envBindingStatus) return envBindingStatus, err } return nil, nil } } return nil, nil }
/** * Created with IntelliJ IDEA. * User: Administrator * Date: 14-2-25 * Time: 下午4:40 * To change this template use File | Settings | File Templates. */ package main import ( "net" // "log" "packet" // "os" "sync" "time" //"fmt" "common" "runtime" // "helper" ) //// 命令接口 //type CmdInterface interface { // doMsg(pUser *user, length int, b []byte) bool //} //全局变量 var ( allSocketsSem sync.RWMutex // Used to synchronize access to all data structures in this var group allConn [Max_Conn]*connection // This array contains all socket //lastPlayerSlot int // The last slot in use in allPlayers //numPlayers int // The total number of players currently //CmdList [Max_CMD]CmdInterface //命令最大数量 //ProtoHandler [Max_CMD]func ( *user, *packet.Packet) //协议涵数 ) //开始服务 func StartListen() error { addr := common.GetElement("SocketInfo", "ListenAddr", "127.0.0.1:8080") listener, err := net.Listen("tcp", addr) if err != nil { return err } LogInfo("StartListen start, addr= ",addr); go func() { for failures := 0; failures < 100; { if !WorldRunning { break; } conn, err := listener.Accept() if err != nil { LogError("Failed listening: ", err, "\n"); failures++ } ok, freeSocket := GetFreeConnection(conn) if ok { go NewConnection(freeSocket) } else { LogError("GetFreeConnection > %d\n", Max_Conn); } } LogError("Too many listener.Accept() errors, giving up") //os.Exit(1) }() return nil } //初始化连接数据 func InitConnection() { var index uint32 = 0 for i := 0; i < Max_Conn; i++ { up := new(connection) up.id = index up.conn = nil up.connState = ConnStateFree up.logonTimer = time.Now() up.channel = make(chan []byte, ClientChannelSize) up.commandChannel = make(chan ClientCommand, ClientChannelSize) up.user = nil allConn[i] = up index = index + 1 } } //空闲连接 func GetFreeConnection(conn net.Conn) (ok bool, pConn *connection) { allSocketsSem.Lock() var index int for index = 0; index < Max_Conn; index++ { if allConn[index].connState == ConnStateFree { allConn[index].conn = conn allConn[index].connState = ConnStateLogin allConn[index].user = nil break } } allSocketsSem.Unlock() if index >= Max_Conn { LogInfo(" Handle the case with too many players,index = ", index, ",MAX_PLAYERS =\n", Max_Conn) return false, nil } return true, allConn[index] } //释放连连接 func FreeConnection(pConn *connection) (ok bool ) { //fmt.Printf(" FreeConnection id = %d\n",pSocket.id) allSocketsSem.Lock() pConn.connState = ConnStateFree; pConn.conn.Close(); pConn.conn = nil; pConn.user = nil if len(pConn.channel) > 0 { tmp := <-pConn.channel LogInfo(" clear channel =", tmp) } if len(pConn.commandChannel) > 0 { tmp := <-pConn.commandChannel LogInfo(" clear channel =", tmp) } allSocketsSem.Unlock() return true } //关闭所有连接 func CloseConnection() { for i := 0; i < Max_Conn; i++ { pSocket := allConn[i] FreeConnection(pSocket) } } func NewConnection(pConn *connection) { defer catchError(pConn) var length int buff := pConn.recvBuff[:] tick := 0 for tick = 0; tick < Max_Tick; { if !WorldRunning { break; } time.Sleep(ObjectsUpdatePeriod) // Read out all waiting data, if any, from the incoming channels for moreData := true; moreData; { select { case clientMessage := <-pConn.channel: pConn.writeBlocking_Bl(clientMessage) case clientCommand := <-pConn.commandChannel: clientCommand(pConn) default: moreData = false } if pConn.connState == ConnStateDisc { //玩家关闭 break; } } //Read data length from socket pConn.conn.SetReadDeadline(time.Now().Add(ObjectsUpdatePeriod)) n, err := pConn.conn.Read(buff[0:2]) // Read the length information. This will block for ObjectsUpdatePeriod ns if err != nil { if e2, ok := err.(*net.OpError); ok && (e2.Timeout() || e2.Temporary()) { tick += 1; //log.Printf("Read timeout %v", e2) // This will happen frequently continue } LogInfo("Disconnect from ", pConn.id, ", because of ", err) // This is a normal case break } //包没收完,继续收 if n == 1 { //LogDebug("Got %d bytes reading from socket\n", n) for (n == 1) { n2, err := pConn.conn.Read(buff[1:2]) // Second byte of the length if err != nil || n2 != 1 { LogInfo("Failed again to read: ", err) break; } n = 2 } } if n != 2 { LogDebug("Got %d bytes reading from socket,tick =%d\n", n, tick) continue } //ret = uint16(buf[0])<<8 | uint16(buf[1]) length = int(uint(buff[0])<<8 + uint(buff[1])) if length < 4 || length > Max_Recv_Packge { //超过最大包长,异常,直接丢掉 LogInfo("Expecting ", length, " bytes, which is too much for buffer. Buffer was extended") continue } // Read the rest of the bytes pConn.conn.SetReadDeadline(time.Now().Add(ObjectsUpdatePeriod)) // Give it up after a long time for n2 := n; n2 < length; { //LogDebug("Got", n2, "out of", length, "bytes") // If unlucky, we only get one byte at a time const maxDelay = 5 for i := 0; i < maxDelay; i++ { // Normal case is one iteration in this loop n, err = pConn.conn.Read(buff[n2:length]) if err == nil { break // No error } e2, ok := err.(net.Error) if ok && !e2.Temporary() && !e2.Timeout() { // We don't really expect a timeout here break // Bad error, can't handle it. } LogInfo("Temporary, retry") if i == maxDelay - 1 { LogInfo("Timeout, giving up") } } if err != nil { LogInfo("Disconnect ", pConn.id, " because of ", err) panic(err) } n2 += n } //加入到流量统计中 //trafficStatistics.AddReceived(length) //cmd := uint16(buff[2])<<8 | uint16(buff[3]) reader := packet.Reader(buff[2:length]) cmd,err := reader.ReadU16() //登录验证包及前置验证 if (pConn.connState <= ConnStateLogin) { PrepareHandler(pConn, cmd, reader) tick += 1; continue; } //正常数据 if pConn.user != nil && pConn.user.conn != nil { ProtoHandler(pConn, cmd, reader) tick = 0 continue; } //异常数据,TICK计次 tick += 1; LogDebug("doMsg empty,Cmd = ", cmd) } LogInfo("Disconnect ", pConn.id, " tick = ", tick, "(", Max_Tick, ").\n") } //异常处理 func catchError(pConn *connection) { if err := recover(); err != nil { LogInfo("err", err) //这里要异常要退出整个程序,只能在debug模式下使用 for i := 0; i < 10; i++ { funcName, file, line, ok := runtime.Caller(i) if ok { LogInfo("frame ", i, ":[func:", runtime.FuncForPC(funcName).Name(), ",file:", file, ",line:", line) } } } if pConn == nil {return} LogInfo("Disconnect id = ", pConn.id) FreeConnection(pConn) }
package sqlbuilder import ( "fmt" "strings" ) type table struct { name string joinType int joinConstraints []SQLProvider subQuery SQLProvider } func (t *table) GetSQL(cache *VarCache) string { if t.joinType == join_none { if t.subQuery != nil { return t.subQuery.GetSQL(cache) } return t.name } joinType := joinTypes[t.joinType] ons := make([]string, len(t.joinConstraints)) for i, c := range t.joinConstraints { ons[i] = c.GetSQL(cache) } return fmt.Sprintf("%s JOIN %s ON %s", joinType, t.name, strings.Join(ons, " AND ")) } var joinTypes = map[int]string{ join_inner: "INNER", join_left: "LEFT", join_right: "RIGHT", join_outer: "OUTER", } // Used within a JOIN context, joins on a particular column link func OnColumn(field, otherField string) SQLProvider { return Raw{field + " = " + otherField} } // Just a passthru to make people feel better func OnExpression(expr SQLProvider) SQLProvider { return expr } // Add a JOIN component. Constraints can be any number of sqlPRoviders, but you should only // use OnColumn and OnValue func (q *Query) join(joinType int, tableName string, constraints ...SQLProvider) *Query { newTable := &table{ joinType: joinType, name: tableName, joinConstraints: constraints, } q.tables = append(q.tables, newTable) return q } func (q *Query) InnerJoin(tableName string, constraints ...SQLProvider) *Query { return q.join(join_inner, tableName, constraints...) } func (q *Query) LeftJoin(tableName string, constraints ...SQLProvider) *Query { return q.join(join_left, tableName, constraints...) } func (q *Query) RightJoin(tableName string, constraints ...SQLProvider) *Query { return q.join(join_right, tableName, constraints...) } func (q *Query) OuterJoin(tableName string, constraints ...SQLProvider) *Query { return q.join(join_outer, tableName, constraints...) } // Get the alias of a table that has already been joined on the query. This is useful for when you construct the query using several different components and potentially more than one component may need to join the same table. Important to note, however that this function will return the first joined table that matches. If you join the same table twice with different aliases, you should not rely on this function. func (q *Query) GetJoinAlias(tableName string) (found bool, alias string) { var spl []string var lowerName string for _, t := range q.tables { lowerName = strings.ToLower(t.name) spl = strings.Split(lowerName, " as ") if spl[0] == tableName { found = true if len(spl) > 1 { alias = spl[1] } else { alias = spl[0] } break } } return } // Join a table/alias comboination if it hasn't already been joined func (q *Query) lazyJoin(joinType int, tableName string, constraints ...SQLProvider) *Query { for _, t := range q.tables { if t.name == tableName && t.joinType == joinType { return q } } return q.join(joinType, tableName, constraints...) } func (q *Query) LazyInnerJoin(tableName string, constraints ...SQLProvider) *Query { return q.lazyJoin(join_inner, tableName, constraints...) } func (q *Query) LazyLeftJoin(tableName string, constraints ...SQLProvider) *Query { return q.lazyJoin(join_left, tableName, constraints...) } func (q *Query) LazyRightJoin(tableName string, constraints ...SQLProvider) *Query { return q.lazyJoin(join_right, tableName, constraints...) } func (q *Query) LazyOuterJoin(tableName string, constraints ...SQLProvider) *Query { return q.lazyJoin(join_outer, tableName, constraints...) }
package explain import ( "github.com/pkg/errors" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" ) func lookup(schema *apiextv1.JSONSchemaProps, path []string) (*apiextv1.JSONSchemaProps, error) { if len(path) == 0 { return schema, nil } properties := map[string]apiextv1.JSONSchemaProps{} if schema.Items != nil && schema.Items.Schema != nil { properties = schema.Items.Schema.Properties } if len(schema.Properties) > 0 { properties = schema.Properties } property, ok := properties[path[0]] if !ok { return nil, errors.Errorf("invalid field %s, no such property found", path[0]) } return lookup(&property, path[1:]) }
package mongodb import ( "github.com/b2wdigital/goignite/pkg/config" "log" ) const ( ConfigRoot = "transport.client.mongodb" Uri = ConfigRoot + ".uri" HealthEnabled = ConfigRoot + ".enabled" HealthDescription = ConfigRoot + ".health.description" HealthRequired = ConfigRoot + ".health.required" NewRelicEnabled = ConfigRoot + ".newrelic.enabled" ) func init() { log.Println("getting configurations for mongodb") config.Add(Uri, "mongodb://localhost:27017/temp", "define mongodb uri") config.Add(HealthEnabled, true, "enabled/disable health check") config.Add(HealthDescription, "default connection", "define health description") config.Add(HealthRequired, true, "define health description") config.Add(NewRelicEnabled, false, "enable/disable newrelic") }
package service import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strings" "time" "github.com/sirupsen/logrus" "github.com/Hudayberdyyev/weather_api/models" "github.com/Hudayberdyyev/weather_api/pkg/repository" ) const ( APIKey = "559cd760f10f8731db7e748be0666c37" URL = "http://api.openweathermap.org/data/2.5/forecast?q={city name}&appid={API key}&lang=ru&units=metric" ) var owmURL string type ForecastService struct { repo repository.Forecast } func NewForecastService(repo repository.Forecast) *ForecastService { return &ForecastService{repo: repo} } func (s *ForecastService) Update() error { cities, err := s.repo.GetCities() if err != nil { return err } for _, value := range *cities { owmURL = URL owmURL = strings.Replace(owmURL, "{city name}", value.Name, 1) owmURL = strings.Replace(owmURL, "{API key}", APIKey, 1) urlParsed, err := url.Parse(owmURL) fmt.Println(urlParsed.String()) spaceClient := http.Client{ Timeout: time.Second * 5, // Timeout after 2 seconds } req, err := http.NewRequest(http.MethodGet, urlParsed.String(), nil) if err != nil { return err } req.Header.Set("Accept", "*/*") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36") res, getErr := spaceClient.Do(req) if getErr != nil { return getErr } if res.Body != nil { defer res.Body.Close() } body, readErr := ioutil.ReadAll(res.Body) if readErr != nil { return readErr } var result models.OwmResponse jsonErr := json.Unmarshal(body, &result) if jsonErr != nil { return jsonErr } var firstTimestamp int64 if len(result.ListData) > 0 { firstTimestamp = result.ListData[0].Dt } else { return errors.New("empty response from OpenWeather") } if err = s.repo.DeleteOld(value.RegionId, firstTimestamp); err != nil { return err } if err = s.repo.Create(value.RegionId, &result); err != nil { return err } logrus.Println(value, "ok") } if err = s.repo.DeleteEarlyCurrentDate(); err != nil { return err } return nil }
func uncommonFromSentences(A string, B string) []string { s1:=strings.Split(A," ") s2:=strings.Split(B," ") m:=make(map[string]int) res:=[]string{} for _,v:=range s1{ m[v]+=1 } for _,v:=range s2{ m[v]+=1 } for k,v:=range m{ if v==1 && len(k)>0{ res = append(res,k) } } return res }
package core import ( "fmt" "image/color" "math" "math/rand" ) //Vec3 contains 3 components - can //be used to represent colors, points, vectors etc. type Vec3 struct { X, Y, Z float64 } func Clamp(x float64, min float64, max float64) float64 { if x < min { return min } if x > max { return max } return x } func remap(x, min, max float64) float64 { return x*(max-min) + min } func RandomVector() Vec3 { return NewVector3(rand.Float64(), rand.Float64(), rand.Float64()) } func RandomVectorByRange(min, max float64) Vec3 { x := remap(rand.Float64(), min, max) y := remap(rand.Float64(), min, max) z := remap(rand.Float64(), min, max) return NewVector3(x, y, z) } func RandomUnitSphereSample2() Vec3 { r1 := rand.Float64() r2 := rand.Float64() x := math.Cos(2.0*math.Pi*r1) * 2.0 * math.Sqrt(r2*(1.0-r2)) y := math.Sin(2.0*math.Pi*r1) * 2.0 * math.Sqrt(r2*(1.0-r2)) z := 1.0 - 2.0*r2 return Vec3{x, y, z} } func GetRandomVectorInUnitSphere() Vec3 { //while loop. for i := 0; i < 1; { randpt := RandomVectorByRange(-1, 1) if randpt.LengthSquared() >= 1 { continue } return randpt } return Vec3{} } //TODO - don't do this type Col3 = Vec3 type Pt3 = Vec3 //New constructs a vec3 by components func NewVector3(x float64, y float64, z float64) Vec3 { v := Vec3{} v.X = x v.Y = y v.Z = z return v } //Negate returns a new vector with componets negated func (v Vec3) Negate() Vec3 { return NewVector3(-v.X, -v.Y, -v.Z) } func (v Vec3) Add(u Vec3) Vec3 { return NewVector3( v.X+u.X, v.Y+u.Y, v.Z+u.Z) } func (v Vec3) Subtract(u Vec3) Vec3 { return NewVector3( v.X-u.X, v.Y-u.Y, v.Z-u.Z) } func (v Vec3) Scale(factor float64) Vec3 { return NewVector3( v.X*factor, v.Y*factor, v.Z*factor) } func (v Vec3) Length() float64 { return math.Sqrt(v.LengthSquared()) } func (v Vec3) LengthSquared() float64 { return v.X*v.X + v.Y*v.Y + v.Z*v.Z } func (v Vec3) String() string { return fmt.Sprintf("[%f, %f, %f]", v.X, v.Y, v.Z) } func (v Vec3) NearZero() bool { const e = .000001 if math.Abs(v.X) < e && math.Abs(v.Y) < e && math.Abs(v.Z) < e { return true } return false } //Multiply does componentwise multiplication - hadamard product func Multiply(v Vec3, u Vec3) Vec3 { return NewVector3( v.X*u.X, v.Y*u.Y, v.Z*u.Z) } func Dot(v Vec3, u Vec3) float64 { return u.X*v.X + v.Y*u.Y + v.Z*u.Z } func Cross(v Vec3, u Vec3) Vec3 { return NewVector3( v.Y*u.Z-v.Z*u.Y, v.Z*u.X-v.X*u.Z, v.X*u.Y-v.Y*u.X) } func Normalize(v Vec3) Vec3 { return v.Scale(1.0 / (v.Length())) } func (v Vec3) ToRGBA() color.RGBA { col := color.RGBA{uint8(v.X), uint8(v.Y), uint8(v.Z), 255} return col } func Reflect(v *Vec3, n *Vec3) Vec3 { return v.Subtract(n.Scale(2 * Dot(*v, *n))) } //TODO research the proof of this func Refract(unitVectorIn *Vec3, normal *Vec3, refractionRatio float64) Vec3 { cos_theta := math.Min(Dot(unitVectorIn.Negate(), *normal), 1.0) //relative to normal. refractedRayOutPerpendicularComponents := (unitVectorIn.Add(normal.Scale(cos_theta))).Scale(refractionRatio) refractedRayOutParallelComponents := normal.Scale(-math.Sqrt(math.Abs(1.0 - refractedRayOutPerpendicularComponents.LengthSquared()))) return refractedRayOutParallelComponents.Add(refractedRayOutPerpendicularComponents) } func (vec *Vec3) Index(index int) float64 { switch index { case 0: return vec.X case 1: return vec.Y case 2: return vec.Z } return math.NaN() } func Test() { println("inside core package") }
package main import ( "bytes" "fmt" "net/http" "os" "strings" ) func main() { if body, err := http.Get(`http://checkip.amazonaws.com/`); err == nil { buffer := new(bytes.Buffer) buffer.ReadFrom(body.Body) fmt.Println(strings.TrimSpace(buffer.String())) } else { errorMessage := fmt.Sprintf("+%v", err) fmt.Println(errorMessage) os.Exit(1) } }
package cmd import ( "fmt" "os" "github.com/ovh/venom" ) // Exit func display an error message on stderr and exit 1 func Exit(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) venom.OSExit(1) }
package main import ( "crypto/sha256" "fmt" ) func main() { hasher := sha256.New() fmt.Println(hasher.Sum([]byte("hello world"))) fmt.Printf("%d\n", hasher.Sum([]byte("hello world"))) }
package compress import ( "bytes" "compress/flate" "fmt" "io" "io/ioutil" "reflect" "testing" "github.com/gobwas/ws" "github.com/gobwas/ws/wsutil" ) func TestCompressWriter(t *testing.T) { for i, test := range []struct { label string level int fragmented bool seq [][]byte result []byte }{ { label: "empty", level: 6, seq: [][]byte{nil}, result: nil, }, { label: "simple", level: 6, seq: [][]byte{[]byte("hello world!")}, result: ws.MustCompileFrame(MustCompressFrame(ws.NewTextFrame([]byte("hello world!")), -1))[2:], // strip header }, { label: "small", level: 6, seq: [][]byte{[]byte("hi")}, result: ws.MustCompileFrame(MustCompressFrame(ws.NewTextFrame([]byte("hi")), -1))[2:], // strip header }, { label: "multiple_writes", level: 6, seq: [][]byte{[]byte("hello "), []byte("world!")}, result: []byte{0xca, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x0, 0x0, 0x2a, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x4, 0x0}, }, { label: "fragmented_writes", level: 6, fragmented: true, seq: [][]byte{[]byte("hello "), []byte("world!")}, result: []byte{0xca, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0x2a, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x4, 0x0, 0x0, 0x0, 0xff, 0xff}, }, } { t.Run(fmt.Sprintf("%s#%d", test.label, i), func(t *testing.T) { var err error buf := &bytes.Buffer{} cw := NewWriter(buf, test.level) for i, b := range test.seq { _, err = cw.Write(b) if err != nil { t.Errorf("cannot write data: %s", err) return } if test.fragmented && i <= len(test.seq)-1 { err = cw.FlushFragment() } else { err = cw.Flush() } if err != nil { t.Errorf("cannot flush data: %s", err) return } } if !reflect.DeepEqual(buf.Bytes(), test.result) { t.Errorf("write data is not equal:\n\tact:\t%#v\n\texp:\t%#v\n", buf.Bytes(), test.result) return } }) } } func TestCompressReader(t *testing.T) { for _, test := range []struct { name string seq []ws.Frame chop int exp []byte err error }{ { name: "empty", seq: []ws.Frame{}, err: io.EOF, }, { name: "single", seq: []ws.Frame{ ws.NewTextFrame([]byte("Привет, Мир!")), }, exp: []byte("Привет, Мир!"), }, { name: "single_compressed", seq: []ws.Frame{ { Header: ws.Header{ Fin: true, Rsv: 0x04, OpCode: ws.OpText, Length: 14, }, Payload: []byte{0xca, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x04, 0x0}, }, }, exp: []byte("hello world!"), }, { name: "fragmented_compressed", seq: []ws.Frame{ { Header: ws.Header{ Fin: false, Rsv: 0x04, OpCode: ws.OpText, Length: 7, }, Payload: []byte{0xca, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28}, }, { Header: ws.Header{ Fin: true, Rsv: 0x00, OpCode: ws.OpContinuation, Length: 7, }, Payload: []byte{0xcf, 0x2f, 0xca, 0x49, 0x51, 0x04, 0x0}, }, }, exp: []byte("hello world!"), }, { name: "fragmented_compressed_multiple_flushed", seq: []ws.Frame{ { Header: ws.Header{ Fin: false, Rsv: 0x04, OpCode: ws.OpText, Length: 12, }, Payload: []byte{0xca, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff}, }, { Header: ws.Header{ Fin: true, Rsv: 0x00, OpCode: ws.OpContinuation, Length: 8, }, Payload: []byte{0x2a, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x4, 0x0}, }, }, exp: []byte("hello world!"), }, { name: "fragmented_compressed_broken", seq: []ws.Frame{ { Header: ws.Header{ Fin: false, Rsv: 0x04, OpCode: ws.OpText, Length: 7, }, Payload: []byte{0xca, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28}, }, ws.NewTextFrame([]byte("Hello, Brave New World!")), }, exp: []byte("hello world!"), err: ws.ErrProtocolContinuationExpected, }, { name: "fragmented_compressed_control", seq: []ws.Frame{ { Header: ws.Header{ Fin: false, Rsv: 0x04, OpCode: ws.OpText, Length: 7, }, Payload: []byte{0xca, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28}, }, ws.NewFrame(ws.OpPing, true, nil), ws.NewFrame(ws.OpPing, true, nil), { Header: ws.Header{ Fin: true, Rsv: 0x00, OpCode: ws.OpContinuation, Length: 7, }, Payload: []byte{0xcf, 0x2f, 0xca, 0x49, 0x51, 0x04, 0x0}, }, ws.NewFrame(ws.OpPing, true, nil), ws.NewFrame(ws.OpPing, true, []byte("ping info")), }, exp: []byte("hello world!"), }, } { t.Run(test.name, func(t *testing.T) { // Prepare input. connBuf := &bytes.Buffer{} for _, f := range test.seq { if err := ws.WriteFrame(connBuf, f); err != nil { t.Fatal(err) } } conn := &chopReader{ src: bytes.NewReader(connBuf.Bytes()), sz: test.chop, } compressedMessage := false mask := [4]byte{} masked := false bts := make([]byte, 1024) pos := 0 startedContinuation := false for { header, err := ws.ReadHeader(conn) if err == io.EOF { break } else if err != nil { t.Errorf("cannot read header of frame: %v", err) } if !header.OpCode.IsData() { io.ReadFull(conn, make([]byte, header.Length)) continue } if header.Rsv1() { compressedMessage = true } if startedContinuation && header.OpCode != ws.OpContinuation { if test.err != ws.ErrProtocolContinuationExpected { t.Errorf("Continuation frame expected") } return } startedContinuation = startedContinuation || !header.Fin var tmpBts []byte if len(bts) < pos+int(header.Length) { tmpBts = make([]byte, header.Length) } else { tmpBts = bts[pos:pos+int(header.Length)] } n, err := io.ReadFull(conn, tmpBts) if err != nil { t.Errorf("cannot read payload of frame: %v", err) break } copy(bts[pos:], tmpBts) pos += n if header.Masked { masked = true mask = header.Mask } if header.Fin { var payload []byte if compressedMessage { r := bytes.NewReader(bts[0:pos]) compressedReader := NewReader(r, len(bts)) payload, err = ioutil.ReadAll(compressedReader) if err != nil { t.Errorf("cannot read message: %v", err) } } else { payload = make([]byte, pos) copy(payload, bts[0:pos]) } if masked { ws.Cipher(payload, mask, 0) } if test.err == nil && !bytes.Equal(payload, test.exp) { t.Errorf( "Read compressed from reader:\nact:\t%#x\nexp:\t%#x\nact:\t%s\nexp:\t%s\n", payload, test.exp, string(payload), string(test.exp), ) } pos = 0 compressedMessage = false startedContinuation = false } if header.OpCode == ws.OpClose { break } } }) } } func BenchmarkCompressWriter(b *testing.B) { for _, bench := range []struct { compressed bool message string repeated int }{ { message: "hello world", }, { message: "hello world", repeated: 1000, }, { message: "hello world", repeated: 10000, }, { message: "hello world", compressed: true, }, { message: "hello world", repeated: 1000, compressed: true, }, { message: "hello world", repeated: 10000, compressed: true, }, } { b.Run(fmt.Sprintf("message=%s;repeated=%d;comp=%v", bench.message, bench.repeated, bench.compressed), func(b *testing.B) { buf := &bytes.Buffer{} for r := bench.repeated; r >= 0; r-- { buf.WriteString(bench.message) } var ( writer *wsutil.Writer cw Writer err error ) if bench.compressed { cw = NewWriter(ioutil.Discard, flate.BestSpeed) } else { writer = wsutil.NewWriter(ioutil.Discard, ws.StateServerSide, ws.OpText) } for i := 0; i < b.N; i++ { if cw != nil { _, err = cw.Write(buf.Bytes()) if err == nil { err = cw.Flush() } } else { _, err = writer.Write(buf.Bytes()) if err == nil { err = writer.Flush() } } if err != nil { b.Errorf("cannot write: %s", err) return } } }) } } type chopReader struct { src io.Reader sz int } func (c chopReader) Read(p []byte) (n int, err error) { sz := c.sz if sz == 0 { sz = 1 } if sz > len(p) { sz = len(p) } return c.src.Read(p[:sz]) }
// All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v20180317 import ( "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common" tchttp "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common/http" "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common/profile" ) const APIVersion = "2018-03-17" type Client struct { common.Client } // Deprecated func NewClientWithSecretId(secretId, secretKey, region string) (client *Client, err error) { cpf := profile.NewClientProfile() client = &Client{} client.Init(region).WithSecretId(secretId, secretKey).WithProfile(cpf) return } func NewClient(credential *common.Credential, region string, clientProfile *profile.ClientProfile) (client *Client, err error) { client = &Client{} client.Init(region). WithCredential(credential). WithProfile(clientProfile) return } func NewAssociateTargetGroupsRequest() (request *AssociateTargetGroupsRequest) { request = &AssociateTargetGroupsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "AssociateTargetGroups") return } func NewAssociateTargetGroupsResponse() (response *AssociateTargetGroupsResponse) { response = &AssociateTargetGroupsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(AssociateTargetGroups)用来将目标组绑定到负载均衡的监听器(四层协议)或转发规则(七层协议)上。 // 本接口为异步接口,本接口返回成功后需以返回的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) AssociateTargetGroups(request *AssociateTargetGroupsRequest) (response *AssociateTargetGroupsResponse, err error) { if request == nil { request = NewAssociateTargetGroupsRequest() } response = NewAssociateTargetGroupsResponse() err = c.Send(request, response) return } func NewAutoRewriteRequest() (request *AutoRewriteRequest) { request = &AutoRewriteRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "AutoRewrite") return } func NewAutoRewriteResponse() (response *AutoRewriteResponse) { response = &AutoRewriteResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 用户需要先创建出一个HTTPS:443监听器,并在其下创建转发规则。通过调用本接口,系统会自动创建出一个HTTP:80监听器(如果之前不存在),并在其下创建转发规则,与HTTPS:443监听器下的Domains(在入参中指定)对应。创建成功后可以通过HTTP:80地址自动跳转为HTTPS:443地址进行访问。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) AutoRewrite(request *AutoRewriteRequest) (response *AutoRewriteResponse, err error) { if request == nil { request = NewAutoRewriteRequest() } response = NewAutoRewriteResponse() err = c.Send(request, response) return } func NewBatchDeregisterTargetsRequest() (request *BatchDeregisterTargetsRequest) { request = &BatchDeregisterTargetsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "BatchDeregisterTargets") return } func NewBatchDeregisterTargetsResponse() (response *BatchDeregisterTargetsResponse) { response = &BatchDeregisterTargetsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 批量解绑四七层后端服务。 func (c *Client) BatchDeregisterTargets(request *BatchDeregisterTargetsRequest) (response *BatchDeregisterTargetsResponse, err error) { if request == nil { request = NewBatchDeregisterTargetsRequest() } response = NewBatchDeregisterTargetsResponse() err = c.Send(request, response) return } func NewBatchModifyTargetWeightRequest() (request *BatchModifyTargetWeightRequest) { request = &BatchModifyTargetWeightRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "BatchModifyTargetWeight") return } func NewBatchModifyTargetWeightResponse() (response *BatchModifyTargetWeightResponse) { response = &BatchModifyTargetWeightResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(BatchModifyTargetWeight)用于批量修改负载均衡监听器绑定的后端机器的转发权重,支持负载均衡的4层和7层监听器;不支持传统型负载均衡。 // 本接口为异步接口,本接口返回成功后需以返回的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) BatchModifyTargetWeight(request *BatchModifyTargetWeightRequest) (response *BatchModifyTargetWeightResponse, err error) { if request == nil { request = NewBatchModifyTargetWeightRequest() } response = NewBatchModifyTargetWeightResponse() err = c.Send(request, response) return } func NewBatchRegisterTargetsRequest() (request *BatchRegisterTargetsRequest) { request = &BatchRegisterTargetsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "BatchRegisterTargets") return } func NewBatchRegisterTargetsResponse() (response *BatchRegisterTargetsResponse) { response = &BatchRegisterTargetsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 批量绑定虚拟主机或弹性网卡,支持跨域绑定,支持四层、七层(TCP、UDP、HTTP、HTTPS)协议绑定。 func (c *Client) BatchRegisterTargets(request *BatchRegisterTargetsRequest) (response *BatchRegisterTargetsResponse, err error) { if request == nil { request = NewBatchRegisterTargetsRequest() } response = NewBatchRegisterTargetsResponse() err = c.Send(request, response) return } func NewCreateListenerRequest() (request *CreateListenerRequest) { request = &CreateListenerRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "CreateListener") return } func NewCreateListenerResponse() (response *CreateListenerResponse) { response = &CreateListenerResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 在一个负载均衡实例下创建监听器。 // 本接口为异步接口,接口返回成功后,需以返回的 RequestId 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) CreateListener(request *CreateListenerRequest) (response *CreateListenerResponse, err error) { if request == nil { request = NewCreateListenerRequest() } response = NewCreateListenerResponse() err = c.Send(request, response) return } func NewCreateLoadBalancerRequest() (request *CreateLoadBalancerRequest) { request = &CreateLoadBalancerRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "CreateLoadBalancer") return } func NewCreateLoadBalancerResponse() (response *CreateLoadBalancerResponse) { response = &CreateLoadBalancerResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(CreateLoadBalancer)用来创建负载均衡实例(本接口只支持购买按量计费的负载均衡,包年包月的负载均衡请通过控制台购买)。为了使用负载均衡服务,您必须购买一个或多个负载均衡实例。成功调用该接口后,会返回负载均衡实例的唯一 ID。负载均衡实例的类型分为:公网、内网。详情可参考产品说明中的产品类型。 // 注意:(1)指定可用区申请负载均衡、跨zone容灾(仅香港支持)【如果您需要体验该功能,请通过 工单申请】;(2)目前只有北京、上海、广州支持IPv6;(3)一个账号在每个地域的默认购买配额为:公网100个,内网100个。 // 本接口为异步接口,接口成功返回后,可使用 DescribeLoadBalancers 接口查询负载均衡实例的状态(如创建中、正常),以确定是否创建成功。 func (c *Client) CreateLoadBalancer(request *CreateLoadBalancerRequest) (response *CreateLoadBalancerResponse, err error) { if request == nil { request = NewCreateLoadBalancerRequest() } response = NewCreateLoadBalancerResponse() err = c.Send(request, response) return } func NewCreateLoadBalancerSnatIpsRequest() (request *CreateLoadBalancerSnatIpsRequest) { request = &CreateLoadBalancerSnatIpsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "CreateLoadBalancerSnatIps") return } func NewCreateLoadBalancerSnatIpsResponse() (response *CreateLoadBalancerSnatIpsResponse) { response = &CreateLoadBalancerSnatIpsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 针对SnatPro负载均衡,这个接口用于添加SnatIp,如果负载均衡没有开启SnatPro,添加SnatIp后会自动开启 func (c *Client) CreateLoadBalancerSnatIps(request *CreateLoadBalancerSnatIpsRequest) (response *CreateLoadBalancerSnatIpsResponse, err error) { if request == nil { request = NewCreateLoadBalancerSnatIpsRequest() } response = NewCreateLoadBalancerSnatIpsResponse() err = c.Send(request, response) return } func NewCreateRuleRequest() (request *CreateRuleRequest) { request = &CreateRuleRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "CreateRule") return } func NewCreateRuleResponse() (response *CreateRuleResponse) { response = &CreateRuleResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // CreateRule 接口用于在一个已存在的负载均衡七层监听器下创建转发规则,七层监听器中,后端服务必须绑定到规则上而非监听器上。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) CreateRule(request *CreateRuleRequest) (response *CreateRuleResponse, err error) { if request == nil { request = NewCreateRuleRequest() } response = NewCreateRuleResponse() err = c.Send(request, response) return } func NewCreateTargetGroupRequest() (request *CreateTargetGroupRequest) { request = &CreateTargetGroupRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "CreateTargetGroup") return } func NewCreateTargetGroupResponse() (response *CreateTargetGroupResponse) { response = &CreateTargetGroupResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 创建目标组。(目标组功能正在灰度中,需要开通白名单支持) func (c *Client) CreateTargetGroup(request *CreateTargetGroupRequest) (response *CreateTargetGroupResponse, err error) { if request == nil { request = NewCreateTargetGroupRequest() } response = NewCreateTargetGroupResponse() err = c.Send(request, response) return } func NewDeleteListenerRequest() (request *DeleteListenerRequest) { request = &DeleteListenerRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeleteListener") return } func NewDeleteListenerResponse() (response *DeleteListenerResponse) { response = &DeleteListenerResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口用来删除负载均衡实例下的监听器(四层和七层)。 // 本接口为异步接口,接口返回成功后,需以得到的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) DeleteListener(request *DeleteListenerRequest) (response *DeleteListenerResponse, err error) { if request == nil { request = NewDeleteListenerRequest() } response = NewDeleteListenerResponse() err = c.Send(request, response) return } func NewDeleteLoadBalancerRequest() (request *DeleteLoadBalancerRequest) { request = &DeleteLoadBalancerRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeleteLoadBalancer") return } func NewDeleteLoadBalancerResponse() (response *DeleteLoadBalancerResponse) { response = &DeleteLoadBalancerResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DeleteLoadBalancer 接口用以删除指定的一个或多个负载均衡实例。 // 本接口为异步接口,接口返回成功后,需以返回的 RequestId 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) DeleteLoadBalancer(request *DeleteLoadBalancerRequest) (response *DeleteLoadBalancerResponse, err error) { if request == nil { request = NewDeleteLoadBalancerRequest() } response = NewDeleteLoadBalancerResponse() err = c.Send(request, response) return } func NewDeleteLoadBalancerListenersRequest() (request *DeleteLoadBalancerListenersRequest) { request = &DeleteLoadBalancerListenersRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeleteLoadBalancerListeners") return } func NewDeleteLoadBalancerListenersResponse() (response *DeleteLoadBalancerListenersResponse) { response = &DeleteLoadBalancerListenersResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 该接口支持删除负载均衡的多个监听器。 // 本接口为异步接口,本接口返回成功后需以返回的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) DeleteLoadBalancerListeners(request *DeleteLoadBalancerListenersRequest) (response *DeleteLoadBalancerListenersResponse, err error) { if request == nil { request = NewDeleteLoadBalancerListenersRequest() } response = NewDeleteLoadBalancerListenersResponse() err = c.Send(request, response) return } func NewDeleteLoadBalancerSnatIpsRequest() (request *DeleteLoadBalancerSnatIpsRequest) { request = &DeleteLoadBalancerSnatIpsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeleteLoadBalancerSnatIps") return } func NewDeleteLoadBalancerSnatIpsResponse() (response *DeleteLoadBalancerSnatIpsResponse) { response = &DeleteLoadBalancerSnatIpsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 对于SnatPro的负载均衡,这个接口用于删除SnatIp func (c *Client) DeleteLoadBalancerSnatIps(request *DeleteLoadBalancerSnatIpsRequest) (response *DeleteLoadBalancerSnatIpsResponse, err error) { if request == nil { request = NewDeleteLoadBalancerSnatIpsRequest() } response = NewDeleteLoadBalancerSnatIpsResponse() err = c.Send(request, response) return } func NewDeleteRewriteRequest() (request *DeleteRewriteRequest) { request = &DeleteRewriteRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeleteRewrite") return } func NewDeleteRewriteResponse() (response *DeleteRewriteResponse) { response = &DeleteRewriteResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DeleteRewrite 接口支持删除指定转发规则之间的重定向关系。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) DeleteRewrite(request *DeleteRewriteRequest) (response *DeleteRewriteResponse, err error) { if request == nil { request = NewDeleteRewriteRequest() } response = NewDeleteRewriteResponse() err = c.Send(request, response) return } func NewDeleteRuleRequest() (request *DeleteRuleRequest) { request = &DeleteRuleRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeleteRule") return } func NewDeleteRuleResponse() (response *DeleteRuleResponse) { response = &DeleteRuleResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DeleteRule 接口用来删除负载均衡实例七层监听器下的转发规则。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) DeleteRule(request *DeleteRuleRequest) (response *DeleteRuleResponse, err error) { if request == nil { request = NewDeleteRuleRequest() } response = NewDeleteRuleResponse() err = c.Send(request, response) return } func NewDeleteTargetGroupsRequest() (request *DeleteTargetGroupsRequest) { request = &DeleteTargetGroupsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeleteTargetGroups") return } func NewDeleteTargetGroupsResponse() (response *DeleteTargetGroupsResponse) { response = &DeleteTargetGroupsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 删除目标组 func (c *Client) DeleteTargetGroups(request *DeleteTargetGroupsRequest) (response *DeleteTargetGroupsResponse, err error) { if request == nil { request = NewDeleteTargetGroupsRequest() } response = NewDeleteTargetGroupsResponse() err = c.Send(request, response) return } func NewDeregisterTargetGroupInstancesRequest() (request *DeregisterTargetGroupInstancesRequest) { request = &DeregisterTargetGroupInstancesRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeregisterTargetGroupInstances") return } func NewDeregisterTargetGroupInstancesResponse() (response *DeregisterTargetGroupInstancesResponse) { response = &DeregisterTargetGroupInstancesResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 将服务器从目标组中解绑。 // 本接口为异步接口,本接口返回成功后需以返回的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) DeregisterTargetGroupInstances(request *DeregisterTargetGroupInstancesRequest) (response *DeregisterTargetGroupInstancesResponse, err error) { if request == nil { request = NewDeregisterTargetGroupInstancesRequest() } response = NewDeregisterTargetGroupInstancesResponse() err = c.Send(request, response) return } func NewDeregisterTargetsRequest() (request *DeregisterTargetsRequest) { request = &DeregisterTargetsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeregisterTargets") return } func NewDeregisterTargetsResponse() (response *DeregisterTargetsResponse) { response = &DeregisterTargetsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DeregisterTargets 接口用来将一台或多台后端服务从负载均衡的监听器或转发规则上解绑,对于四层监听器,只需指定监听器ID即可,对于七层监听器,还需通过LocationId或Domain+Url指定转发规则。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) DeregisterTargets(request *DeregisterTargetsRequest) (response *DeregisterTargetsResponse, err error) { if request == nil { request = NewDeregisterTargetsRequest() } response = NewDeregisterTargetsResponse() err = c.Send(request, response) return } func NewDeregisterTargetsFromClassicalLBRequest() (request *DeregisterTargetsFromClassicalLBRequest) { request = &DeregisterTargetsFromClassicalLBRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DeregisterTargetsFromClassicalLB") return } func NewDeregisterTargetsFromClassicalLBResponse() (response *DeregisterTargetsFromClassicalLBResponse) { response = &DeregisterTargetsFromClassicalLBResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DeregisterTargetsFromClassicalLB 接口用于解绑负载均衡后端服务。 // 本接口为异步接口,接口返回成功后,需以返回的 RequestId 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) DeregisterTargetsFromClassicalLB(request *DeregisterTargetsFromClassicalLBRequest) (response *DeregisterTargetsFromClassicalLBResponse, err error) { if request == nil { request = NewDeregisterTargetsFromClassicalLBRequest() } response = NewDeregisterTargetsFromClassicalLBResponse() err = c.Send(request, response) return } func NewDescribeBlockIPListRequest() (request *DescribeBlockIPListRequest) { request = &DescribeBlockIPListRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeBlockIPList") return } func NewDescribeBlockIPListResponse() (response *DescribeBlockIPListResponse) { response = &DescribeBlockIPListResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询一个负载均衡所封禁的IP列表(黑名单)。(接口灰度中,如需使用请提工单) func (c *Client) DescribeBlockIPList(request *DescribeBlockIPListRequest) (response *DescribeBlockIPListResponse, err error) { if request == nil { request = NewDescribeBlockIPListRequest() } response = NewDescribeBlockIPListResponse() err = c.Send(request, response) return } func NewDescribeBlockIPTaskRequest() (request *DescribeBlockIPTaskRequest) { request = &DescribeBlockIPTaskRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeBlockIPTask") return } func NewDescribeBlockIPTaskResponse() (response *DescribeBlockIPTaskResponse) { response = &DescribeBlockIPTaskResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 根据 ModifyBlockIPList 接口返回的异步任务的ID,查询封禁IP(黑名单)异步任务的执行状态。(接口灰度中,如需使用请提工单) func (c *Client) DescribeBlockIPTask(request *DescribeBlockIPTaskRequest) (response *DescribeBlockIPTaskResponse, err error) { if request == nil { request = NewDescribeBlockIPTaskRequest() } response = NewDescribeBlockIPTaskResponse() err = c.Send(request, response) return } func NewDescribeClassicalLBByInstanceIdRequest() (request *DescribeClassicalLBByInstanceIdRequest) { request = &DescribeClassicalLBByInstanceIdRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeClassicalLBByInstanceId") return } func NewDescribeClassicalLBByInstanceIdResponse() (response *DescribeClassicalLBByInstanceIdResponse) { response = &DescribeClassicalLBByInstanceIdResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DescribeClassicalLBByInstanceId用于通过后端实例ID获取传统型负载均衡ID列表 func (c *Client) DescribeClassicalLBByInstanceId(request *DescribeClassicalLBByInstanceIdRequest) (response *DescribeClassicalLBByInstanceIdResponse, err error) { if request == nil { request = NewDescribeClassicalLBByInstanceIdRequest() } response = NewDescribeClassicalLBByInstanceIdResponse() err = c.Send(request, response) return } func NewDescribeClassicalLBHealthStatusRequest() (request *DescribeClassicalLBHealthStatusRequest) { request = &DescribeClassicalLBHealthStatusRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeClassicalLBHealthStatus") return } func NewDescribeClassicalLBHealthStatusResponse() (response *DescribeClassicalLBHealthStatusResponse) { response = &DescribeClassicalLBHealthStatusResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DescribeClassicalLBHealthStatus用于获取传统型负载均衡后端的健康状态 func (c *Client) DescribeClassicalLBHealthStatus(request *DescribeClassicalLBHealthStatusRequest) (response *DescribeClassicalLBHealthStatusResponse, err error) { if request == nil { request = NewDescribeClassicalLBHealthStatusRequest() } response = NewDescribeClassicalLBHealthStatusResponse() err = c.Send(request, response) return } func NewDescribeClassicalLBListenersRequest() (request *DescribeClassicalLBListenersRequest) { request = &DescribeClassicalLBListenersRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeClassicalLBListeners") return } func NewDescribeClassicalLBListenersResponse() (response *DescribeClassicalLBListenersResponse) { response = &DescribeClassicalLBListenersResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DescribeClassicalLBListeners 接口用于获取传统型负载均衡的监听器信息。 func (c *Client) DescribeClassicalLBListeners(request *DescribeClassicalLBListenersRequest) (response *DescribeClassicalLBListenersResponse, err error) { if request == nil { request = NewDescribeClassicalLBListenersRequest() } response = NewDescribeClassicalLBListenersResponse() err = c.Send(request, response) return } func NewDescribeClassicalLBTargetsRequest() (request *DescribeClassicalLBTargetsRequest) { request = &DescribeClassicalLBTargetsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeClassicalLBTargets") return } func NewDescribeClassicalLBTargetsResponse() (response *DescribeClassicalLBTargetsResponse) { response = &DescribeClassicalLBTargetsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DescribeClassicalLBTargets用于获取传统型负载均衡绑定的后端服务 func (c *Client) DescribeClassicalLBTargets(request *DescribeClassicalLBTargetsRequest) (response *DescribeClassicalLBTargetsResponse, err error) { if request == nil { request = NewDescribeClassicalLBTargetsRequest() } response = NewDescribeClassicalLBTargetsResponse() err = c.Send(request, response) return } func NewDescribeListenersRequest() (request *DescribeListenersRequest) { request = &DescribeListenersRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeListeners") return } func NewDescribeListenersResponse() (response *DescribeListenersResponse) { response = &DescribeListenersResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DescribeListeners 接口可根据负载均衡器 ID,监听器的协议或端口作为过滤条件获取监听器列表。如果不指定任何过滤条件,则返回该负载均衡实例下的所有监听器。 func (c *Client) DescribeListeners(request *DescribeListenersRequest) (response *DescribeListenersResponse, err error) { if request == nil { request = NewDescribeListenersRequest() } response = NewDescribeListenersResponse() err = c.Send(request, response) return } func NewDescribeLoadBalancerListByCertIdRequest() (request *DescribeLoadBalancerListByCertIdRequest) { request = &DescribeLoadBalancerListByCertIdRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeLoadBalancerListByCertId") return } func NewDescribeLoadBalancerListByCertIdResponse() (response *DescribeLoadBalancerListByCertIdResponse) { response = &DescribeLoadBalancerListByCertIdResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 根据证书ID查询其在一个地域中所关联到负载均衡实例列表 func (c *Client) DescribeLoadBalancerListByCertId(request *DescribeLoadBalancerListByCertIdRequest) (response *DescribeLoadBalancerListByCertIdResponse, err error) { if request == nil { request = NewDescribeLoadBalancerListByCertIdRequest() } response = NewDescribeLoadBalancerListByCertIdResponse() err = c.Send(request, response) return } func NewDescribeLoadBalancersRequest() (request *DescribeLoadBalancersRequest) { request = &DescribeLoadBalancersRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeLoadBalancers") return } func NewDescribeLoadBalancersResponse() (response *DescribeLoadBalancersResponse) { response = &DescribeLoadBalancersResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询一个地域的负载均衡实例列表 func (c *Client) DescribeLoadBalancers(request *DescribeLoadBalancersRequest) (response *DescribeLoadBalancersResponse, err error) { if request == nil { request = NewDescribeLoadBalancersRequest() } response = NewDescribeLoadBalancersResponse() err = c.Send(request, response) return } func NewDescribeRewriteRequest() (request *DescribeRewriteRequest) { request = &DescribeRewriteRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeRewrite") return } func NewDescribeRewriteResponse() (response *DescribeRewriteResponse) { response = &DescribeRewriteResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DescribeRewrite 接口可根据负载均衡实例ID,查询一个负载均衡实例下转发规则的重定向关系。如果不指定监听器ID或转发规则ID,则返回该负载均衡实例下的所有重定向关系。 func (c *Client) DescribeRewrite(request *DescribeRewriteRequest) (response *DescribeRewriteResponse, err error) { if request == nil { request = NewDescribeRewriteRequest() } response = NewDescribeRewriteResponse() err = c.Send(request, response) return } func NewDescribeTargetGroupInstancesRequest() (request *DescribeTargetGroupInstancesRequest) { request = &DescribeTargetGroupInstancesRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeTargetGroupInstances") return } func NewDescribeTargetGroupInstancesResponse() (response *DescribeTargetGroupInstancesResponse) { response = &DescribeTargetGroupInstancesResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 获取目标组绑定的服务器信息 func (c *Client) DescribeTargetGroupInstances(request *DescribeTargetGroupInstancesRequest) (response *DescribeTargetGroupInstancesResponse, err error) { if request == nil { request = NewDescribeTargetGroupInstancesRequest() } response = NewDescribeTargetGroupInstancesResponse() err = c.Send(request, response) return } func NewDescribeTargetGroupListRequest() (request *DescribeTargetGroupListRequest) { request = &DescribeTargetGroupListRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeTargetGroupList") return } func NewDescribeTargetGroupListResponse() (response *DescribeTargetGroupListResponse) { response = &DescribeTargetGroupListResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 获取目标组列表 func (c *Client) DescribeTargetGroupList(request *DescribeTargetGroupListRequest) (response *DescribeTargetGroupListResponse, err error) { if request == nil { request = NewDescribeTargetGroupListRequest() } response = NewDescribeTargetGroupListResponse() err = c.Send(request, response) return } func NewDescribeTargetGroupsRequest() (request *DescribeTargetGroupsRequest) { request = &DescribeTargetGroupsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeTargetGroups") return } func NewDescribeTargetGroupsResponse() (response *DescribeTargetGroupsResponse) { response = &DescribeTargetGroupsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询目标组信息 func (c *Client) DescribeTargetGroups(request *DescribeTargetGroupsRequest) (response *DescribeTargetGroupsResponse, err error) { if request == nil { request = NewDescribeTargetGroupsRequest() } response = NewDescribeTargetGroupsResponse() err = c.Send(request, response) return } func NewDescribeTargetHealthRequest() (request *DescribeTargetHealthRequest) { request = &DescribeTargetHealthRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeTargetHealth") return } func NewDescribeTargetHealthResponse() (response *DescribeTargetHealthResponse) { response = &DescribeTargetHealthResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DescribeTargetHealth 接口用来获取负载均衡后端服务的健康检查结果,不支持传统型负载均衡。 func (c *Client) DescribeTargetHealth(request *DescribeTargetHealthRequest) (response *DescribeTargetHealthResponse, err error) { if request == nil { request = NewDescribeTargetHealthRequest() } response = NewDescribeTargetHealthResponse() err = c.Send(request, response) return } func NewDescribeTargetsRequest() (request *DescribeTargetsRequest) { request = &DescribeTargetsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeTargets") return } func NewDescribeTargetsResponse() (response *DescribeTargetsResponse) { response = &DescribeTargetsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // DescribeTargets 接口用来查询负载均衡实例的某些监听器绑定的后端服务列表。 func (c *Client) DescribeTargets(request *DescribeTargetsRequest) (response *DescribeTargetsResponse, err error) { if request == nil { request = NewDescribeTargetsRequest() } response = NewDescribeTargetsResponse() err = c.Send(request, response) return } func NewDescribeTaskStatusRequest() (request *DescribeTaskStatusRequest) { request = &DescribeTaskStatusRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DescribeTaskStatus") return } func NewDescribeTaskStatusResponse() (response *DescribeTaskStatusResponse) { response = &DescribeTaskStatusResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口用于查询异步任务的执行状态,对于非查询类的接口(创建/删除负载均衡实例、监听器、规则以及绑定或解绑后端服务等),在接口调用成功后,都需要使用本接口查询任务最终是否执行成功。 func (c *Client) DescribeTaskStatus(request *DescribeTaskStatusRequest) (response *DescribeTaskStatusResponse, err error) { if request == nil { request = NewDescribeTaskStatusRequest() } response = NewDescribeTaskStatusResponse() err = c.Send(request, response) return } func NewDisassociateTargetGroupsRequest() (request *DisassociateTargetGroupsRequest) { request = &DisassociateTargetGroupsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "DisassociateTargetGroups") return } func NewDisassociateTargetGroupsResponse() (response *DisassociateTargetGroupsResponse) { response = &DisassociateTargetGroupsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 解除规则的目标组关联关系。 // 本接口为异步接口,本接口返回成功后需以返回的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) DisassociateTargetGroups(request *DisassociateTargetGroupsRequest) (response *DisassociateTargetGroupsResponse, err error) { if request == nil { request = NewDisassociateTargetGroupsRequest() } response = NewDisassociateTargetGroupsResponse() err = c.Send(request, response) return } func NewManualRewriteRequest() (request *ManualRewriteRequest) { request = &ManualRewriteRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ManualRewrite") return } func NewManualRewriteResponse() (response *ManualRewriteResponse) { response = &ManualRewriteResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 用户手动配置原访问地址和重定向地址,系统自动将原访问地址的请求重定向至对应路径的目的地址。同一域名下可以配置多条路径作为重定向策略,实现http/https之间请求的自动跳转。设置重定向时,需满足如下约束条件:若A已经重定向至B,则A不能再重定向至C(除非先删除老的重定向关系,再建立新的重定向关系),B不能重定向至任何其它地址。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) ManualRewrite(request *ManualRewriteRequest) (response *ManualRewriteResponse, err error) { if request == nil { request = NewManualRewriteRequest() } response = NewManualRewriteResponse() err = c.Send(request, response) return } func NewModifyBlockIPListRequest() (request *ModifyBlockIPListRequest) { request = &ModifyBlockIPListRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyBlockIPList") return } func NewModifyBlockIPListResponse() (response *ModifyBlockIPListResponse) { response = &ModifyBlockIPListResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 修改负载均衡的IP(client IP)封禁黑名单列表,一个转发规则最多支持封禁 2000000 个IP,及黑名单容量为 2000000。 // (接口灰度中,如需使用请提工单) func (c *Client) ModifyBlockIPList(request *ModifyBlockIPListRequest) (response *ModifyBlockIPListResponse, err error) { if request == nil { request = NewModifyBlockIPListRequest() } response = NewModifyBlockIPListResponse() err = c.Send(request, response) return } func NewModifyDomainRequest() (request *ModifyDomainRequest) { request = &ModifyDomainRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyDomain") return } func NewModifyDomainResponse() (response *ModifyDomainResponse) { response = &ModifyDomainResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // ModifyDomain接口用来修改负载均衡七层监听器下的域名。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) ModifyDomain(request *ModifyDomainRequest) (response *ModifyDomainResponse, err error) { if request == nil { request = NewModifyDomainRequest() } response = NewModifyDomainResponse() err = c.Send(request, response) return } func NewModifyDomainAttributesRequest() (request *ModifyDomainAttributesRequest) { request = &ModifyDomainAttributesRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyDomainAttributes") return } func NewModifyDomainAttributesResponse() (response *ModifyDomainAttributesResponse) { response = &ModifyDomainAttributesResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // ModifyDomainAttributes接口用于修改负载均衡7层监听器转发规则的域名级别属性,如修改域名、修改DefaultServer、开启/关闭Http2、修改证书。 // 本接口为异步接口,本接口返回成功后,需以返回的RequestId为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) ModifyDomainAttributes(request *ModifyDomainAttributesRequest) (response *ModifyDomainAttributesResponse, err error) { if request == nil { request = NewModifyDomainAttributesRequest() } response = NewModifyDomainAttributesResponse() err = c.Send(request, response) return } func NewModifyListenerRequest() (request *ModifyListenerRequest) { request = &ModifyListenerRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyListener") return } func NewModifyListenerResponse() (response *ModifyListenerResponse) { response = &ModifyListenerResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // ModifyListener接口用来修改负载均衡监听器的属性,包括监听器名称、健康检查参数、证书信息、转发策略等。本接口不支持传统型负载均衡。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) ModifyListener(request *ModifyListenerRequest) (response *ModifyListenerResponse, err error) { if request == nil { request = NewModifyListenerRequest() } response = NewModifyListenerResponse() err = c.Send(request, response) return } func NewModifyLoadBalancerAttributesRequest() (request *ModifyLoadBalancerAttributesRequest) { request = &ModifyLoadBalancerAttributesRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyLoadBalancerAttributes") return } func NewModifyLoadBalancerAttributesResponse() (response *ModifyLoadBalancerAttributesResponse) { response = &ModifyLoadBalancerAttributesResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 修改负载均衡实例的属性。支持修改负载均衡实例的名称、设置负载均衡的跨域属性。 func (c *Client) ModifyLoadBalancerAttributes(request *ModifyLoadBalancerAttributesRequest) (response *ModifyLoadBalancerAttributesResponse, err error) { if request == nil { request = NewModifyLoadBalancerAttributesRequest() } response = NewModifyLoadBalancerAttributesResponse() err = c.Send(request, response) return } func NewModifyRuleRequest() (request *ModifyRuleRequest) { request = &ModifyRuleRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyRule") return } func NewModifyRuleResponse() (response *ModifyRuleResponse) { response = &ModifyRuleResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // ModifyRule 接口用来修改负载均衡七层监听器下的转发规则的各项属性,包括转发路径、健康检查属性、转发策略等。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) ModifyRule(request *ModifyRuleRequest) (response *ModifyRuleResponse, err error) { if request == nil { request = NewModifyRuleRequest() } response = NewModifyRuleResponse() err = c.Send(request, response) return } func NewModifyTargetGroupAttributeRequest() (request *ModifyTargetGroupAttributeRequest) { request = &ModifyTargetGroupAttributeRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyTargetGroupAttribute") return } func NewModifyTargetGroupAttributeResponse() (response *ModifyTargetGroupAttributeResponse) { response = &ModifyTargetGroupAttributeResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 修改目标组的名称或者默认端口属性 func (c *Client) ModifyTargetGroupAttribute(request *ModifyTargetGroupAttributeRequest) (response *ModifyTargetGroupAttributeResponse, err error) { if request == nil { request = NewModifyTargetGroupAttributeRequest() } response = NewModifyTargetGroupAttributeResponse() err = c.Send(request, response) return } func NewModifyTargetGroupInstancesPortRequest() (request *ModifyTargetGroupInstancesPortRequest) { request = &ModifyTargetGroupInstancesPortRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyTargetGroupInstancesPort") return } func NewModifyTargetGroupInstancesPortResponse() (response *ModifyTargetGroupInstancesPortResponse) { response = &ModifyTargetGroupInstancesPortResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 批量修改目标组服务器端口。 // 本接口为异步接口,本接口返回成功后需以返回的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) ModifyTargetGroupInstancesPort(request *ModifyTargetGroupInstancesPortRequest) (response *ModifyTargetGroupInstancesPortResponse, err error) { if request == nil { request = NewModifyTargetGroupInstancesPortRequest() } response = NewModifyTargetGroupInstancesPortResponse() err = c.Send(request, response) return } func NewModifyTargetGroupInstancesWeightRequest() (request *ModifyTargetGroupInstancesWeightRequest) { request = &ModifyTargetGroupInstancesWeightRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyTargetGroupInstancesWeight") return } func NewModifyTargetGroupInstancesWeightResponse() (response *ModifyTargetGroupInstancesWeightResponse) { response = &ModifyTargetGroupInstancesWeightResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 批量修改目标组的服务器权重。 // 本接口为异步接口,本接口返回成功后需以返回的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) ModifyTargetGroupInstancesWeight(request *ModifyTargetGroupInstancesWeightRequest) (response *ModifyTargetGroupInstancesWeightResponse, err error) { if request == nil { request = NewModifyTargetGroupInstancesWeightRequest() } response = NewModifyTargetGroupInstancesWeightResponse() err = c.Send(request, response) return } func NewModifyTargetPortRequest() (request *ModifyTargetPortRequest) { request = &ModifyTargetPortRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyTargetPort") return } func NewModifyTargetPortResponse() (response *ModifyTargetPortResponse) { response = &ModifyTargetPortResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // ModifyTargetPort接口用于修改监听器绑定的后端服务的端口。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) ModifyTargetPort(request *ModifyTargetPortRequest) (response *ModifyTargetPortResponse, err error) { if request == nil { request = NewModifyTargetPortRequest() } response = NewModifyTargetPortResponse() err = c.Send(request, response) return } func NewModifyTargetWeightRequest() (request *ModifyTargetWeightRequest) { request = &ModifyTargetWeightRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ModifyTargetWeight") return } func NewModifyTargetWeightResponse() (response *ModifyTargetWeightResponse) { response = &ModifyTargetWeightResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // ModifyTargetWeight 接口用于修改负载均衡绑定的后端服务的转发权重。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) ModifyTargetWeight(request *ModifyTargetWeightRequest) (response *ModifyTargetWeightResponse, err error) { if request == nil { request = NewModifyTargetWeightRequest() } response = NewModifyTargetWeightResponse() err = c.Send(request, response) return } func NewRegisterTargetGroupInstancesRequest() (request *RegisterTargetGroupInstancesRequest) { request = &RegisterTargetGroupInstancesRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "RegisterTargetGroupInstances") return } func NewRegisterTargetGroupInstancesResponse() (response *RegisterTargetGroupInstancesResponse) { response = &RegisterTargetGroupInstancesResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 注册服务器到目标组。 // 本接口为异步接口,本接口返回成功后需以返回的 RequestID 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) RegisterTargetGroupInstances(request *RegisterTargetGroupInstancesRequest) (response *RegisterTargetGroupInstancesResponse, err error) { if request == nil { request = NewRegisterTargetGroupInstancesRequest() } response = NewRegisterTargetGroupInstancesResponse() err = c.Send(request, response) return } func NewRegisterTargetsRequest() (request *RegisterTargetsRequest) { request = &RegisterTargetsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "RegisterTargets") return } func NewRegisterTargetsResponse() (response *RegisterTargetsResponse) { response = &RegisterTargetsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // RegisterTargets 接口用来将一台或多台后端服务绑定到负载均衡的监听器(或7层转发规则),在此之前您需要先行创建相关的4层监听器或7层转发规则。对于四层监听器(TCP、UDP),只需指定监听器ID即可,对于七层监听器(HTTP、HTTPS),还需通过LocationId或者Domain+Url指定转发规则。 // 本接口为异步接口,本接口返回成功后需以返回的RequestID为入参,调用DescribeTaskStatus接口查询本次任务是否成功。 func (c *Client) RegisterTargets(request *RegisterTargetsRequest) (response *RegisterTargetsResponse, err error) { if request == nil { request = NewRegisterTargetsRequest() } response = NewRegisterTargetsResponse() err = c.Send(request, response) return } func NewRegisterTargetsWithClassicalLBRequest() (request *RegisterTargetsWithClassicalLBRequest) { request = &RegisterTargetsWithClassicalLBRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "RegisterTargetsWithClassicalLB") return } func NewRegisterTargetsWithClassicalLBResponse() (response *RegisterTargetsWithClassicalLBResponse) { response = &RegisterTargetsWithClassicalLBResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // RegisterTargetsWithClassicalLB 接口用于绑定后端服务到传统型负载均衡。 // 本接口为异步接口,接口返回成功后,需以返回的 RequestId 为入参,调用 DescribeTaskStatus 接口查询本次任务是否成功。 func (c *Client) RegisterTargetsWithClassicalLB(request *RegisterTargetsWithClassicalLBRequest) (response *RegisterTargetsWithClassicalLBResponse, err error) { if request == nil { request = NewRegisterTargetsWithClassicalLBRequest() } response = NewRegisterTargetsWithClassicalLBResponse() err = c.Send(request, response) return } func NewReplaceCertForLoadBalancersRequest() (request *ReplaceCertForLoadBalancersRequest) { request = &ReplaceCertForLoadBalancersRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "ReplaceCertForLoadBalancers") return } func NewReplaceCertForLoadBalancersResponse() (response *ReplaceCertForLoadBalancersResponse) { response = &ReplaceCertForLoadBalancersResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // ReplaceCertForLoadBalancers 接口用以替换负载均衡实例所关联的证书,对于各个地域的负载均衡,如果指定的老的证书ID与其有关联关系,则会先解除关联,再建立新证书与该负载均衡的关联关系。 // 此接口支持替换服务端证书或客户端证书。 // 需要使用的新证书,可以通过传入证书ID来指定,如果不指定证书ID,则必须传入证书内容等相关信息,用以新建证书并绑定至负载均衡。 // 注:本接口仅可从广州地域调用。 func (c *Client) ReplaceCertForLoadBalancers(request *ReplaceCertForLoadBalancersRequest) (response *ReplaceCertForLoadBalancersResponse, err error) { if request == nil { request = NewReplaceCertForLoadBalancersRequest() } response = NewReplaceCertForLoadBalancersResponse() err = c.Send(request, response) return } func NewSetLoadBalancerSecurityGroupsRequest() (request *SetLoadBalancerSecurityGroupsRequest) { request = &SetLoadBalancerSecurityGroupsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "SetLoadBalancerSecurityGroups") return } func NewSetLoadBalancerSecurityGroupsResponse() (response *SetLoadBalancerSecurityGroupsResponse) { response = &SetLoadBalancerSecurityGroupsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // SetLoadBalancerSecurityGroups 接口支持对一个公网负载均衡实例执行设置(绑定、解绑)安全组操作。查询一个负载均衡实例目前已绑定的安全组,可使用 DescribeLoadBalancers 接口。本接口是set语义, // 绑定操作时,入参需要传入负载均衡实例要绑定的所有安全组(已绑定的+新增绑定的)。 // 解绑操作时,入参需要传入负载均衡实例执行解绑后所绑定的所有安全组;如果要解绑所有安全组,可不传此参数,或传入空数组。注意:内网负载均衡不支持绑定安全组。 func (c *Client) SetLoadBalancerSecurityGroups(request *SetLoadBalancerSecurityGroupsRequest) (response *SetLoadBalancerSecurityGroupsResponse, err error) { if request == nil { request = NewSetLoadBalancerSecurityGroupsRequest() } response = NewSetLoadBalancerSecurityGroupsResponse() err = c.Send(request, response) return } func NewSetSecurityGroupForLoadbalancersRequest() (request *SetSecurityGroupForLoadbalancersRequest) { request = &SetSecurityGroupForLoadbalancersRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("clb", APIVersion, "SetSecurityGroupForLoadbalancers") return } func NewSetSecurityGroupForLoadbalancersResponse() (response *SetSecurityGroupForLoadbalancersResponse) { response = &SetSecurityGroupForLoadbalancersResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 绑定或解绑一个安全组到多个公网负载均衡实例。注意:内网负载均衡不支持绑定安全组。 func (c *Client) SetSecurityGroupForLoadbalancers(request *SetSecurityGroupForLoadbalancersRequest) (response *SetSecurityGroupForLoadbalancersResponse, err error) { if request == nil { request = NewSetSecurityGroupForLoadbalancersRequest() } response = NewSetSecurityGroupForLoadbalancersResponse() err = c.Send(request, response) return }
package codegen const goTemplate = ` // Generated by Meduza. Do not rewrite unless you know what you're doing... package model import "github.com/EverythingMe/meduza/schema" {{ define "Column" }}\ {{ .GoName }} schema.{{.Type}} ~db:"{{.Name}}\ {{ if .Options.required }},required{{end}}"\ {{ if .Options.max_len }} maxlen:"{{ .Options.max_len }}"{{end}}\ {{ if .Options.subtype }} type:"{{ .Options.subtype }}"{{end}}\ {{ if .HasDefault }} default:"{{ getDefault .Default "go" }}"{{end}}\ ~ {{end}} {{ $sc := .Name }}\ const Schema_{{.Name}} = "{{.Name}}" {{ range .Tables }} const Table_{{ .BaseName}} = "{{.BaseName}}" {{ if .Comment }}// {{ .Class }} {{ .Comment }} {{ end }} type {{ .Class }} struct { _ struct{} ~table:"{{.BaseName}}" schema:"{{ $sc }}"~ Id schema.Key ~db:",primary"~ {{ range .Columns }}\ {{ if ne .Comment ""}} // {{ .Comment }} {{end}}\ {{ template "Column" . }}\ {{ end }}\ } {{ end }}`
package main import ( "fmt" "testing" ) func scoreChecker(input []Frame, expectedScore int, expectedError error) error { score, err := GetScore(input) if err != expectedError && !(err != nil && expectedError != nil && err.Error() == expectedError.Error()) { return fmt.Errorf("Score error : %+v, expected %+v", err, expectedError) } if score != expectedScore { return fmt.Errorf("Score : %d, expected %d", score, expectedScore) } return nil } func TestNullScore(t *testing.T) { input := []Frame{} expected := 0 if err := scoreChecker(input, expected, nil); err != nil { t.Fatalf("%+v\n", err) } } func TestPositifNumber(t *testing.T){ input := []Frame{{0,1},{13,2},{0,1},{13,2},{0,1},{13,2},{0,1},{13,2},{0,1},{13,2}} expected := 0 if err := scoreChecker(input, expected, nil); err != nil { t.Fatalf("%+v\n", err) } } func TestScore(t *testing.T) { input := []Frame{{1,2},{1,2},{1,2},{1,2},{1,2},{1,2},{1,2},{1,2},{1,2},{1,2}} expected := 30 if err := scoreChecker(input, expected, nil); err != nil { t.Fatalf("%+v\n", err) } } func TestNumberOfIndex(t *testing.T){ input := []Frame{{4,5},{5,6},{4,5},{5,6},{4,5},{5,6},{4,5},{5,6},{4,5},{5,6}} expected := 200 if err := scoreChecker(input, expected, nil); err != nil { t.Fatalf("%+v\n", err) } } func TestSomme(t *testing.T) { input := []Frame{{10, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}} expected := 0 if err := scoreChecker(input, expected, errExpected); err != nil { t.Fatalf("%+v\n", err) } } func testspare(t *testing.T) { input := []Frame{{8,2}, {5,1},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}} expected := 10+5+5+1 if err := scoreChecker(input, expected, nil); err != nil { t.Fatalf("%+v\n", err) } } func TestSpareEnd(t *testing.T) { input := []Frame{{0, 3}, {5, 1}, {3, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {6,4}} expected := 0+3+5+1+3+6+4 if err := scoreChecker(input, expected, nil); err != nil { t.Fatalf("%+v\n", err) } } func TestStrike(t *testing.T) { input := []Frame{{10, 0}, {6,2}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}} expected := 10+6+2+6+2 if err := scoreChecker(input, expected, nil); err != nil { t.Fatalf("%+v\n", err) } } func TestStrikeEnd(t *testing.T) { input := []Frame{{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {10, 0}} expected := 10 if err := scoreChecker(input, expected, nil); err != nil { t.Fatalf("%+v\n", err) } }
package clock import "fmt" // Clock represents a time without dates. type Clock struct { hour, minute int } // New returns a new Clock at hour:minute. func New(hour, minute int) Clock { hour += minute / 60 minute %= 60 if minute < 0 { minute += 60 hour -= 1 } hour %= 24 if hour < 0 { hour += 24 } return Clock{hour: hour, minute: minute} } // String returns the time in the format "hh:mm". func (c Clock) String() string { return fmt.Sprintf("%02d:%02d", c.hour, c.minute) } // Add returns a clock at time + minutes. func (c Clock) Add(minutes int) Clock { return New(c.hour, c.minute+minutes) } // Subtract returns a clock at time - minutes. func (c Clock) Subtract(minutes int) Clock { return New(c.hour, c.minute-minutes) }
package user import ( "github.com/gin-gonic/gin" "net/http" "github.com/jinzhu/gorm" "fmt" "beaver/user/usermodel" "beaver/apputils" ) func UserRouter(router *gin.RouterGroup, db gorm.DB) { router.GET("", func(ctx *gin.Context) { result := usermodel.Fetch(&db) fmt.Println(result) ctx.JSON(http.StatusOK, result.Value) }) router.GET("/:id", func(ctx *gin.Context) { userId := ctx.Param("id") user := usermodel.FetchUserById(userId, &db) ctx.JSON(http.StatusOK, user.Value) }) router.POST("", func(ctx *gin.Context) { user := usermodel.UserJSON{} ctx.BindJSON(&user) result := usermodel.Create(&user, &db) if result.Error != nil { ctx.JSON(http.StatusBadRequest, utils.HTTPError{Error:error(result.Error)}) } else { ctx.JSON(http.StatusOK, result.Value) } }) router.DELETE("/:id", func(ctx *gin.Context) { userId := ctx.Param("id") result := usermodel.Remove(userId, &db) if result.Error != nil { ctx.JSON(http.StatusBadRequest, utils.HTTPError{Error:error(result.Error)}) } else { ctx.JSON(http.StatusOK, nil) } }) router.PUT("/:id", func(ctx *gin.Context) { user := usermodel.UserJSON{} ctx.BindJSON(&user) result := usermodel.Update(ctx.Param("id"), &user, &db) if result.Error != nil { ctx.JSON(http.StatusBadRequest, utils.HTTPError{Error:error(result.Error)}) } else { ctx.JSON(http.StatusOK, result.Value) } }) }
package orm import ( "DataApi.Go/database/models/YPA" "DataApi.Go/lib/common" "fmt" "github.com/jinzhu/gorm" "strings" ) type YpaSourceReportDaily = YPA.YpaSourceReportDaily func SelectBetweenDailyYpa(db *gorm.DB, startDate int, endDate int) []common.JSON { table := "ypa_source_report_daily" var ypaSourceReportDaily YpaSourceReportDaily rows, err := db.Table(table).Model(&ypaSourceReportDaily).Where("date BETWEEN ? AND ?", startDate, endDate).Rows() if err != nil { fmt.Println(err) } defer rows.Close() var rowsList []common.JSON for rows.Next() { var ypaSourceReportDaily YpaSourceReportDaily err := db.ScanRows(rows, &ypaSourceReportDaily) if err != nil { fmt.Println(err) return nil } rowsList = append(rowsList, common.JSON{ "date":strings.Replace(ypaSourceReportDaily.Date, "-", "", 2), "revenue": ypaSourceReportDaily.Revenue, }) } return rowsList }
// Copyright © 2017 Jimmy Song // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "fmt" "github.com/rootsongjc/magpie/docker" "github.com/rootsongjc/magpie/tool" "github.com/rootsongjc/magpie/yarn" "github.com/spf13/cobra" "github.com/spf13/viper" ) var distribute bool var view bool var statusCmd = &cobra.Command{ Use: "status", Short: "Get yarn cluster status", Long: "Get the resource usage, node status of yarn cluster.", Run: func(cmd *cobra.Command, args []string) { cluster_names := viper.GetStringSlice("clusters.cluster_name") if distribute == false && view == false { if clustername == "" { yarn.Get_yarn_status(cluster_names) } else { names := []string{clustername} yarn.Get_yarn_status(names) } if clustername == "" { docker.Get_docker_status(cluster_names) } else { names := []string{clustername} docker.Get_docker_status(names) } fmt.Println("============NODEMANAGER AND DOCKER CONTAINERS COMPARATION===========") fmt.Println("CLUSTER\tNODEMANAGER\tCONTAINER\tRESULT") if clustername == "" { for _, c := range cluster_names { tool.Compare_yarn_docker_cluster(c) } } else { tool.Compare_yarn_docker_cluster(clustername) } } if distribute == true { yarn.Yarn_distribution(clustername) } if view == true { if clustername == "" { fmt.Println("You must specify the clusteranem with -c") } else { yarn.Yarn_view(clustername) } } }, } func init() { yarnCmd.AddCommand(statusCmd) statusCmd.Flags().StringVarP(&clustername, "clustername", "c", "", "Yarn cluster name") statusCmd.Flags().BoolVarP(&distribute, "distribute", "d", false, "Yarn nodemanager distribution") statusCmd.Flags().BoolVarP(&view, "view", "v", false, "Show the yarn cluster containers view") }
package pt import ( "bufio" "fmt" "io" "net" "time" "golang.org/x/net/proxy" "net/url" "strconv" "encoding/binary" ) const ( socksVersion = 0x04 socksCmdConnect = 0x01 socksResponseVersion = 0x00 socksRequestGranted = 0x5a socksRequestRejected = 0x5b ) // Put a sanity timeout on how long we wait for a SOCKS request. const socksRequestTimeout = 5 * time.Second // SocksRequest describes a SOCKS request. type SocksRequest struct { // The endpoint requested by the client as a "host:port" string. Target string // The userid string sent by the client. Username string // The parsed contents of Username as a key–value mapping. Args Args } // SocksConn encapsulates a net.Conn and information associated with a SOCKS request. type SocksConn struct { net.Conn Req SocksRequest } // Send a message to the proxy client that access to the given address is // granted. If the IP field inside addr is not an IPv4 address, the IP portion // of the response will be four zero bytes. func (conn *SocksConn) Grant(addr *net.TCPAddr) error { return sendSocks4aResponseGranted(conn, addr) } // Send a message to the proxy client that access was rejected or failed. func (conn *SocksConn) Reject() error { return sendSocks4aResponseRejected(conn) } // SocksListener wraps a net.Listener in order to read a SOCKS request on Accept. // // func handleConn(conn *pt.SocksConn) error { // defer conn.Close() // remote, err := net.Dial("tcp", conn.Req.Target) // if err != nil { // conn.Reject() // return err // } // defer remote.Close() // err = conn.Grant(remote.RemoteAddr().(*net.TCPAddr)) // if err != nil { // return err // } // // do something with conn and remote // return nil // } // ... // ln, err := pt.ListenSocks("tcp", "127.0.0.1:0") // if err != nil { // panic(err.Error()) // } // for { // conn, err := ln.AcceptSocks() // if err != nil { // log.Printf("accept error: %s", err) // if e, ok := err.(net.Error); ok && e.Temporary() { // continue // } // break // } // go handleConn(conn) // } type SocksListener struct { net.Listener } // Open a net.Listener according to network and laddr, and return it as a // SocksListener. func ListenSocks(network, laddr string) (*SocksListener, error) { ln, err := net.Listen(network, laddr) if err != nil { return nil, err } return NewSocksListener(ln), nil } // Create a new SocksListener wrapping the given net.Listener. func NewSocksListener(ln net.Listener) *SocksListener { return &SocksListener{ln} } // Accept is the same as AcceptSocks, except that it returns a generic net.Conn. // It is present for the sake of satisfying the net.Listener interface. func (ln *SocksListener) Accept() (net.Conn, error) { return ln.AcceptSocks() } // Call Accept on the wrapped net.Listener, do SOCKS negotiation, and return a // SocksConn. After accepting, you must call either conn.Grant or conn.Reject // (presumably after trying to connect to conn.Req.Target). // // Errors returned by AcceptSocks may be temporary (for example, EOF while // reading the request, or a badly formatted userid string), or permanent (e.g., // the underlying socket is closed). You can determine whether an error is // temporary and take appropriate action with a type conversion to net.Error. // For example: // // for { // conn, err := ln.AcceptSocks() // if err != nil { // if e, ok := err.(net.Error); ok && e.Temporary() { // log.Printf("temporary accept error; trying again: %s", err) // continue // } // log.Printf("permanent accept error; giving up: %s", err) // break // } // go handleConn(conn) // } func (ln *SocksListener) AcceptSocks() (*SocksConn, error) { retry: c, err := ln.Listener.Accept() if err != nil { return nil, err } conn := new(SocksConn) conn.Conn = c err = conn.SetDeadline(time.Now().Add(socksRequestTimeout)) if err != nil { conn.Close() goto retry } conn.Req, err = readSocks4aConnect(conn) if err != nil { conn.Close() goto retry } err = conn.SetDeadline(time.Time{}) if err != nil { conn.Close() goto retry } return conn, nil } // Returns "socks4", suitable to be included in a call to Cmethod. func (ln *SocksListener) Version() string { return "socks4" } // Read a SOCKS4a connect request. Returns a SocksRequest. func readSocks4aConnect(s io.Reader) (req SocksRequest, err error) { r := bufio.NewReader(s) var h [8]byte _, err = io.ReadFull(r, h[:]) if err != nil { return } if h[0] != socksVersion { err = fmt.Errorf("SOCKS header had version 0x%02x, not 0x%02x", h[0], socksVersion) return } if h[1] != socksCmdConnect { err = fmt.Errorf("SOCKS header had command 0x%02x, not 0x%02x", h[1], socksCmdConnect) return } var usernameBytes []byte usernameBytes, err = r.ReadBytes('\x00') if err != nil { return } req.Username = string(usernameBytes[:len(usernameBytes)-1]) req.Args, err = parseClientParameters(req.Username) if err != nil { return } var port int var host string port = int(h[2])<<8 | int(h[3])<<0 if h[4] == 0 && h[5] == 0 && h[6] == 0 && h[7] != 0 { var hostBytes []byte hostBytes, err = r.ReadBytes('\x00') if err != nil { fmt.Println(err.Error()) return } host = string(hostBytes[:len(hostBytes)-1]) } else { host = net.IPv4(h[4], h[5], h[6], h[7]).String() } if r.Buffered() != 0 { err = fmt.Errorf("%d bytes left after SOCKS header", r.Buffered()) return } req.Target = fmt.Sprintf("%s:%d", host, port) return } // Send a SOCKS4a response with the given code and address. If the IP field // inside addr is not an IPv4 address, the IP portion of the response will be // four zero bytes. func sendSocks4aResponse(w io.Writer, code byte, addr *net.TCPAddr) error { var resp [8]byte resp[0] = socksResponseVersion resp[1] = code resp[2] = byte((addr.Port >> 8) & 0xff) resp[3] = byte((addr.Port >> 0) & 0xff) ipv4 := addr.IP.To4() if ipv4 != nil { resp[4] = ipv4[0] resp[5] = ipv4[1] resp[6] = ipv4[2] resp[7] = ipv4[3] } _, err := w.Write(resp[:]) return err } var emptyAddr = net.TCPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 0} // Send a SOCKS4a response code 0x5a. func sendSocks4aResponseGranted(w io.Writer, addr *net.TCPAddr) error { return sendSocks4aResponse(w, socksRequestGranted, addr) } // Send a SOCKS4a response code 0x5b (with an all-zero address). func sendSocks4aResponseRejected(w io.Writer) error { return sendSocks4aResponse(w, socksRequestRejected, &emptyAddr) } //From https://github.com/Bogdan-D/go-socks4 func SocksInit() { proxy.RegisterDialerType("socks4", func(u *url.URL, d proxy.Dialer) (proxy.Dialer, error) { return &socks4{url: u, dialer: d}, nil }) } const ( socks_version = 0x04 socks_connect = 0x01 socks_bind = 0x02 socks_ident = "nobody@0.0.0.0" access_granted = 0x5a access_rejected = 0x5b access_identd_required = 0x5c access_identd_failed = 0x5d ErrWrongURL = "wrong server url" ErrWrongConnType = "no support for connections of type" ErrConnFailed = "connection failed to socks4 server" ErrHostUnknown = "unable to find IP address of host" ErrSocksServer = "socks4 server error" ErrConnRejected = "connection rejected" ErrIdentRequired = "socks4 server require valid identd" ) type socks4 struct { url *url.URL dialer proxy.Dialer } type socks4Error struct { message string details interface{} } func (s *socks4Error) String() string { return s.message } func (s *socks4Error) Error() string { if s.details == nil { return s.message } return fmt.Sprintf("%s: %v", s.message, s.details) } func Dial(network, address string) (net.Conn, error) { var socksProx *socks4 return socksProx.Dial(network, address) } func (s *socks4) Dial(network, addr string) (c net.Conn, err error) { var buf []byte switch network { case "tcp", "tcp4": default: return nil, &socks4Error{message: ErrWrongConnType, details: network} } c, err = s.dialer.Dial(network, s.url.Host) if err != nil { return nil, &socks4Error{message: ErrConnFailed, details: err} } host, port, err := net.SplitHostPort(addr) if err != nil { return nil, &socks4Error{message: ErrWrongURL, details: err} } // ipAddr := net.ParseIP(host) socksV4a := false var ip4 net.IP if ipAddr != nil{ ip, err := net.ResolveIPAddr("ip4", host) if err != nil { return nil, &socks4Error{message: ErrHostUnknown, details: err} } ip4 = ip.IP.To4() }else { socksV4a = true ip, err := net.ResolveIPAddr("ip4", "0.0.0.255") if err != nil { return nil, &socks4Error{message: ErrHostUnknown, details: err} } ip4 = ip.IP.To4() } var bport [2]byte iport, _ := strconv.Atoi(port) binary.BigEndian.PutUint16(bport[:], uint16(iport)) buf = []byte{socks_version, socks_connect} buf = append(buf, bport[:]...) buf = append(buf, ip4...) //buf = append(buf, socks_ident...) buf = append(buf, 0) if socksV4a { //hostLength := utf8.RuneCountInString(host) //hostBytes := []byte(host) buf = append(buf, ipAddr[12:16]...) } i, err := c.Write(buf) if err != nil { return nil, &socks4Error{message: ErrSocksServer, details: err} } if l := len(buf); i != l { return nil, &socks4Error{message: ErrSocksServer, details: fmt.Sprintf("write %d bytes, expected %d", i, l)} } var resp [8]byte i, err = c.Read(resp[:]) if err != nil && err != io.EOF { return nil, &socks4Error{message: ErrSocksServer, details: err} } if i != 8 { return nil, &socks4Error{message: ErrSocksServer, details: fmt.Sprintf("read %d bytes, expected 8", i)} } switch resp[1] { case access_granted: return c, nil case access_identd_required, access_identd_failed: return nil, &socks4Error{message: ErrIdentRequired, details: strconv.FormatInt(int64(resp[1]), 16)} default: c.Close() return nil, &socks4Error{message: ErrConnRejected, details: strconv.FormatInt(int64(resp[1]), 16)} } }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" betapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/clouddeploy/beta/clouddeploy_beta_go_proto" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/clouddeploy/beta" ) // DeliveryPipelineServer implements the gRPC interface for DeliveryPipeline. type DeliveryPipelineServer struct{} // ProtoToDeliveryPipelineSerialPipeline converts a DeliveryPipelineSerialPipeline object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipeline(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipeline) *beta.DeliveryPipelineSerialPipeline { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipeline{} for _, r := range p.GetStages() { obj.Stages = append(obj.Stages, *ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStages(r)) } return obj } // ProtoToDeliveryPipelineSerialPipelineStages converts a DeliveryPipelineSerialPipelineStages object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStages(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStages) *beta.DeliveryPipelineSerialPipelineStages { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStages{ TargetId: dcl.StringOrNil(p.GetTargetId()), Strategy: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategy(p.GetStrategy()), } for _, r := range p.GetProfiles() { obj.Profiles = append(obj.Profiles, r) } for _, r := range p.GetDeployParameters() { obj.DeployParameters = append(obj.DeployParameters, *ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesDeployParameters(r)) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategy converts a DeliveryPipelineSerialPipelineStagesStrategy object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategy(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategy) *beta.DeliveryPipelineSerialPipelineStagesStrategy { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategy{ Standard: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandard(p.GetStandard()), Canary: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanary(p.GetCanary()), } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyStandard converts a DeliveryPipelineSerialPipelineStagesStrategyStandard object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandard(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandard) *beta.DeliveryPipelineSerialPipelineStagesStrategyStandard { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyStandard{ Verify: dcl.Bool(p.GetVerify()), Predeploy: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy(p.GetPredeploy()), Postdeploy: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy(p.GetPostdeploy()), } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy converts a DeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy) *beta.DeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy{} for _, r := range p.GetActions() { obj.Actions = append(obj.Actions, r) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy converts a DeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy) *beta.DeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy{} for _, r := range p.GetActions() { obj.Actions = append(obj.Actions, r) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanary converts a DeliveryPipelineSerialPipelineStagesStrategyCanary object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanary(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanary) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanary { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanary{ RuntimeConfig: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig(p.GetRuntimeConfig()), CanaryDeployment: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment(p.GetCanaryDeployment()), CustomCanaryDeployment: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment(p.GetCustomCanaryDeployment()), } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig{ Kubernetes: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes(p.GetKubernetes()), CloudRun: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun(p.GetCloudRun()), } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes{ GatewayServiceMesh: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh(p.GetGatewayServiceMesh()), ServiceNetworking: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking(p.GetServiceNetworking()), } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh{ HttpRoute: dcl.StringOrNil(p.GetHttpRoute()), Service: dcl.StringOrNil(p.GetService()), Deployment: dcl.StringOrNil(p.GetDeployment()), RouteUpdateWaitTime: dcl.StringOrNil(p.GetRouteUpdateWaitTime()), } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking{ Service: dcl.StringOrNil(p.GetService()), Deployment: dcl.StringOrNil(p.GetDeployment()), DisablePodOverprovisioning: dcl.Bool(p.GetDisablePodOverprovisioning()), } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun{ AutomaticTrafficControl: dcl.Bool(p.GetAutomaticTrafficControl()), } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment{ Verify: dcl.Bool(p.GetVerify()), Predeploy: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy(p.GetPredeploy()), Postdeploy: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy(p.GetPostdeploy()), } for _, r := range p.GetPercentages() { obj.Percentages = append(obj.Percentages, r) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy{} for _, r := range p.GetActions() { obj.Actions = append(obj.Actions, r) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy{} for _, r := range p.GetActions() { obj.Actions = append(obj.Actions, r) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment{} for _, r := range p.GetPhaseConfigs() { obj.PhaseConfigs = append(obj.PhaseConfigs, *ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs(r)) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs{ PhaseId: dcl.StringOrNil(p.GetPhaseId()), Percentage: dcl.Int64OrNil(p.GetPercentage()), Verify: dcl.Bool(p.GetVerify()), Predeploy: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy(p.GetPredeploy()), Postdeploy: ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy(p.GetPostdeploy()), } for _, r := range p.GetProfiles() { obj.Profiles = append(obj.Profiles, r) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy{} for _, r := range p.GetActions() { obj.Actions = append(obj.Actions, r) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy) *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy{} for _, r := range p.GetActions() { obj.Actions = append(obj.Actions, r) } return obj } // ProtoToDeliveryPipelineSerialPipelineStagesDeployParameters converts a DeliveryPipelineSerialPipelineStagesDeployParameters object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineSerialPipelineStagesDeployParameters(p *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesDeployParameters) *beta.DeliveryPipelineSerialPipelineStagesDeployParameters { if p == nil { return nil } obj := &beta.DeliveryPipelineSerialPipelineStagesDeployParameters{} return obj } // ProtoToDeliveryPipelineCondition converts a DeliveryPipelineCondition object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineCondition(p *betapb.ClouddeployBetaDeliveryPipelineCondition) *beta.DeliveryPipelineCondition { if p == nil { return nil } obj := &beta.DeliveryPipelineCondition{ PipelineReadyCondition: ProtoToClouddeployBetaDeliveryPipelineConditionPipelineReadyCondition(p.GetPipelineReadyCondition()), TargetsPresentCondition: ProtoToClouddeployBetaDeliveryPipelineConditionTargetsPresentCondition(p.GetTargetsPresentCondition()), TargetsTypeCondition: ProtoToClouddeployBetaDeliveryPipelineConditionTargetsTypeCondition(p.GetTargetsTypeCondition()), } return obj } // ProtoToDeliveryPipelineConditionPipelineReadyCondition converts a DeliveryPipelineConditionPipelineReadyCondition object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineConditionPipelineReadyCondition(p *betapb.ClouddeployBetaDeliveryPipelineConditionPipelineReadyCondition) *beta.DeliveryPipelineConditionPipelineReadyCondition { if p == nil { return nil } obj := &beta.DeliveryPipelineConditionPipelineReadyCondition{ Status: dcl.Bool(p.GetStatus()), UpdateTime: dcl.StringOrNil(p.GetUpdateTime()), } return obj } // ProtoToDeliveryPipelineConditionTargetsPresentCondition converts a DeliveryPipelineConditionTargetsPresentCondition object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineConditionTargetsPresentCondition(p *betapb.ClouddeployBetaDeliveryPipelineConditionTargetsPresentCondition) *beta.DeliveryPipelineConditionTargetsPresentCondition { if p == nil { return nil } obj := &beta.DeliveryPipelineConditionTargetsPresentCondition{ Status: dcl.Bool(p.GetStatus()), UpdateTime: dcl.StringOrNil(p.GetUpdateTime()), } for _, r := range p.GetMissingTargets() { obj.MissingTargets = append(obj.MissingTargets, r) } return obj } // ProtoToDeliveryPipelineConditionTargetsTypeCondition converts a DeliveryPipelineConditionTargetsTypeCondition object from its proto representation. func ProtoToClouddeployBetaDeliveryPipelineConditionTargetsTypeCondition(p *betapb.ClouddeployBetaDeliveryPipelineConditionTargetsTypeCondition) *beta.DeliveryPipelineConditionTargetsTypeCondition { if p == nil { return nil } obj := &beta.DeliveryPipelineConditionTargetsTypeCondition{ Status: dcl.Bool(p.GetStatus()), ErrorDetails: dcl.StringOrNil(p.GetErrorDetails()), } return obj } // ProtoToDeliveryPipeline converts a DeliveryPipeline resource from its proto representation. func ProtoToDeliveryPipeline(p *betapb.ClouddeployBetaDeliveryPipeline) *beta.DeliveryPipeline { obj := &beta.DeliveryPipeline{ Name: dcl.StringOrNil(p.GetName()), Uid: dcl.StringOrNil(p.GetUid()), Description: dcl.StringOrNil(p.GetDescription()), CreateTime: dcl.StringOrNil(p.GetCreateTime()), UpdateTime: dcl.StringOrNil(p.GetUpdateTime()), SerialPipeline: ProtoToClouddeployBetaDeliveryPipelineSerialPipeline(p.GetSerialPipeline()), Condition: ProtoToClouddeployBetaDeliveryPipelineCondition(p.GetCondition()), Etag: dcl.StringOrNil(p.GetEtag()), Project: dcl.StringOrNil(p.GetProject()), Location: dcl.StringOrNil(p.GetLocation()), Suspended: dcl.Bool(p.GetSuspended()), } return obj } // DeliveryPipelineSerialPipelineToProto converts a DeliveryPipelineSerialPipeline object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineToProto(o *beta.DeliveryPipelineSerialPipeline) *betapb.ClouddeployBetaDeliveryPipelineSerialPipeline { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipeline{} sStages := make([]*betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStages, len(o.Stages)) for i, r := range o.Stages { sStages[i] = ClouddeployBetaDeliveryPipelineSerialPipelineStagesToProto(&r) } p.SetStages(sStages) return p } // DeliveryPipelineSerialPipelineStagesToProto converts a DeliveryPipelineSerialPipelineStages object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesToProto(o *beta.DeliveryPipelineSerialPipelineStages) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStages { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStages{} p.SetTargetId(dcl.ValueOrEmptyString(o.TargetId)) p.SetStrategy(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyToProto(o.Strategy)) sProfiles := make([]string, len(o.Profiles)) for i, r := range o.Profiles { sProfiles[i] = r } p.SetProfiles(sProfiles) sDeployParameters := make([]*betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesDeployParameters, len(o.DeployParameters)) for i, r := range o.DeployParameters { sDeployParameters[i] = ClouddeployBetaDeliveryPipelineSerialPipelineStagesDeployParametersToProto(&r) } p.SetDeployParameters(sDeployParameters) return p } // DeliveryPipelineSerialPipelineStagesStrategyToProto converts a DeliveryPipelineSerialPipelineStagesStrategy object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategy) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategy { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategy{} p.SetStandard(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardToProto(o.Standard)) p.SetCanary(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryToProto(o.Canary)) return p } // DeliveryPipelineSerialPipelineStagesStrategyStandardToProto converts a DeliveryPipelineSerialPipelineStagesStrategyStandard object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyStandard) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandard { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandard{} p.SetVerify(dcl.ValueOrEmptyBool(o.Verify)) p.SetPredeploy(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPredeployToProto(o.Predeploy)) p.SetPostdeploy(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPostdeployToProto(o.Postdeploy)) return p } // DeliveryPipelineSerialPipelineStagesStrategyStandardPredeployToProto converts a DeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPredeployToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPredeploy{} sActions := make([]string, len(o.Actions)) for i, r := range o.Actions { sActions[i] = r } p.SetActions(sActions) return p } // DeliveryPipelineSerialPipelineStagesStrategyStandardPostdeployToProto converts a DeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPostdeployToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyStandardPostdeploy{} sActions := make([]string, len(o.Actions)) for i, r := range o.Actions { sActions[i] = r } p.SetActions(sActions) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanary object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanary) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanary { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanary{} p.SetRuntimeConfig(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigToProto(o.RuntimeConfig)) p.SetCanaryDeployment(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentToProto(o.CanaryDeployment)) p.SetCustomCanaryDeployment(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentToProto(o.CustomCanaryDeployment)) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfig{} p.SetKubernetes(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesToProto(o.Kubernetes)) p.SetCloudRun(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRunToProto(o.CloudRun)) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetes{} p.SetGatewayServiceMesh(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMeshToProto(o.GatewayServiceMesh)) p.SetServiceNetworking(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworkingToProto(o.ServiceNetworking)) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMeshToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMeshToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesGatewayServiceMesh{} p.SetHttpRoute(dcl.ValueOrEmptyString(o.HttpRoute)) p.SetService(dcl.ValueOrEmptyString(o.Service)) p.SetDeployment(dcl.ValueOrEmptyString(o.Deployment)) p.SetRouteUpdateWaitTime(dcl.ValueOrEmptyString(o.RouteUpdateWaitTime)) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworkingToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworkingToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigKubernetesServiceNetworking{} p.SetService(dcl.ValueOrEmptyString(o.Service)) p.SetDeployment(dcl.ValueOrEmptyString(o.Deployment)) p.SetDisablePodOverprovisioning(dcl.ValueOrEmptyBool(o.DisablePodOverprovisioning)) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRunToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRunToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryRuntimeConfigCloudRun{} p.SetAutomaticTrafficControl(dcl.ValueOrEmptyBool(o.AutomaticTrafficControl)) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeployment{} p.SetVerify(dcl.ValueOrEmptyBool(o.Verify)) p.SetPredeploy(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeployToProto(o.Predeploy)) p.SetPostdeploy(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeployToProto(o.Postdeploy)) sPercentages := make([]int64, len(o.Percentages)) for i, r := range o.Percentages { sPercentages[i] = r } p.SetPercentages(sPercentages) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeployToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeployToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPredeploy{} sActions := make([]string, len(o.Actions)) for i, r := range o.Actions { sActions[i] = r } p.SetActions(sActions) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeployToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeployToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCanaryDeploymentPostdeploy{} sActions := make([]string, len(o.Actions)) for i, r := range o.Actions { sActions[i] = r } p.SetActions(sActions) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeployment{} sPhaseConfigs := make([]*betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs, len(o.PhaseConfigs)) for i, r := range o.PhaseConfigs { sPhaseConfigs[i] = ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsToProto(&r) } p.SetPhaseConfigs(sPhaseConfigs) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigs{} p.SetPhaseId(dcl.ValueOrEmptyString(o.PhaseId)) p.SetPercentage(dcl.ValueOrEmptyInt64(o.Percentage)) p.SetVerify(dcl.ValueOrEmptyBool(o.Verify)) p.SetPredeploy(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeployToProto(o.Predeploy)) p.SetPostdeploy(ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeployToProto(o.Postdeploy)) sProfiles := make([]string, len(o.Profiles)) for i, r := range o.Profiles { sProfiles[i] = r } p.SetProfiles(sProfiles) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeployToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeployToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPredeploy{} sActions := make([]string, len(o.Actions)) for i, r := range o.Actions { sActions[i] = r } p.SetActions(sActions) return p } // DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeployToProto converts a DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeployToProto(o *beta.DeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesStrategyCanaryCustomCanaryDeploymentPhaseConfigsPostdeploy{} sActions := make([]string, len(o.Actions)) for i, r := range o.Actions { sActions[i] = r } p.SetActions(sActions) return p } // DeliveryPipelineSerialPipelineStagesDeployParametersToProto converts a DeliveryPipelineSerialPipelineStagesDeployParameters object to its proto representation. func ClouddeployBetaDeliveryPipelineSerialPipelineStagesDeployParametersToProto(o *beta.DeliveryPipelineSerialPipelineStagesDeployParameters) *betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesDeployParameters { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineSerialPipelineStagesDeployParameters{} mValues := make(map[string]string, len(o.Values)) for k, r := range o.Values { mValues[k] = r } p.SetValues(mValues) mMatchTargetLabels := make(map[string]string, len(o.MatchTargetLabels)) for k, r := range o.MatchTargetLabels { mMatchTargetLabels[k] = r } p.SetMatchTargetLabels(mMatchTargetLabels) return p } // DeliveryPipelineConditionToProto converts a DeliveryPipelineCondition object to its proto representation. func ClouddeployBetaDeliveryPipelineConditionToProto(o *beta.DeliveryPipelineCondition) *betapb.ClouddeployBetaDeliveryPipelineCondition { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineCondition{} p.SetPipelineReadyCondition(ClouddeployBetaDeliveryPipelineConditionPipelineReadyConditionToProto(o.PipelineReadyCondition)) p.SetTargetsPresentCondition(ClouddeployBetaDeliveryPipelineConditionTargetsPresentConditionToProto(o.TargetsPresentCondition)) p.SetTargetsTypeCondition(ClouddeployBetaDeliveryPipelineConditionTargetsTypeConditionToProto(o.TargetsTypeCondition)) return p } // DeliveryPipelineConditionPipelineReadyConditionToProto converts a DeliveryPipelineConditionPipelineReadyCondition object to its proto representation. func ClouddeployBetaDeliveryPipelineConditionPipelineReadyConditionToProto(o *beta.DeliveryPipelineConditionPipelineReadyCondition) *betapb.ClouddeployBetaDeliveryPipelineConditionPipelineReadyCondition { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineConditionPipelineReadyCondition{} p.SetStatus(dcl.ValueOrEmptyBool(o.Status)) p.SetUpdateTime(dcl.ValueOrEmptyString(o.UpdateTime)) return p } // DeliveryPipelineConditionTargetsPresentConditionToProto converts a DeliveryPipelineConditionTargetsPresentCondition object to its proto representation. func ClouddeployBetaDeliveryPipelineConditionTargetsPresentConditionToProto(o *beta.DeliveryPipelineConditionTargetsPresentCondition) *betapb.ClouddeployBetaDeliveryPipelineConditionTargetsPresentCondition { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineConditionTargetsPresentCondition{} p.SetStatus(dcl.ValueOrEmptyBool(o.Status)) p.SetUpdateTime(dcl.ValueOrEmptyString(o.UpdateTime)) sMissingTargets := make([]string, len(o.MissingTargets)) for i, r := range o.MissingTargets { sMissingTargets[i] = r } p.SetMissingTargets(sMissingTargets) return p } // DeliveryPipelineConditionTargetsTypeConditionToProto converts a DeliveryPipelineConditionTargetsTypeCondition object to its proto representation. func ClouddeployBetaDeliveryPipelineConditionTargetsTypeConditionToProto(o *beta.DeliveryPipelineConditionTargetsTypeCondition) *betapb.ClouddeployBetaDeliveryPipelineConditionTargetsTypeCondition { if o == nil { return nil } p := &betapb.ClouddeployBetaDeliveryPipelineConditionTargetsTypeCondition{} p.SetStatus(dcl.ValueOrEmptyBool(o.Status)) p.SetErrorDetails(dcl.ValueOrEmptyString(o.ErrorDetails)) return p } // DeliveryPipelineToProto converts a DeliveryPipeline resource to its proto representation. func DeliveryPipelineToProto(resource *beta.DeliveryPipeline) *betapb.ClouddeployBetaDeliveryPipeline { p := &betapb.ClouddeployBetaDeliveryPipeline{} p.SetName(dcl.ValueOrEmptyString(resource.Name)) p.SetUid(dcl.ValueOrEmptyString(resource.Uid)) p.SetDescription(dcl.ValueOrEmptyString(resource.Description)) p.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime)) p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime)) p.SetSerialPipeline(ClouddeployBetaDeliveryPipelineSerialPipelineToProto(resource.SerialPipeline)) p.SetCondition(ClouddeployBetaDeliveryPipelineConditionToProto(resource.Condition)) p.SetEtag(dcl.ValueOrEmptyString(resource.Etag)) p.SetProject(dcl.ValueOrEmptyString(resource.Project)) p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) p.SetSuspended(dcl.ValueOrEmptyBool(resource.Suspended)) mAnnotations := make(map[string]string, len(resource.Annotations)) for k, r := range resource.Annotations { mAnnotations[k] = r } p.SetAnnotations(mAnnotations) mLabels := make(map[string]string, len(resource.Labels)) for k, r := range resource.Labels { mLabels[k] = r } p.SetLabels(mLabels) return p } // applyDeliveryPipeline handles the gRPC request by passing it to the underlying DeliveryPipeline Apply() method. func (s *DeliveryPipelineServer) applyDeliveryPipeline(ctx context.Context, c *beta.Client, request *betapb.ApplyClouddeployBetaDeliveryPipelineRequest) (*betapb.ClouddeployBetaDeliveryPipeline, error) { p := ProtoToDeliveryPipeline(request.GetResource()) res, err := c.ApplyDeliveryPipeline(ctx, p) if err != nil { return nil, err } r := DeliveryPipelineToProto(res) return r, nil } // applyClouddeployBetaDeliveryPipeline handles the gRPC request by passing it to the underlying DeliveryPipeline Apply() method. func (s *DeliveryPipelineServer) ApplyClouddeployBetaDeliveryPipeline(ctx context.Context, request *betapb.ApplyClouddeployBetaDeliveryPipelineRequest) (*betapb.ClouddeployBetaDeliveryPipeline, error) { cl, err := createConfigDeliveryPipeline(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return s.applyDeliveryPipeline(ctx, cl, request) } // DeleteDeliveryPipeline handles the gRPC request by passing it to the underlying DeliveryPipeline Delete() method. func (s *DeliveryPipelineServer) DeleteClouddeployBetaDeliveryPipeline(ctx context.Context, request *betapb.DeleteClouddeployBetaDeliveryPipelineRequest) (*emptypb.Empty, error) { cl, err := createConfigDeliveryPipeline(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteDeliveryPipeline(ctx, ProtoToDeliveryPipeline(request.GetResource())) } // ListClouddeployBetaDeliveryPipeline handles the gRPC request by passing it to the underlying DeliveryPipelineList() method. func (s *DeliveryPipelineServer) ListClouddeployBetaDeliveryPipeline(ctx context.Context, request *betapb.ListClouddeployBetaDeliveryPipelineRequest) (*betapb.ListClouddeployBetaDeliveryPipelineResponse, error) { cl, err := createConfigDeliveryPipeline(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } resources, err := cl.ListDeliveryPipeline(ctx, request.GetProject(), request.GetLocation()) if err != nil { return nil, err } var protos []*betapb.ClouddeployBetaDeliveryPipeline for _, r := range resources.Items { rp := DeliveryPipelineToProto(r) protos = append(protos, rp) } p := &betapb.ListClouddeployBetaDeliveryPipelineResponse{} p.SetItems(protos) return p, nil } func createConfigDeliveryPipeline(ctx context.Context, service_account_file string) (*beta.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return beta.NewClient(conf), nil }
package utils import "github.com/lucasjones/reggen" func GenerateCodeForOrder () (string,error){ return reggen.Generate("[0-9]{2}[a-z]{3}[A-Z]{3}", 8) }
package main import ( "flag" "fmt" ) var ( flagConfigFile = flag.String("config", "./config.yml", "Path to configuration file") flagDryRun = flag.Bool("dry-run", false, "Dry run mode") cfg *Config ) func InArray(k string, arr []string) bool { for _, val := range arr { if val == k { return true } } return false } func CanProcessProject(name string) bool { if InArray(name, cfg.ExcludeProjects) { return false } if len(cfg.OnlyProject) == 0 { return true } if InArray(name, cfg.OnlyProject) { return true } return false } func IsEqual(a, b interface{}) bool { if fmt.Sprintf("%v", a) == fmt.Sprintf("%v", b) { return true } return false } func main() { var err error flag.Parse() cfg, err = ConfigFromFile(*flagConfigFile) if err != nil { panic(err) } client := NewClient(cfg.GitLabUrl, cfg.GitLabToken) projects, err := client.GetGroupProjects(cfg.GroupID) if err != nil { panic(err) } fmt.Printf("Found %d projects\n", len(projects)) for _, project := range projects { name := project.Get("name").(string) id := project.Get("id").(float64) if !CanProcessProject(name) { continue } fmt.Println(name) for setting, cfgVal := range cfg.Settings { projVal := project.Get(setting) if !IsEqual(projVal, cfgVal) { fmt.Printf("\t%s = %v (%v)\n", setting, projVal, cfgVal) } } if *flagDryRun { fmt.Println() continue } err = client.UpdateProject(id, cfg.Settings) if err != nil { fmt.Println(err) if cfg.StopOnError { break } } fmt.Println("ok") } }
package users import ( "time" rand "github.com/Pallinder/go-randomdata" uuid "github.com/satori/go.uuid" log "github.com/sirupsen/logrus" bh "github.com/timshannon/bolthold" bolt "go.etcd.io/bbolt" "github.com/Zenika/marcel/api/db/internal/db" ) func EnsureOneUser() error { return db.Store.Bolt().Update(func(tx *bolt.Tx) error { res, err := db.Store.TxFindAggregate(tx, &User{}, nil) if err != nil { return err } if res[0].Count() != 0 { return nil } log.Info("No users in database, creating admin...") u := &User{ DisplayName: "Admin", Login: "admin", Role: "admin", CreatedAt: time.Now(), } password := rand.RandStringRunes(10) if err := u.SetPassword(password); err != nil { return err } if err := insert(tx, u); err != nil { return err } log.Infof("User admin created with password %s", password) return nil }) } func Insert(u *User) error { return insert(nil, u) } func insert(tx *bolt.Tx, u *User) error { u.ID = uuid.NewV4().String() if u.Role == "" { u.Role = "user" } u.CreatedAt = time.Now() if tx == nil { return db.Store.Insert(u.ID, u) } return db.Store.TxInsert(tx, u.ID, u) } func List() ([]User, error) { var users []User return users, db.Store.Find(&users, nil) } func Get(id string) (*User, error) { u := new(User) if err := db.Store.Get(id, u); err != nil { if err == bh.ErrNotFound { return nil, nil } return nil, err } return u, nil } func GetByLogin(login string) (*User, error) { var users []User err := db.Store.Find(&users, bh.Where("Login").Eq(login).Index("Login")) if err != nil { return nil, err } if len(users) == 0 { return nil, nil } return &users[0], nil } func Delete(id string) error { return db.Store.Delete(id, &User{}) } func Disconnect(id string) error { return db.Store.Bolt().Update(func(tx *bolt.Tx) error { u := new(User) if err := db.Store.TxGet(tx, id, u); err != nil { if err == bh.ErrNotFound { return nil } return err } u.LastDisconnection = time.Now() return db.Store.TxUpdate(tx, id, u) }) } func Update(user *User) error { return db.Store.Update(user.ID, user) } func UpsertAll(users []User) error { return db.Store.Bolt().Update(func(tx *bolt.Tx) error { for _, u := range users { if err := db.Store.TxUpsert(tx, u.ID, &u); err != nil { return err } } return nil }) }
package controllers import ( "github.com/astaxie/beego" "github.com/morephp/blog/models" "math/rand" "time" ) type MainController struct { beego.Controller } func (this *MainController) Get() { rand.Seed(time.Now().UnixNano()) // iconS := []string{"phone","email","screen", "earth",} // this.Data["Icon"] = iconS[rand.Intn(4)] page, _ := this.GetInt("page") this.Data["Articles"] = models.ListMoreArticle(this.Ctx, page) this.TplNames = "index.tpl" } func (this *MainController) More() { page, _ := this.GetInt("page") this.Data["Articles"] = models.ListMoreArticle(this.Ctx, page) this.TplNames = "more.tpl" }
package handlers import ( "github.com/olivetree123/coco" "github.com/olivetree123/river/pocket" ) func PopHandler(c *coco.Coco) coco.Result { node := pocket.DataList.Pop() return coco.APIResponse(node) }
package main import "fmt" func main() { var test byte fmt.Printf("test=%c,test=%d\n", test, test) //直接输出byte值,就是输出了对应的字符的码值 var a byte = 'n' fmt.Println("a=", a) //如果我们希望输出对应的字符,需要使用格式化输出%c var b byte = '0' fmt.Printf("b=%c,b=%d\n", b, b) //当我们定义一个中文字符的时候,因为byte的长度是0-255,长度不够,我们通常用int来声明,所以字符的本质其实就是一个整数 //例如我其实对应的码值就是25105 var c int = '我' fmt.Printf("c=%c,c=%d,c=%v\n", c, c, c) var d byte = '0' var e byte = '1' f := d + e fmt.Printf("f=%c,f=%d", f, f) }
package main func Modulo(a, b int) int { temp := a % b if temp < 0 { return (temp + b) } return temp }
package main type Job interface { Filenames() (tmplname, outname string) } type GenListJob struct { Names []string } func (job *GenListJob) Filenames() (string, string) { return "gen_list_job.tmpl", "gen_list.go" } type GenSearchJob struct { Names []string } func (job *GenSearchJob) Filenames() (string, string) { return "gen_search_job.tmpl", "gen_search.go" } type GenStringJob struct { Fields map[string][]string } func (job *GenStringJob) Filenames() (string, string) { return "gen_string_job.tmpl", "gen_string.go" }
package dushengchen /** Submission: https://leetcode.com/submissions/detail/371271670/ */ func lengthOfLastWord(s string) int { // wordMap := map[string]bool{} lastWordStart, lastWordEnd := 0, 0 start := 0 r := []rune(s) for i, v := range r { if v == ' ' { if start < i { lastWordStart, lastWordEnd = start, i } start = i + 1 } } if start <= len(r)-1 { lastWordStart, lastWordEnd = start, len(r) } // fmt.Println(string(r[lastWordStart:lastWordEnd])) return lastWordEnd - lastWordStart }
/* * @lc app=leetcode.cn id=13 lang=golang * * [13] 罗马数字转整数 */ package solution // @lc code=start var m13 = map[string]int{ "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, } func romanToInt(s string) (ans int) { pre := 0 for i := len(s) - 1; i >= 0; i-- { c := s[i : i+1] num := m13[c] if num >= pre { ans += num } else { ans -= num } pre = num } return } // @lc code=end
package kinetic import ( "encoding/binary" "errors" "runtime" "syscall" "testing" "time" . "github.com/smartystreets/goconvey/convey" ) func TestProducerStop(t *testing.T) { producerInterface, _ := new(KinesisProducer).Init() producerInterface.NewEndpoint(testEndpoint, "stream-name") producer := producerInterface.(*KinesisProducer) CreateAndWaitForStream(producer.client, "stream-name") producerInterface.ReInit() Convey("Given a running producer", t, func() { go producer.produce() Convey("It should stop producing if sent an interrupt signal", func() { producer.interrupts <- syscall.SIGINT runtime.Gosched() // Wait for it to stop for { if !producer.IsProducing() { break } } So(producer.IsProducing(), ShouldEqual, false) }) }) producer.Close() } func TestSyncStop(t *testing.T) { producerInterface, _ := new(KinesisProducer).Init() producerInterface.NewEndpoint(testEndpoint, "stream-name") producer := producerInterface.(*KinesisProducer) CreateAndWaitForStream(producer.client, "stream-name") producerInterface.ReInit() Convey("Given a running producer", t, func() { go producer.produce() runtime.Gosched() Convey("It should stop producing if sent an interrupt signal", func() { err := producer.CloseSync() So(err, ShouldBeNil) // Wait for it to stop So(producer.IsProducing(), ShouldEqual, false) }) }) producer.Close() } func TestProducerError(t *testing.T) { producerInterface, _ := new(KinesisProducer).Init() producerInterface.NewEndpoint(testEndpoint, "stream-name") producer := producerInterface.(*KinesisProducer) CreateAndWaitForStream(producer.client, "stream-name") producerInterface.ReInit() Convey("Given a running producer", t, func() { go producer.produce() Convey("It should handle errors successfully", func() { producer.errors <- errors.New("All your base are belong to us") // Let the error propagate <-time.After(3 * time.Second) So(producer.getErrCount(), ShouldEqual, 1) So(producer.IsProducing(), ShouldEqual, true) }) }) producer.Close() } func TestProducerMessage(t *testing.T) { listener, _ := new(Listener).InitC("your-stream", "0", "LATEST", "accesskey", "secretkey", "us-east-1", 4) producer, _ := new(KinesisProducer).InitC("your-stream", "0", "LATEST", "accesskey", "secretkey", "us-east-1", 4) listener.NewEndpoint(testEndpoint, "your-stream") producer.NewEndpoint(testEndpoint, "your-stream") CreateAndWaitForStream(producer.(*KinesisProducer).client, "your-stream") listener.ReInit() producer.ReInit() for _, c := range cases { Convey("Given a valid message", t, func() { producer.Send(new(Message).Init(c.message, "test")) Convey("It should be passed on the queue without error", func() { msg, err := listener.Retrieve() if err != nil { t.Fatalf(err.Error()) } So(string(msg.Value()), ShouldResemble, string(c.message)) }) }) } listener.Close() producer.Close() } func TestProducerSendSyncMessage(t *testing.T) { listener, _ := new(Listener).InitC("your-stream", "0", "LATEST", "accesskey", "secretkey", "us-east-1", 4) producer, _ := new(KinesisProducer).InitC("your-stream", "0", "LATEST", "accesskey", "secretkey", "us-east-1", 4) listener.NewEndpoint(testEndpoint, "your-stream") producer.NewEndpoint(testEndpoint, "your-stream") CreateAndWaitForStream(producer.(*KinesisProducer).client, "your-stream") listener.ReInit() producer.ReInit() for _, c := range cases { Convey("Given a valid message", t, func() { producer.SendSync(new(Message).Init(c.message, "test")) Convey("It should be passed on the queue without error", func() { msg, err := listener.Retrieve() if err != nil { t.Fatalf(err.Error()) } So(string(msg.Value()), ShouldResemble, string(c.message)) }) }) } listener.Close() producer.Close() } func TestProducerTryToSend(t *testing.T) { producer, _ := new(KinesisProducer).InitC("your-stream", "0", "LATEST", "accesskey", "secretkey", "us-east-1", 4) producer.NewEndpoint(testEndpoint, "your-stream") CreateAndWaitForStream(producer.(*KinesisProducer).client, "stream-name") producer.ReInit() closeError := producer.CloseSync() // This is to make the test deterministic. It stops producer from sending messages. runtime.Gosched() var totDropped int for i := 0; i < 5000; i++ { b := make([]byte, 2) binary.LittleEndian.PutUint16(b, uint16(i)) if err := producer.TryToSend(new(Message).Init(b, "foo")); nil != err { totDropped++ } } Convey("Given a producer", t, func() { Convey("TryToSend should drop messages when the queue is full", func() { So(closeError, ShouldBeNil) So(totDropped, ShouldEqual, 1000) So(len(producer.(*KinesisProducer).messages), ShouldEqual, 4000) }) }) }
/* Copyright 2021. The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package componentdefinition import ( "context" "fmt" "net/http" admissionv1 "k8s.io/api/admission/v1" "k8s.io/apimachinery/pkg/api/meta" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/runtime/inject" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" "github.com/oam-dev/kubevela/apis/core.oam.dev/common" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" "github.com/oam-dev/kubevela/pkg/oam" "github.com/oam-dev/kubevela/pkg/oam/util" webhookutils "github.com/oam-dev/kubevela/pkg/webhook/utils" ) var componentDefGVR = v1beta1.SchemeGroupVersion.WithResource("componentdefinitions") // ValidatingHandler handles validation of component definition type ValidatingHandler struct { // Decoder decodes object Decoder *admission.Decoder Client client.Client } var _ inject.Client = &ValidatingHandler{} // InjectClient injects the client into the ApplicationValidateHandler func (h *ValidatingHandler) InjectClient(c client.Client) error { if h.Client != nil { return nil } h.Client = c return nil } var _ admission.Handler = &ValidatingHandler{} // Handle validate component definition func (h *ValidatingHandler) Handle(ctx context.Context, req admission.Request) admission.Response { obj := &v1beta1.ComponentDefinition{} if req.Resource.String() != componentDefGVR.String() { return admission.Errored(http.StatusBadRequest, fmt.Errorf("expect resource to be %s", componentDefGVR)) } if req.Operation == admissionv1.Create || req.Operation == admissionv1.Update { err := h.Decoder.Decode(req, obj) if err != nil { return admission.Errored(http.StatusBadRequest, err) } err = ValidateWorkload(h.Client.RESTMapper(), obj) if err != nil { return admission.Denied(err.Error()) } revisionName := obj.GetAnnotations()[oam.AnnotationDefinitionRevisionName] if len(revisionName) != 0 { defRevName := fmt.Sprintf("%s-v%s", obj.Name, revisionName) err = webhookutils.ValidateDefinitionRevision(ctx, h.Client, obj, client.ObjectKey{Namespace: obj.Namespace, Name: defRevName}) if err != nil { return admission.Denied(err.Error()) } } } return admission.ValidationResponse(true, "") } var _ admission.DecoderInjector = &ValidatingHandler{} // InjectDecoder injects the decoder into the ValidatingHandler func (h *ValidatingHandler) InjectDecoder(d *admission.Decoder) error { h.Decoder = d return nil } // RegisterValidatingHandler will register ComponentDefinition validation to webhook func RegisterValidatingHandler(mgr manager.Manager) { server := mgr.GetWebhookServer() server.Register("/validating-core-oam-dev-v1beta1-componentdefinitions", &webhook.Admission{Handler: &ValidatingHandler{}}) } // ValidateWorkload validates whether the Workload field is valid func ValidateWorkload(mapper meta.RESTMapper, cd *v1beta1.ComponentDefinition) error { // If the Type and Definition are all empty, it will be rejected. if cd.Spec.Workload.Type == "" && cd.Spec.Workload.Definition == (common.WorkloadGVK{}) { return fmt.Errorf("neither the type nor the definition of the workload field in the ComponentDefinition %s can be empty", cd.Name) } // if Type and Definitiondon‘t point to the same workloaddefinition, it will be rejected. if cd.Spec.Workload.Type != "" && cd.Spec.Workload.Definition != (common.WorkloadGVK{}) { defRef, err := util.ConvertWorkloadGVK2Definition(mapper, cd.Spec.Workload.Definition) if err != nil { return err } if defRef.Name != cd.Spec.Workload.Type { return fmt.Errorf("the type and the definition of the workload field in ComponentDefinition %s should represent the same workload", cd.Name) } } return nil }
package structs type VoiceEnrollment struct { CreatedAt int `json:"createdAt"` ContentLanguage string `json:"contentLanguage"` VoiceEnrollmentId int `json:"voiceEnrollmentId"` Text string `json:"text"` APICallId string `json:"apiCallId"` } type GetAllVoiceEnrollmentsReturn struct { Message string `json:"message"` Count int `json:"count"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` VoiceEnrollments []VoiceEnrollment `json:"voiceEnrollments"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type FaceEnrollment struct { CreatedAt int `json:"createdAt"` FaceEnrollmentId int `json:"faceEnrollmentId"` APICallId string `json:"apiCallId"` } type GetAllFaceEnrollmentsReturn struct { Message string `json:"message"` Count int `json:"count"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` FaceEnrollments []FaceEnrollment `json:"faceEnrollments"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type VideoEnrollment struct { CreatedAt int `json:"createdAt"` ContentLanguage string `json:"contentLanguage"` VideoEnrollmentId int `json:"videoEnrollmentId"` Text string `json:"text"` APICallId string `json:"apiCallId"` } type GetAllVideoEnrollmentsReturn struct { Message string `json:"message"` Count int `json:"count"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` VideoEnrollments []VideoEnrollment `json:"videoEnrollments"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type CreateVoiceEnrollmentReturn struct { Message string `json:"message"` ContentLanguage string `json:"contentLanguage"` Id int `json:"id"` Status int `json:"status"` Text string `json:"text"` TextConfidence float64 `json:"textConfidence"` CreatedAt int `json:"createdAt"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type CreateVoiceEnrollmentByUrlReturn struct { Message string `json:"message"` ContentLanguage string `json:"contentLanguage"` Id int `json:"id"` Status int `json:"status"` Text string `json:"text"` TextConfidence float64 `json:"textConfidence"` CreatedAt int `json:"createdAt"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type CreateFaceEnrollmentReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` FaceEnrollmentId int `json:"faceEnrollmentId"` CreatedAt int `json:"createdAt"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type CreateFaceEnrollmentByUrlReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` FaceEnrollmentId int `json:"faceEnrollmentId"` CreatedAt int `json:"createdAt"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type CreateVideoEnrollmentReturn struct { Message string `json:"message"` ContentLanguage string `json:"contentLanguage"` Id int `json:"id"` Status int `json:"status"` Text string `json:"text"` TextConfidence float64 `json:"textConfidence"` CreatedAt int `json:"createdAt"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type CreateVideoEnrollmentByUrlReturn struct { Message string `json:"message"` ContentLanguage string `json:"contentLanguage"` Id int `json:"id"` Status int `json:"status"` Text string `json:"text"` TextConfidence float64 `json:"textConfidence"` CreatedAt int `json:"createdAt"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type DeleteVoiceEnrollmentReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type DeleteFaceEnrollmentReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type DeleteVideoEnrollmentReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type DeleteAllVoiceEnrollmentsReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type DeleteAllFaceEnrollmentsReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type DeleteAllVideoEnrollmentsReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` } type DeleteAllEnrollmentsReturn struct { Message string `json:"message"` Status int `json:"status"` TimeTaken string `json:"timeTaken"` ResponseCode string `json:"responseCode"` APICallId string `json:"apiCallId"` }
package requests import "time" var _ = time.Time{} type CreateEvent struct { EventCreated time.Time EventEnds *time.Time Summary string Organizer string EventUser string EventBegins time.Time EventID string Location string Source string Attendees string } type UpdateEvent struct { EventCreated time.Time EventEnds *time.Time Summary string Organizer string EventUser string EventBegins time.Time EventID string Location string Source string Attendees string } func (c *CreateEvent) Valid() error { return validate.Struct(c) } func (c *UpdateEvent) Valid() error { return validate.Struct(c) }
package main import "github.com/jinzhu/gorm" // Holding stores the number of stocks owned type Holding struct { Stock Stock Count uint } // Value of Stocks in holding func (h *Holding) Value(db *gorm.DB) float64 { return float64(h.Count) * h.Stock.Value(db) }
package database import ( "time" "errors" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "themis/utils" "themis/models" ) // IWorkItemStorage is the interface for the workitem storage. type IWorkItemStorage interface { Insert(workItem models.WorkItem) (bson.ObjectId, error) Update(workItem models.WorkItem) error Delete(id bson.ObjectId) error GetOne(id bson.ObjectId) (models.WorkItem, error) GetAll(queryExpression interface{}) ([]models.WorkItem, error) GetAllChildIDs(id bson.ObjectId) ([]bson.ObjectId, error) GetAllPaged(queryExpression interface{}, offset int, limit int) ([]models.WorkItem, error) GetAllCount(queryExpression interface{}) (int, error) NewDisplayID(spaceID string) (int, error) } // WorkItemStorage is the storage backend for WorkItems. type WorkItemStorage struct { database *mgo.Database } // NewWorkItemStorage creates a new storage backend for WorkItems. func NewWorkItemStorage(database *mgo.Database) *WorkItemStorage { return &WorkItemStorage{database: database} } // Insert creates a new record in the database and returns the new ID. func (workItemStorage *WorkItemStorage) Insert(workItem models.WorkItem) (bson.ObjectId, error) { coll := workItemStorage.database.C(workItem.GetCollectionName()) if workItem.ID != "" { utils.ErrorLog.Printf("Given WorkItem instance already has an ID %s. Can not insert into database.\n", workItem.ID.Hex()) return "", errors.New("Given WorkItem instance already has an ID. Can not insert into database") } workItem.ID = bson.NewObjectId() var err error workItem.DisplayID, err = workItemStorage.NewDisplayID(workItem.SpaceID.Hex()) if err != nil { return "", err } utils.ReplaceDotsToDollarsInAttributes(&workItem.Attributes) if err = coll.Insert(workItem); err != nil { utils.ErrorLog.Printf("Error while inserting new WorkItem with ID %s into database: %s", workItem.ID, err.Error()) return "", err } utils.DebugLog.Printf("Inserted new WorkItem with ID %s and display_id %d into database.", workItem.ID.Hex(), workItem.DisplayID) utils.ReplaceDollarsToDotsInAttributes(&workItem.Attributes) return workItem.ID, nil } // Update updates an existing record in the database. func (workItemStorage *WorkItemStorage) Update(workItem models.WorkItem) error { workItem.UpdatedAt = time.Now() coll := workItemStorage.database.C(workItem.GetCollectionName()) if workItem.ID == "" { utils.ErrorLog.Println("Given WorkItem instance has an empty ID. Can not be updated in the database.") return errors.New("Given WorkItem instance has an empty ID. Can not be updated in the database") } utils.ReplaceDotsToDollarsInAttributes(&workItem.Attributes) if err := coll.UpdateId(workItem.ID, workItem); err != nil { utils.ErrorLog.Printf("Error while updating WorkItem with ID %s in database: %s", workItem.ID, err.Error()) return err } utils.ReplaceDollarsToDotsInAttributes(&workItem.Attributes) utils.DebugLog.Printf("Updated WorkItem with ID %s in database.", workItem.ID.Hex()) return nil } // Delete removes a record from the database. func (workItemStorage *WorkItemStorage) Delete(id bson.ObjectId) error { coll := workItemStorage.database.C(models.WorkItemName) // TODO this should not use memory if id == "" { utils.ErrorLog.Println("Given WorkItem instance has an empty ID. Can not be deleted from database.") return errors.New("Given WorkItem instance has an empty ID. Can not be updated from database") } info, err := coll.RemoveAll(bson.M{"_id": id}) if err != nil { utils.ErrorLog.Printf("Error while deleting WorkItem with ID %s in database: %s", id, err.Error()) return err } utils.DebugLog.Printf("Deleted %d WorkItem with ID %s from database.", info.Removed, id) return nil } // GetOne returns an entity from the database based on a given ID. func (workItemStorage *WorkItemStorage) GetOne(id bson.ObjectId) (models.WorkItem, error) { wItem := models.NewWorkItem() coll := workItemStorage.database.C(wItem.GetCollectionName()) if id == "" { utils.ErrorLog.Println("Given WorkItem id is empty.") return *wItem, errors.New("Given WorkItem id is empty") } if err := coll.Find(bson.M{"_id": id}).One(wItem); err != nil { utils.ErrorLog.Printf("Error while retrieving WorkItem with ID %s from database: %s", wItem.ID, err.Error()) return *wItem, err } utils.ReplaceDollarsToDotsInAttributes(&wItem.Attributes) utils.DebugLog.Printf("Retrieved WorkItem with ID %s from database.", wItem.ID.Hex()) return *wItem, nil } // GetAll returns an entity from the database based on a given ID. The queryExpression is a Mongo // compliant search expression, either a Map or a Struct that can be serialized by bson. See // https://docs.mongodb.com/manual/tutorial/query-documents/ for details on what can be expressed // in a query. The keys used are the bson keys used on the model structs. Example: // `bson.M{"space": spaceID}`. func (workItemStorage *WorkItemStorage) GetAll(queryExpression interface{}) ([]models.WorkItem, error) { allWorkItems := new([]models.WorkItem) coll := workItemStorage.database.C(models.WorkItemName) if err := coll.Find(queryExpression).All(allWorkItems); err != nil { utils.ErrorLog.Printf("Error while retrieving all WorkItems from database: %s", err.Error()) return nil, err } for _, thisWorkItem := range *allWorkItems { utils.ReplaceDollarsToDotsInAttributes(&(thisWorkItem.Attributes)) } utils.DebugLog.Printf("Retrieved WorkItems from database with filter %s.", queryExpression) return *allWorkItems, nil } // GetAllChildIDs returns all child IDs for the given WorkItem ID. func (workItemStorage *WorkItemStorage) GetAllChildIDs(id bson.ObjectId) ([]bson.ObjectId, error) { childrenIDs := new([]bson.ObjectId) coll := workItemStorage.database.C(models.WorkItemName) if err := coll.Find(bson.M{"parent_workitem_id": id}).Select(bson.M{}).All(childrenIDs); err != nil { utils.ErrorLog.Printf("Error while retrieving child IDs from database: %s", err.Error()) return nil, err } utils.DebugLog.Printf("Retrieved WorkItem child IDs from database for parent WorkItem %s.", id) return *childrenIDs, nil } // GetAllPaged returns a subset of the work items based on offset and limit. func (workItemStorage *WorkItemStorage) GetAllPaged(queryExpression interface{}, offset int, limit int) ([]models.WorkItem, error) { // TODO there might be performance issues with this approach. See here: // https://stackoverflow.com/questions/40634865/efficient-paging-in-mongodb-using-mgo allWorkItems := new([]models.WorkItem) coll := workItemStorage.database.C(models.WorkItemName) query := coll.Find(queryExpression).Sort("updated_at").Limit(limit) query = query.Skip(offset) if err := query.All(allWorkItems); err != nil { utils.ErrorLog.Printf("Error while retrieving paged WorkItems from database: %s", err.Error()) return nil, err } for _, thisWorkItem := range *allWorkItems { utils.ReplaceDollarsToDotsInAttributes(&(thisWorkItem.Attributes)) } utils.DebugLog.Printf("Retrieved paged WorkItems from database with filter %s.", queryExpression) return *allWorkItems, nil } // GetAllCount returns the number of elements in the database. func (workItemStorage *WorkItemStorage) GetAllCount(queryExpression interface{}) (int, error) { coll := workItemStorage.database.C(models.WorkItemName) allCount, err := coll.Find(queryExpression).Count() if err != nil { utils.ErrorLog.Printf("Error while retrieving number of WorkItems from database: %s", err.Error()) return -1, err } utils.DebugLog.Printf("Retrieved WorkItem count from database with filter %s.", queryExpression) return allCount, nil } // NewDisplayID creates a new human-readable id. func (workItemStorage *WorkItemStorage) NewDisplayID(spaceID string) (int, error) { coll := workItemStorage.database.C(models.WorkItemName) allWorkItems := new([]models.Iteration) err := coll.Find(bson.M{"space_id": bson.ObjectIdHex(spaceID)}).Sort("-display_id").Limit(1).All(allWorkItems) if err != nil { utils.ErrorLog.Printf("Error while retrieving latest display_id of WorkItems from database: %s", err.Error()) return -1, err } if len(*allWorkItems)>0 { latestDisplayID := (*allWorkItems)[0].DisplayID return latestDisplayID + 1, nil } return 0, nil }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" alphapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/run/alpha/run_alpha_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/run/alpha" ) // ServiceServer implements the gRPC interface for Service. type ServiceServer struct{} // ProtoToServiceIngressEnum converts a ServiceIngressEnum enum from its proto representation. func ProtoToRunAlphaServiceIngressEnum(e alphapb.RunAlphaServiceIngressEnum) *alpha.ServiceIngressEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceIngressEnum_name[int32(e)]; ok { e := alpha.ServiceIngressEnum(n[len("RunAlphaServiceIngressEnum"):]) return &e } return nil } // ProtoToServiceLaunchStageEnum converts a ServiceLaunchStageEnum enum from its proto representation. func ProtoToRunAlphaServiceLaunchStageEnum(e alphapb.RunAlphaServiceLaunchStageEnum) *alpha.ServiceLaunchStageEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceLaunchStageEnum_name[int32(e)]; ok { e := alpha.ServiceLaunchStageEnum(n[len("RunAlphaServiceLaunchStageEnum"):]) return &e } return nil } // ProtoToServiceTemplateVPCAccessEgressEnum converts a ServiceTemplateVPCAccessEgressEnum enum from its proto representation. func ProtoToRunAlphaServiceTemplateVPCAccessEgressEnum(e alphapb.RunAlphaServiceTemplateVPCAccessEgressEnum) *alpha.ServiceTemplateVPCAccessEgressEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTemplateVPCAccessEgressEnum_name[int32(e)]; ok { e := alpha.ServiceTemplateVPCAccessEgressEnum(n[len("RunAlphaServiceTemplateVPCAccessEgressEnum"):]) return &e } return nil } // ProtoToServiceTemplateExecutionEnvironmentEnum converts a ServiceTemplateExecutionEnvironmentEnum enum from its proto representation. func ProtoToRunAlphaServiceTemplateExecutionEnvironmentEnum(e alphapb.RunAlphaServiceTemplateExecutionEnvironmentEnum) *alpha.ServiceTemplateExecutionEnvironmentEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTemplateExecutionEnvironmentEnum_name[int32(e)]; ok { e := alpha.ServiceTemplateExecutionEnvironmentEnum(n[len("RunAlphaServiceTemplateExecutionEnvironmentEnum"):]) return &e } return nil } // ProtoToServiceTrafficTypeEnum converts a ServiceTrafficTypeEnum enum from its proto representation. func ProtoToRunAlphaServiceTrafficTypeEnum(e alphapb.RunAlphaServiceTrafficTypeEnum) *alpha.ServiceTrafficTypeEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTrafficTypeEnum_name[int32(e)]; ok { e := alpha.ServiceTrafficTypeEnum(n[len("RunAlphaServiceTrafficTypeEnum"):]) return &e } return nil } // ProtoToServiceTerminalConditionStateEnum converts a ServiceTerminalConditionStateEnum enum from its proto representation. func ProtoToRunAlphaServiceTerminalConditionStateEnum(e alphapb.RunAlphaServiceTerminalConditionStateEnum) *alpha.ServiceTerminalConditionStateEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTerminalConditionStateEnum_name[int32(e)]; ok { e := alpha.ServiceTerminalConditionStateEnum(n[len("RunAlphaServiceTerminalConditionStateEnum"):]) return &e } return nil } // ProtoToServiceTerminalConditionSeverityEnum converts a ServiceTerminalConditionSeverityEnum enum from its proto representation. func ProtoToRunAlphaServiceTerminalConditionSeverityEnum(e alphapb.RunAlphaServiceTerminalConditionSeverityEnum) *alpha.ServiceTerminalConditionSeverityEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTerminalConditionSeverityEnum_name[int32(e)]; ok { e := alpha.ServiceTerminalConditionSeverityEnum(n[len("RunAlphaServiceTerminalConditionSeverityEnum"):]) return &e } return nil } // ProtoToServiceTerminalConditionReasonEnum converts a ServiceTerminalConditionReasonEnum enum from its proto representation. func ProtoToRunAlphaServiceTerminalConditionReasonEnum(e alphapb.RunAlphaServiceTerminalConditionReasonEnum) *alpha.ServiceTerminalConditionReasonEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTerminalConditionReasonEnum_name[int32(e)]; ok { e := alpha.ServiceTerminalConditionReasonEnum(n[len("RunAlphaServiceTerminalConditionReasonEnum"):]) return &e } return nil } // ProtoToServiceTerminalConditionRevisionReasonEnum converts a ServiceTerminalConditionRevisionReasonEnum enum from its proto representation. func ProtoToRunAlphaServiceTerminalConditionRevisionReasonEnum(e alphapb.RunAlphaServiceTerminalConditionRevisionReasonEnum) *alpha.ServiceTerminalConditionRevisionReasonEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTerminalConditionRevisionReasonEnum_name[int32(e)]; ok { e := alpha.ServiceTerminalConditionRevisionReasonEnum(n[len("RunAlphaServiceTerminalConditionRevisionReasonEnum"):]) return &e } return nil } // ProtoToServiceTerminalConditionJobReasonEnum converts a ServiceTerminalConditionJobReasonEnum enum from its proto representation. func ProtoToRunAlphaServiceTerminalConditionJobReasonEnum(e alphapb.RunAlphaServiceTerminalConditionJobReasonEnum) *alpha.ServiceTerminalConditionJobReasonEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTerminalConditionJobReasonEnum_name[int32(e)]; ok { e := alpha.ServiceTerminalConditionJobReasonEnum(n[len("RunAlphaServiceTerminalConditionJobReasonEnum"):]) return &e } return nil } // ProtoToServiceTrafficStatusesTypeEnum converts a ServiceTrafficStatusesTypeEnum enum from its proto representation. func ProtoToRunAlphaServiceTrafficStatusesTypeEnum(e alphapb.RunAlphaServiceTrafficStatusesTypeEnum) *alpha.ServiceTrafficStatusesTypeEnum { if e == 0 { return nil } if n, ok := alphapb.RunAlphaServiceTrafficStatusesTypeEnum_name[int32(e)]; ok { e := alpha.ServiceTrafficStatusesTypeEnum(n[len("RunAlphaServiceTrafficStatusesTypeEnum"):]) return &e } return nil } // ProtoToServiceBinaryAuthorization converts a ServiceBinaryAuthorization object from its proto representation. func ProtoToRunAlphaServiceBinaryAuthorization(p *alphapb.RunAlphaServiceBinaryAuthorization) *alpha.ServiceBinaryAuthorization { if p == nil { return nil } obj := &alpha.ServiceBinaryAuthorization{ UseDefault: dcl.Bool(p.GetUseDefault()), BreakglassJustification: dcl.StringOrNil(p.GetBreakglassJustification()), } return obj } // ProtoToServiceTemplate converts a ServiceTemplate object from its proto representation. func ProtoToRunAlphaServiceTemplate(p *alphapb.RunAlphaServiceTemplate) *alpha.ServiceTemplate { if p == nil { return nil } obj := &alpha.ServiceTemplate{ Revision: dcl.StringOrNil(p.GetRevision()), Scaling: ProtoToRunAlphaServiceTemplateScaling(p.GetScaling()), VPCAccess: ProtoToRunAlphaServiceTemplateVPCAccess(p.GetVpcAccess()), ContainerConcurrency: dcl.Int64OrNil(p.GetContainerConcurrency()), Timeout: dcl.StringOrNil(p.GetTimeout()), ServiceAccount: dcl.StringOrNil(p.GetServiceAccount()), ExecutionEnvironment: ProtoToRunAlphaServiceTemplateExecutionEnvironmentEnum(p.GetExecutionEnvironment()), } for _, r := range p.GetContainers() { obj.Containers = append(obj.Containers, *ProtoToRunAlphaServiceTemplateContainers(r)) } for _, r := range p.GetVolumes() { obj.Volumes = append(obj.Volumes, *ProtoToRunAlphaServiceTemplateVolumes(r)) } return obj } // ProtoToServiceTemplateScaling converts a ServiceTemplateScaling object from its proto representation. func ProtoToRunAlphaServiceTemplateScaling(p *alphapb.RunAlphaServiceTemplateScaling) *alpha.ServiceTemplateScaling { if p == nil { return nil } obj := &alpha.ServiceTemplateScaling{ MinInstanceCount: dcl.Int64OrNil(p.GetMinInstanceCount()), MaxInstanceCount: dcl.Int64OrNil(p.GetMaxInstanceCount()), } return obj } // ProtoToServiceTemplateVPCAccess converts a ServiceTemplateVPCAccess object from its proto representation. func ProtoToRunAlphaServiceTemplateVPCAccess(p *alphapb.RunAlphaServiceTemplateVPCAccess) *alpha.ServiceTemplateVPCAccess { if p == nil { return nil } obj := &alpha.ServiceTemplateVPCAccess{ Connector: dcl.StringOrNil(p.GetConnector()), Egress: ProtoToRunAlphaServiceTemplateVPCAccessEgressEnum(p.GetEgress()), } return obj } // ProtoToServiceTemplateContainers converts a ServiceTemplateContainers object from its proto representation. func ProtoToRunAlphaServiceTemplateContainers(p *alphapb.RunAlphaServiceTemplateContainers) *alpha.ServiceTemplateContainers { if p == nil { return nil } obj := &alpha.ServiceTemplateContainers{ Name: dcl.StringOrNil(p.GetName()), Image: dcl.StringOrNil(p.GetImage()), Resources: ProtoToRunAlphaServiceTemplateContainersResources(p.GetResources()), } for _, r := range p.GetCommand() { obj.Command = append(obj.Command, r) } for _, r := range p.GetArgs() { obj.Args = append(obj.Args, r) } for _, r := range p.GetEnv() { obj.Env = append(obj.Env, *ProtoToRunAlphaServiceTemplateContainersEnv(r)) } for _, r := range p.GetPorts() { obj.Ports = append(obj.Ports, *ProtoToRunAlphaServiceTemplateContainersPorts(r)) } for _, r := range p.GetVolumeMounts() { obj.VolumeMounts = append(obj.VolumeMounts, *ProtoToRunAlphaServiceTemplateContainersVolumeMounts(r)) } return obj } // ProtoToServiceTemplateContainersEnv converts a ServiceTemplateContainersEnv object from its proto representation. func ProtoToRunAlphaServiceTemplateContainersEnv(p *alphapb.RunAlphaServiceTemplateContainersEnv) *alpha.ServiceTemplateContainersEnv { if p == nil { return nil } obj := &alpha.ServiceTemplateContainersEnv{ Name: dcl.StringOrNil(p.GetName()), Value: dcl.StringOrNil(p.GetValue()), ValueSource: ProtoToRunAlphaServiceTemplateContainersEnvValueSource(p.GetValueSource()), } return obj } // ProtoToServiceTemplateContainersEnvValueSource converts a ServiceTemplateContainersEnvValueSource object from its proto representation. func ProtoToRunAlphaServiceTemplateContainersEnvValueSource(p *alphapb.RunAlphaServiceTemplateContainersEnvValueSource) *alpha.ServiceTemplateContainersEnvValueSource { if p == nil { return nil } obj := &alpha.ServiceTemplateContainersEnvValueSource{ SecretKeyRef: ProtoToRunAlphaServiceTemplateContainersEnvValueSourceSecretKeyRef(p.GetSecretKeyRef()), } return obj } // ProtoToServiceTemplateContainersEnvValueSourceSecretKeyRef converts a ServiceTemplateContainersEnvValueSourceSecretKeyRef object from its proto representation. func ProtoToRunAlphaServiceTemplateContainersEnvValueSourceSecretKeyRef(p *alphapb.RunAlphaServiceTemplateContainersEnvValueSourceSecretKeyRef) *alpha.ServiceTemplateContainersEnvValueSourceSecretKeyRef { if p == nil { return nil } obj := &alpha.ServiceTemplateContainersEnvValueSourceSecretKeyRef{ Secret: dcl.StringOrNil(p.GetSecret()), Version: dcl.StringOrNil(p.GetVersion()), } return obj } // ProtoToServiceTemplateContainersResources converts a ServiceTemplateContainersResources object from its proto representation. func ProtoToRunAlphaServiceTemplateContainersResources(p *alphapb.RunAlphaServiceTemplateContainersResources) *alpha.ServiceTemplateContainersResources { if p == nil { return nil } obj := &alpha.ServiceTemplateContainersResources{ CpuIdle: dcl.Bool(p.GetCpuIdle()), } return obj } // ProtoToServiceTemplateContainersPorts converts a ServiceTemplateContainersPorts object from its proto representation. func ProtoToRunAlphaServiceTemplateContainersPorts(p *alphapb.RunAlphaServiceTemplateContainersPorts) *alpha.ServiceTemplateContainersPorts { if p == nil { return nil } obj := &alpha.ServiceTemplateContainersPorts{ Name: dcl.StringOrNil(p.GetName()), ContainerPort: dcl.Int64OrNil(p.GetContainerPort()), } return obj } // ProtoToServiceTemplateContainersVolumeMounts converts a ServiceTemplateContainersVolumeMounts object from its proto representation. func ProtoToRunAlphaServiceTemplateContainersVolumeMounts(p *alphapb.RunAlphaServiceTemplateContainersVolumeMounts) *alpha.ServiceTemplateContainersVolumeMounts { if p == nil { return nil } obj := &alpha.ServiceTemplateContainersVolumeMounts{ Name: dcl.StringOrNil(p.GetName()), MountPath: dcl.StringOrNil(p.GetMountPath()), } return obj } // ProtoToServiceTemplateVolumes converts a ServiceTemplateVolumes object from its proto representation. func ProtoToRunAlphaServiceTemplateVolumes(p *alphapb.RunAlphaServiceTemplateVolumes) *alpha.ServiceTemplateVolumes { if p == nil { return nil } obj := &alpha.ServiceTemplateVolumes{ Name: dcl.StringOrNil(p.GetName()), Secret: ProtoToRunAlphaServiceTemplateVolumesSecret(p.GetSecret()), CloudSqlInstance: ProtoToRunAlphaServiceTemplateVolumesCloudSqlInstance(p.GetCloudSqlInstance()), } return obj } // ProtoToServiceTemplateVolumesSecret converts a ServiceTemplateVolumesSecret object from its proto representation. func ProtoToRunAlphaServiceTemplateVolumesSecret(p *alphapb.RunAlphaServiceTemplateVolumesSecret) *alpha.ServiceTemplateVolumesSecret { if p == nil { return nil } obj := &alpha.ServiceTemplateVolumesSecret{ Secret: dcl.StringOrNil(p.GetSecret()), DefaultMode: dcl.Int64OrNil(p.GetDefaultMode()), } for _, r := range p.GetItems() { obj.Items = append(obj.Items, *ProtoToRunAlphaServiceTemplateVolumesSecretItems(r)) } return obj } // ProtoToServiceTemplateVolumesSecretItems converts a ServiceTemplateVolumesSecretItems object from its proto representation. func ProtoToRunAlphaServiceTemplateVolumesSecretItems(p *alphapb.RunAlphaServiceTemplateVolumesSecretItems) *alpha.ServiceTemplateVolumesSecretItems { if p == nil { return nil } obj := &alpha.ServiceTemplateVolumesSecretItems{ Path: dcl.StringOrNil(p.GetPath()), Version: dcl.StringOrNil(p.GetVersion()), Mode: dcl.Int64OrNil(p.GetMode()), } return obj } // ProtoToServiceTemplateVolumesCloudSqlInstance converts a ServiceTemplateVolumesCloudSqlInstance object from its proto representation. func ProtoToRunAlphaServiceTemplateVolumesCloudSqlInstance(p *alphapb.RunAlphaServiceTemplateVolumesCloudSqlInstance) *alpha.ServiceTemplateVolumesCloudSqlInstance { if p == nil { return nil } obj := &alpha.ServiceTemplateVolumesCloudSqlInstance{} for _, r := range p.GetInstances() { obj.Instances = append(obj.Instances, r) } return obj } // ProtoToServiceTraffic converts a ServiceTraffic object from its proto representation. func ProtoToRunAlphaServiceTraffic(p *alphapb.RunAlphaServiceTraffic) *alpha.ServiceTraffic { if p == nil { return nil } obj := &alpha.ServiceTraffic{ Type: ProtoToRunAlphaServiceTrafficTypeEnum(p.GetType()), Revision: dcl.StringOrNil(p.GetRevision()), Percent: dcl.Int64OrNil(p.GetPercent()), Tag: dcl.StringOrNil(p.GetTag()), } return obj } // ProtoToServiceTerminalCondition converts a ServiceTerminalCondition object from its proto representation. func ProtoToRunAlphaServiceTerminalCondition(p *alphapb.RunAlphaServiceTerminalCondition) *alpha.ServiceTerminalCondition { if p == nil { return nil } obj := &alpha.ServiceTerminalCondition{ Type: dcl.StringOrNil(p.GetType()), State: ProtoToRunAlphaServiceTerminalConditionStateEnum(p.GetState()), Message: dcl.StringOrNil(p.GetMessage()), LastTransitionTime: dcl.StringOrNil(p.GetLastTransitionTime()), Severity: ProtoToRunAlphaServiceTerminalConditionSeverityEnum(p.GetSeverity()), Reason: ProtoToRunAlphaServiceTerminalConditionReasonEnum(p.GetReason()), RevisionReason: ProtoToRunAlphaServiceTerminalConditionRevisionReasonEnum(p.GetRevisionReason()), JobReason: ProtoToRunAlphaServiceTerminalConditionJobReasonEnum(p.GetJobReason()), } return obj } // ProtoToServiceTrafficStatuses converts a ServiceTrafficStatuses object from its proto representation. func ProtoToRunAlphaServiceTrafficStatuses(p *alphapb.RunAlphaServiceTrafficStatuses) *alpha.ServiceTrafficStatuses { if p == nil { return nil } obj := &alpha.ServiceTrafficStatuses{ Type: ProtoToRunAlphaServiceTrafficStatusesTypeEnum(p.GetType()), Revision: dcl.StringOrNil(p.GetRevision()), Percent: dcl.Int64OrNil(p.GetPercent()), Tag: dcl.StringOrNil(p.GetTag()), Uri: dcl.StringOrNil(p.GetUri()), } return obj } // ProtoToService converts a Service resource from its proto representation. func ProtoToService(p *alphapb.RunAlphaService) *alpha.Service { obj := &alpha.Service{ Name: dcl.StringOrNil(p.GetName()), Description: dcl.StringOrNil(p.GetDescription()), Uid: dcl.StringOrNil(p.GetUid()), Generation: dcl.Int64OrNil(p.GetGeneration()), CreateTime: dcl.StringOrNil(p.GetCreateTime()), UpdateTime: dcl.StringOrNil(p.GetUpdateTime()), DeleteTime: dcl.StringOrNil(p.GetDeleteTime()), ExpireTime: dcl.StringOrNil(p.GetExpireTime()), Creator: dcl.StringOrNil(p.GetCreator()), LastModifier: dcl.StringOrNil(p.GetLastModifier()), Client: dcl.StringOrNil(p.GetClient()), ClientVersion: dcl.StringOrNil(p.GetClientVersion()), Ingress: ProtoToRunAlphaServiceIngressEnum(p.GetIngress()), LaunchStage: ProtoToRunAlphaServiceLaunchStageEnum(p.GetLaunchStage()), BinaryAuthorization: ProtoToRunAlphaServiceBinaryAuthorization(p.GetBinaryAuthorization()), Template: ProtoToRunAlphaServiceTemplate(p.GetTemplate()), TerminalCondition: ProtoToRunAlphaServiceTerminalCondition(p.GetTerminalCondition()), LatestReadyRevision: dcl.StringOrNil(p.GetLatestReadyRevision()), LatestCreatedRevision: dcl.StringOrNil(p.GetLatestCreatedRevision()), Uri: dcl.StringOrNil(p.GetUri()), Reconciling: dcl.Bool(p.GetReconciling()), Etag: dcl.StringOrNil(p.GetEtag()), Project: dcl.StringOrNil(p.GetProject()), Location: dcl.StringOrNil(p.GetLocation()), } for _, r := range p.GetTraffic() { obj.Traffic = append(obj.Traffic, *ProtoToRunAlphaServiceTraffic(r)) } for _, r := range p.GetTrafficStatuses() { obj.TrafficStatuses = append(obj.TrafficStatuses, *ProtoToRunAlphaServiceTrafficStatuses(r)) } return obj } // ServiceIngressEnumToProto converts a ServiceIngressEnum enum to its proto representation. func RunAlphaServiceIngressEnumToProto(e *alpha.ServiceIngressEnum) alphapb.RunAlphaServiceIngressEnum { if e == nil { return alphapb.RunAlphaServiceIngressEnum(0) } if v, ok := alphapb.RunAlphaServiceIngressEnum_value["ServiceIngressEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceIngressEnum(v) } return alphapb.RunAlphaServiceIngressEnum(0) } // ServiceLaunchStageEnumToProto converts a ServiceLaunchStageEnum enum to its proto representation. func RunAlphaServiceLaunchStageEnumToProto(e *alpha.ServiceLaunchStageEnum) alphapb.RunAlphaServiceLaunchStageEnum { if e == nil { return alphapb.RunAlphaServiceLaunchStageEnum(0) } if v, ok := alphapb.RunAlphaServiceLaunchStageEnum_value["ServiceLaunchStageEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceLaunchStageEnum(v) } return alphapb.RunAlphaServiceLaunchStageEnum(0) } // ServiceTemplateVPCAccessEgressEnumToProto converts a ServiceTemplateVPCAccessEgressEnum enum to its proto representation. func RunAlphaServiceTemplateVPCAccessEgressEnumToProto(e *alpha.ServiceTemplateVPCAccessEgressEnum) alphapb.RunAlphaServiceTemplateVPCAccessEgressEnum { if e == nil { return alphapb.RunAlphaServiceTemplateVPCAccessEgressEnum(0) } if v, ok := alphapb.RunAlphaServiceTemplateVPCAccessEgressEnum_value["ServiceTemplateVPCAccessEgressEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTemplateVPCAccessEgressEnum(v) } return alphapb.RunAlphaServiceTemplateVPCAccessEgressEnum(0) } // ServiceTemplateExecutionEnvironmentEnumToProto converts a ServiceTemplateExecutionEnvironmentEnum enum to its proto representation. func RunAlphaServiceTemplateExecutionEnvironmentEnumToProto(e *alpha.ServiceTemplateExecutionEnvironmentEnum) alphapb.RunAlphaServiceTemplateExecutionEnvironmentEnum { if e == nil { return alphapb.RunAlphaServiceTemplateExecutionEnvironmentEnum(0) } if v, ok := alphapb.RunAlphaServiceTemplateExecutionEnvironmentEnum_value["ServiceTemplateExecutionEnvironmentEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTemplateExecutionEnvironmentEnum(v) } return alphapb.RunAlphaServiceTemplateExecutionEnvironmentEnum(0) } // ServiceTrafficTypeEnumToProto converts a ServiceTrafficTypeEnum enum to its proto representation. func RunAlphaServiceTrafficTypeEnumToProto(e *alpha.ServiceTrafficTypeEnum) alphapb.RunAlphaServiceTrafficTypeEnum { if e == nil { return alphapb.RunAlphaServiceTrafficTypeEnum(0) } if v, ok := alphapb.RunAlphaServiceTrafficTypeEnum_value["ServiceTrafficTypeEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTrafficTypeEnum(v) } return alphapb.RunAlphaServiceTrafficTypeEnum(0) } // ServiceTerminalConditionStateEnumToProto converts a ServiceTerminalConditionStateEnum enum to its proto representation. func RunAlphaServiceTerminalConditionStateEnumToProto(e *alpha.ServiceTerminalConditionStateEnum) alphapb.RunAlphaServiceTerminalConditionStateEnum { if e == nil { return alphapb.RunAlphaServiceTerminalConditionStateEnum(0) } if v, ok := alphapb.RunAlphaServiceTerminalConditionStateEnum_value["ServiceTerminalConditionStateEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTerminalConditionStateEnum(v) } return alphapb.RunAlphaServiceTerminalConditionStateEnum(0) } // ServiceTerminalConditionSeverityEnumToProto converts a ServiceTerminalConditionSeverityEnum enum to its proto representation. func RunAlphaServiceTerminalConditionSeverityEnumToProto(e *alpha.ServiceTerminalConditionSeverityEnum) alphapb.RunAlphaServiceTerminalConditionSeverityEnum { if e == nil { return alphapb.RunAlphaServiceTerminalConditionSeverityEnum(0) } if v, ok := alphapb.RunAlphaServiceTerminalConditionSeverityEnum_value["ServiceTerminalConditionSeverityEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTerminalConditionSeverityEnum(v) } return alphapb.RunAlphaServiceTerminalConditionSeverityEnum(0) } // ServiceTerminalConditionReasonEnumToProto converts a ServiceTerminalConditionReasonEnum enum to its proto representation. func RunAlphaServiceTerminalConditionReasonEnumToProto(e *alpha.ServiceTerminalConditionReasonEnum) alphapb.RunAlphaServiceTerminalConditionReasonEnum { if e == nil { return alphapb.RunAlphaServiceTerminalConditionReasonEnum(0) } if v, ok := alphapb.RunAlphaServiceTerminalConditionReasonEnum_value["ServiceTerminalConditionReasonEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTerminalConditionReasonEnum(v) } return alphapb.RunAlphaServiceTerminalConditionReasonEnum(0) } // ServiceTerminalConditionRevisionReasonEnumToProto converts a ServiceTerminalConditionRevisionReasonEnum enum to its proto representation. func RunAlphaServiceTerminalConditionRevisionReasonEnumToProto(e *alpha.ServiceTerminalConditionRevisionReasonEnum) alphapb.RunAlphaServiceTerminalConditionRevisionReasonEnum { if e == nil { return alphapb.RunAlphaServiceTerminalConditionRevisionReasonEnum(0) } if v, ok := alphapb.RunAlphaServiceTerminalConditionRevisionReasonEnum_value["ServiceTerminalConditionRevisionReasonEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTerminalConditionRevisionReasonEnum(v) } return alphapb.RunAlphaServiceTerminalConditionRevisionReasonEnum(0) } // ServiceTerminalConditionJobReasonEnumToProto converts a ServiceTerminalConditionJobReasonEnum enum to its proto representation. func RunAlphaServiceTerminalConditionJobReasonEnumToProto(e *alpha.ServiceTerminalConditionJobReasonEnum) alphapb.RunAlphaServiceTerminalConditionJobReasonEnum { if e == nil { return alphapb.RunAlphaServiceTerminalConditionJobReasonEnum(0) } if v, ok := alphapb.RunAlphaServiceTerminalConditionJobReasonEnum_value["ServiceTerminalConditionJobReasonEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTerminalConditionJobReasonEnum(v) } return alphapb.RunAlphaServiceTerminalConditionJobReasonEnum(0) } // ServiceTrafficStatusesTypeEnumToProto converts a ServiceTrafficStatusesTypeEnum enum to its proto representation. func RunAlphaServiceTrafficStatusesTypeEnumToProto(e *alpha.ServiceTrafficStatusesTypeEnum) alphapb.RunAlphaServiceTrafficStatusesTypeEnum { if e == nil { return alphapb.RunAlphaServiceTrafficStatusesTypeEnum(0) } if v, ok := alphapb.RunAlphaServiceTrafficStatusesTypeEnum_value["ServiceTrafficStatusesTypeEnum"+string(*e)]; ok { return alphapb.RunAlphaServiceTrafficStatusesTypeEnum(v) } return alphapb.RunAlphaServiceTrafficStatusesTypeEnum(0) } // ServiceBinaryAuthorizationToProto converts a ServiceBinaryAuthorization object to its proto representation. func RunAlphaServiceBinaryAuthorizationToProto(o *alpha.ServiceBinaryAuthorization) *alphapb.RunAlphaServiceBinaryAuthorization { if o == nil { return nil } p := &alphapb.RunAlphaServiceBinaryAuthorization{} p.SetUseDefault(dcl.ValueOrEmptyBool(o.UseDefault)) p.SetBreakglassJustification(dcl.ValueOrEmptyString(o.BreakglassJustification)) return p } // ServiceTemplateToProto converts a ServiceTemplate object to its proto representation. func RunAlphaServiceTemplateToProto(o *alpha.ServiceTemplate) *alphapb.RunAlphaServiceTemplate { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplate{} p.SetRevision(dcl.ValueOrEmptyString(o.Revision)) p.SetScaling(RunAlphaServiceTemplateScalingToProto(o.Scaling)) p.SetVpcAccess(RunAlphaServiceTemplateVPCAccessToProto(o.VPCAccess)) p.SetContainerConcurrency(dcl.ValueOrEmptyInt64(o.ContainerConcurrency)) p.SetTimeout(dcl.ValueOrEmptyString(o.Timeout)) p.SetServiceAccount(dcl.ValueOrEmptyString(o.ServiceAccount)) p.SetExecutionEnvironment(RunAlphaServiceTemplateExecutionEnvironmentEnumToProto(o.ExecutionEnvironment)) mLabels := make(map[string]string, len(o.Labels)) for k, r := range o.Labels { mLabels[k] = r } p.SetLabels(mLabels) mAnnotations := make(map[string]string, len(o.Annotations)) for k, r := range o.Annotations { mAnnotations[k] = r } p.SetAnnotations(mAnnotations) sContainers := make([]*alphapb.RunAlphaServiceTemplateContainers, len(o.Containers)) for i, r := range o.Containers { sContainers[i] = RunAlphaServiceTemplateContainersToProto(&r) } p.SetContainers(sContainers) sVolumes := make([]*alphapb.RunAlphaServiceTemplateVolumes, len(o.Volumes)) for i, r := range o.Volumes { sVolumes[i] = RunAlphaServiceTemplateVolumesToProto(&r) } p.SetVolumes(sVolumes) return p } // ServiceTemplateScalingToProto converts a ServiceTemplateScaling object to its proto representation. func RunAlphaServiceTemplateScalingToProto(o *alpha.ServiceTemplateScaling) *alphapb.RunAlphaServiceTemplateScaling { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateScaling{} p.SetMinInstanceCount(dcl.ValueOrEmptyInt64(o.MinInstanceCount)) p.SetMaxInstanceCount(dcl.ValueOrEmptyInt64(o.MaxInstanceCount)) return p } // ServiceTemplateVPCAccessToProto converts a ServiceTemplateVPCAccess object to its proto representation. func RunAlphaServiceTemplateVPCAccessToProto(o *alpha.ServiceTemplateVPCAccess) *alphapb.RunAlphaServiceTemplateVPCAccess { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateVPCAccess{} p.SetConnector(dcl.ValueOrEmptyString(o.Connector)) p.SetEgress(RunAlphaServiceTemplateVPCAccessEgressEnumToProto(o.Egress)) return p } // ServiceTemplateContainersToProto converts a ServiceTemplateContainers object to its proto representation. func RunAlphaServiceTemplateContainersToProto(o *alpha.ServiceTemplateContainers) *alphapb.RunAlphaServiceTemplateContainers { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateContainers{} p.SetName(dcl.ValueOrEmptyString(o.Name)) p.SetImage(dcl.ValueOrEmptyString(o.Image)) p.SetResources(RunAlphaServiceTemplateContainersResourcesToProto(o.Resources)) sCommand := make([]string, len(o.Command)) for i, r := range o.Command { sCommand[i] = r } p.SetCommand(sCommand) sArgs := make([]string, len(o.Args)) for i, r := range o.Args { sArgs[i] = r } p.SetArgs(sArgs) sEnv := make([]*alphapb.RunAlphaServiceTemplateContainersEnv, len(o.Env)) for i, r := range o.Env { sEnv[i] = RunAlphaServiceTemplateContainersEnvToProto(&r) } p.SetEnv(sEnv) sPorts := make([]*alphapb.RunAlphaServiceTemplateContainersPorts, len(o.Ports)) for i, r := range o.Ports { sPorts[i] = RunAlphaServiceTemplateContainersPortsToProto(&r) } p.SetPorts(sPorts) sVolumeMounts := make([]*alphapb.RunAlphaServiceTemplateContainersVolumeMounts, len(o.VolumeMounts)) for i, r := range o.VolumeMounts { sVolumeMounts[i] = RunAlphaServiceTemplateContainersVolumeMountsToProto(&r) } p.SetVolumeMounts(sVolumeMounts) return p } // ServiceTemplateContainersEnvToProto converts a ServiceTemplateContainersEnv object to its proto representation. func RunAlphaServiceTemplateContainersEnvToProto(o *alpha.ServiceTemplateContainersEnv) *alphapb.RunAlphaServiceTemplateContainersEnv { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateContainersEnv{} p.SetName(dcl.ValueOrEmptyString(o.Name)) p.SetValue(dcl.ValueOrEmptyString(o.Value)) p.SetValueSource(RunAlphaServiceTemplateContainersEnvValueSourceToProto(o.ValueSource)) return p } // ServiceTemplateContainersEnvValueSourceToProto converts a ServiceTemplateContainersEnvValueSource object to its proto representation. func RunAlphaServiceTemplateContainersEnvValueSourceToProto(o *alpha.ServiceTemplateContainersEnvValueSource) *alphapb.RunAlphaServiceTemplateContainersEnvValueSource { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateContainersEnvValueSource{} p.SetSecretKeyRef(RunAlphaServiceTemplateContainersEnvValueSourceSecretKeyRefToProto(o.SecretKeyRef)) return p } // ServiceTemplateContainersEnvValueSourceSecretKeyRefToProto converts a ServiceTemplateContainersEnvValueSourceSecretKeyRef object to its proto representation. func RunAlphaServiceTemplateContainersEnvValueSourceSecretKeyRefToProto(o *alpha.ServiceTemplateContainersEnvValueSourceSecretKeyRef) *alphapb.RunAlphaServiceTemplateContainersEnvValueSourceSecretKeyRef { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateContainersEnvValueSourceSecretKeyRef{} p.SetSecret(dcl.ValueOrEmptyString(o.Secret)) p.SetVersion(dcl.ValueOrEmptyString(o.Version)) return p } // ServiceTemplateContainersResourcesToProto converts a ServiceTemplateContainersResources object to its proto representation. func RunAlphaServiceTemplateContainersResourcesToProto(o *alpha.ServiceTemplateContainersResources) *alphapb.RunAlphaServiceTemplateContainersResources { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateContainersResources{} p.SetCpuIdle(dcl.ValueOrEmptyBool(o.CpuIdle)) mLimits := make(map[string]string, len(o.Limits)) for k, r := range o.Limits { mLimits[k] = r } p.SetLimits(mLimits) return p } // ServiceTemplateContainersPortsToProto converts a ServiceTemplateContainersPorts object to its proto representation. func RunAlphaServiceTemplateContainersPortsToProto(o *alpha.ServiceTemplateContainersPorts) *alphapb.RunAlphaServiceTemplateContainersPorts { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateContainersPorts{} p.SetName(dcl.ValueOrEmptyString(o.Name)) p.SetContainerPort(dcl.ValueOrEmptyInt64(o.ContainerPort)) return p } // ServiceTemplateContainersVolumeMountsToProto converts a ServiceTemplateContainersVolumeMounts object to its proto representation. func RunAlphaServiceTemplateContainersVolumeMountsToProto(o *alpha.ServiceTemplateContainersVolumeMounts) *alphapb.RunAlphaServiceTemplateContainersVolumeMounts { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateContainersVolumeMounts{} p.SetName(dcl.ValueOrEmptyString(o.Name)) p.SetMountPath(dcl.ValueOrEmptyString(o.MountPath)) return p } // ServiceTemplateVolumesToProto converts a ServiceTemplateVolumes object to its proto representation. func RunAlphaServiceTemplateVolumesToProto(o *alpha.ServiceTemplateVolumes) *alphapb.RunAlphaServiceTemplateVolumes { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateVolumes{} p.SetName(dcl.ValueOrEmptyString(o.Name)) p.SetSecret(RunAlphaServiceTemplateVolumesSecretToProto(o.Secret)) p.SetCloudSqlInstance(RunAlphaServiceTemplateVolumesCloudSqlInstanceToProto(o.CloudSqlInstance)) return p } // ServiceTemplateVolumesSecretToProto converts a ServiceTemplateVolumesSecret object to its proto representation. func RunAlphaServiceTemplateVolumesSecretToProto(o *alpha.ServiceTemplateVolumesSecret) *alphapb.RunAlphaServiceTemplateVolumesSecret { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateVolumesSecret{} p.SetSecret(dcl.ValueOrEmptyString(o.Secret)) p.SetDefaultMode(dcl.ValueOrEmptyInt64(o.DefaultMode)) sItems := make([]*alphapb.RunAlphaServiceTemplateVolumesSecretItems, len(o.Items)) for i, r := range o.Items { sItems[i] = RunAlphaServiceTemplateVolumesSecretItemsToProto(&r) } p.SetItems(sItems) return p } // ServiceTemplateVolumesSecretItemsToProto converts a ServiceTemplateVolumesSecretItems object to its proto representation. func RunAlphaServiceTemplateVolumesSecretItemsToProto(o *alpha.ServiceTemplateVolumesSecretItems) *alphapb.RunAlphaServiceTemplateVolumesSecretItems { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateVolumesSecretItems{} p.SetPath(dcl.ValueOrEmptyString(o.Path)) p.SetVersion(dcl.ValueOrEmptyString(o.Version)) p.SetMode(dcl.ValueOrEmptyInt64(o.Mode)) return p } // ServiceTemplateVolumesCloudSqlInstanceToProto converts a ServiceTemplateVolumesCloudSqlInstance object to its proto representation. func RunAlphaServiceTemplateVolumesCloudSqlInstanceToProto(o *alpha.ServiceTemplateVolumesCloudSqlInstance) *alphapb.RunAlphaServiceTemplateVolumesCloudSqlInstance { if o == nil { return nil } p := &alphapb.RunAlphaServiceTemplateVolumesCloudSqlInstance{} sInstances := make([]string, len(o.Instances)) for i, r := range o.Instances { sInstances[i] = r } p.SetInstances(sInstances) return p } // ServiceTrafficToProto converts a ServiceTraffic object to its proto representation. func RunAlphaServiceTrafficToProto(o *alpha.ServiceTraffic) *alphapb.RunAlphaServiceTraffic { if o == nil { return nil } p := &alphapb.RunAlphaServiceTraffic{} p.SetType(RunAlphaServiceTrafficTypeEnumToProto(o.Type)) p.SetRevision(dcl.ValueOrEmptyString(o.Revision)) p.SetPercent(dcl.ValueOrEmptyInt64(o.Percent)) p.SetTag(dcl.ValueOrEmptyString(o.Tag)) return p } // ServiceTerminalConditionToProto converts a ServiceTerminalCondition object to its proto representation. func RunAlphaServiceTerminalConditionToProto(o *alpha.ServiceTerminalCondition) *alphapb.RunAlphaServiceTerminalCondition { if o == nil { return nil } p := &alphapb.RunAlphaServiceTerminalCondition{} p.SetType(dcl.ValueOrEmptyString(o.Type)) p.SetState(RunAlphaServiceTerminalConditionStateEnumToProto(o.State)) p.SetMessage(dcl.ValueOrEmptyString(o.Message)) p.SetLastTransitionTime(dcl.ValueOrEmptyString(o.LastTransitionTime)) p.SetSeverity(RunAlphaServiceTerminalConditionSeverityEnumToProto(o.Severity)) p.SetReason(RunAlphaServiceTerminalConditionReasonEnumToProto(o.Reason)) p.SetRevisionReason(RunAlphaServiceTerminalConditionRevisionReasonEnumToProto(o.RevisionReason)) p.SetJobReason(RunAlphaServiceTerminalConditionJobReasonEnumToProto(o.JobReason)) return p } // ServiceTrafficStatusesToProto converts a ServiceTrafficStatuses object to its proto representation. func RunAlphaServiceTrafficStatusesToProto(o *alpha.ServiceTrafficStatuses) *alphapb.RunAlphaServiceTrafficStatuses { if o == nil { return nil } p := &alphapb.RunAlphaServiceTrafficStatuses{} p.SetType(RunAlphaServiceTrafficStatusesTypeEnumToProto(o.Type)) p.SetRevision(dcl.ValueOrEmptyString(o.Revision)) p.SetPercent(dcl.ValueOrEmptyInt64(o.Percent)) p.SetTag(dcl.ValueOrEmptyString(o.Tag)) p.SetUri(dcl.ValueOrEmptyString(o.Uri)) return p } // ServiceToProto converts a Service resource to its proto representation. func ServiceToProto(resource *alpha.Service) *alphapb.RunAlphaService { p := &alphapb.RunAlphaService{} p.SetName(dcl.ValueOrEmptyString(resource.Name)) p.SetDescription(dcl.ValueOrEmptyString(resource.Description)) p.SetUid(dcl.ValueOrEmptyString(resource.Uid)) p.SetGeneration(dcl.ValueOrEmptyInt64(resource.Generation)) p.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime)) p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime)) p.SetDeleteTime(dcl.ValueOrEmptyString(resource.DeleteTime)) p.SetExpireTime(dcl.ValueOrEmptyString(resource.ExpireTime)) p.SetCreator(dcl.ValueOrEmptyString(resource.Creator)) p.SetLastModifier(dcl.ValueOrEmptyString(resource.LastModifier)) p.SetClient(dcl.ValueOrEmptyString(resource.Client)) p.SetClientVersion(dcl.ValueOrEmptyString(resource.ClientVersion)) p.SetIngress(RunAlphaServiceIngressEnumToProto(resource.Ingress)) p.SetLaunchStage(RunAlphaServiceLaunchStageEnumToProto(resource.LaunchStage)) p.SetBinaryAuthorization(RunAlphaServiceBinaryAuthorizationToProto(resource.BinaryAuthorization)) p.SetTemplate(RunAlphaServiceTemplateToProto(resource.Template)) p.SetTerminalCondition(RunAlphaServiceTerminalConditionToProto(resource.TerminalCondition)) p.SetLatestReadyRevision(dcl.ValueOrEmptyString(resource.LatestReadyRevision)) p.SetLatestCreatedRevision(dcl.ValueOrEmptyString(resource.LatestCreatedRevision)) p.SetUri(dcl.ValueOrEmptyString(resource.Uri)) p.SetReconciling(dcl.ValueOrEmptyBool(resource.Reconciling)) p.SetEtag(dcl.ValueOrEmptyString(resource.Etag)) p.SetProject(dcl.ValueOrEmptyString(resource.Project)) p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) mLabels := make(map[string]string, len(resource.Labels)) for k, r := range resource.Labels { mLabels[k] = r } p.SetLabels(mLabels) mAnnotations := make(map[string]string, len(resource.Annotations)) for k, r := range resource.Annotations { mAnnotations[k] = r } p.SetAnnotations(mAnnotations) sTraffic := make([]*alphapb.RunAlphaServiceTraffic, len(resource.Traffic)) for i, r := range resource.Traffic { sTraffic[i] = RunAlphaServiceTrafficToProto(&r) } p.SetTraffic(sTraffic) sTrafficStatuses := make([]*alphapb.RunAlphaServiceTrafficStatuses, len(resource.TrafficStatuses)) for i, r := range resource.TrafficStatuses { sTrafficStatuses[i] = RunAlphaServiceTrafficStatusesToProto(&r) } p.SetTrafficStatuses(sTrafficStatuses) return p } // applyService handles the gRPC request by passing it to the underlying Service Apply() method. func (s *ServiceServer) applyService(ctx context.Context, c *alpha.Client, request *alphapb.ApplyRunAlphaServiceRequest) (*alphapb.RunAlphaService, error) { p := ProtoToService(request.GetResource()) res, err := c.ApplyService(ctx, p) if err != nil { return nil, err } r := ServiceToProto(res) return r, nil } // applyRunAlphaService handles the gRPC request by passing it to the underlying Service Apply() method. func (s *ServiceServer) ApplyRunAlphaService(ctx context.Context, request *alphapb.ApplyRunAlphaServiceRequest) (*alphapb.RunAlphaService, error) { cl, err := createConfigService(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return s.applyService(ctx, cl, request) } // DeleteService handles the gRPC request by passing it to the underlying Service Delete() method. func (s *ServiceServer) DeleteRunAlphaService(ctx context.Context, request *alphapb.DeleteRunAlphaServiceRequest) (*emptypb.Empty, error) { cl, err := createConfigService(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteService(ctx, ProtoToService(request.GetResource())) } // ListRunAlphaService handles the gRPC request by passing it to the underlying ServiceList() method. func (s *ServiceServer) ListRunAlphaService(ctx context.Context, request *alphapb.ListRunAlphaServiceRequest) (*alphapb.ListRunAlphaServiceResponse, error) { cl, err := createConfigService(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } resources, err := cl.ListService(ctx, request.GetProject(), request.GetLocation()) if err != nil { return nil, err } var protos []*alphapb.RunAlphaService for _, r := range resources.Items { rp := ServiceToProto(r) protos = append(protos, rp) } p := &alphapb.ListRunAlphaServiceResponse{} p.SetItems(protos) return p, nil } func createConfigService(ctx context.Context, service_account_file string) (*alpha.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return alpha.NewClient(conf), nil }
package main import ( "fmt" "math" ) var a1, a2 int var b1, b2 = 1, 2 var ( e float32 f bool ) const ( a = iota b, c = iota, iota d = iota ) const j = iota const k, y = iota, iota func basic() { var z float64 fmt.Println(z, -z, 1/z, -1/z, z/z) // "0 -0 +Inf -Inf NaN" nan := math.NaN() fmt.Println(math.IsNaN(z / z)) // true fmt.Println(nan == nan, nan < nan, nan > nan) // "false false false" NaN和任何数都是不相等 fmt.Println(a1) fmt.Println(b1) fmt.Println(f) fmt.Println(c) fmt.Println(d) } func complex() { var t = 2.1 + 0.1i fmt.Println(real(t)) fmt.Println(imag(t)) } func main() { complex() }
package common import ( "reflect" "strings" ) //结构体转为map func Struct2Map(obj interface{}, notcol string) map[string]interface{} { t := reflect.TypeOf(obj) v := reflect.ValueOf(obj) var data = make(map[string]interface{}) for i := 0; i < t.NumField(); i++ { if !strings.Contains(notcol, t.Field(i).Name) { data[t.Field(i).Name] = v.Field(i).Interface() } } return data }
package memory import ( "fmt" "regexp" "sort" "strings" "sync" "time" "github.com/signaller-matrix/signaller/internal" "github.com/signaller-matrix/signaller/internal/models" "github.com/signaller-matrix/signaller/internal/models/common" "github.com/signaller-matrix/signaller/internal/models/createroom" "github.com/signaller-matrix/signaller/internal/models/events" "github.com/wangjia184/sortedset" ) type Backend struct { data map[string]internal.User rooms map[string]internal.Room events *sortedset.SortedSet roomAliases map[string]internal.Room hostname string validateUsernameFunc func(string) error // TODO: create ability to redefine validation func mutex sync.RWMutex } type Token struct { Device string } func NewBackend(hostname string) *Backend { return &Backend{ hostname: hostname, validateUsernameFunc: defaultValidationUsernameFunc, rooms: make(map[string]internal.Room), roomAliases: make(map[string]internal.Room), events: sortedset.New(), data: make(map[string]internal.User)} } func (backend *Backend) Register(username, password, device string) (user internal.User, token string, err models.ApiError) { backend.mutex.Lock() if backend.validateUsernameFunc != nil { err := backend.validateUsernameFunc(username) if err != nil { return nil, "", models.NewError(models.M_INVALID_USERNAME, err.Error()) } } if _, ok := backend.data[username]; ok { backend.mutex.Unlock() return nil, "", models.NewError(models.M_USER_IN_USE, "trying to register a user ID which has been taken") } user = &User{ name: username, password: password, Tokens: make(map[string]Token), backend: backend, filters: make(map[string]common.Filter)} backend.data[username] = user backend.mutex.Unlock() return backend.Login(username, password, device) } func (backend *Backend) Login(username, password, device string) (user internal.User, token string, err models.ApiError) { backend.mutex.Lock() defer backend.mutex.Unlock() user, ok := backend.data[username] if !ok { return nil, "", models.NewError(models.M_FORBIDDEN, "wrong username") } if user.Password() != password { return nil, "", models.NewError(models.M_FORBIDDEN, "wrong password") } token = internal.RandomString(defaultTokenSize) backend.data[username].(*User).Tokens[token] = Token{Device: device} return user, token, nil } func (backend *Backend) GetUserByToken(token string) internal.User { backend.mutex.RLock() defer backend.mutex.RUnlock() for _, user := range backend.data { for userToken := range user.(*User).Tokens { if userToken == token { return user } } } return nil } func (backend *Backend) GetRoomByID(id string) internal.Room { backend.mutex.RLock() defer backend.mutex.RUnlock() for roomID, room := range backend.rooms { if roomID == id { return room } } return nil } func (backend *Backend) GetUserByName(userName string) internal.User { backend.mutex.RLock() defer backend.mutex.RUnlock() if user, exists := backend.data[userName]; exists { return user } return nil } func (backend *Backend) PublicRooms(filter string) []internal.Room { backend.mutex.RLock() defer backend.mutex.RUnlock() var rooms []internal.Room for _, room := range backend.rooms { if room.State() == createroom.PublicChat && (strings.Contains(room.Name(), filter) || strings.Contains(room.Topic(), filter) || strings.Contains(room.AliasName(), filter)) { rooms = append(rooms, room) } } sort.Sort(BySize(rooms)) return rooms } func (backend *Backend) GetRoomByAlias(alias string) internal.Room { backend.mutex.RLock() defer backend.mutex.RUnlock() alias = internal.StripAlias(backend.hostname, alias) if room, exists := backend.roomAliases[alias]; exists { return room } return nil } func (backend *Backend) ValidateUsernameFunc() func(string) error { backend.mutex.RLock() defer backend.mutex.RUnlock() return backend.validateUsernameFunc } func defaultValidationUsernameFunc(userName string) error { const re = `^\w{5,}$` if !regexp.MustCompile(re).MatchString(userName) { return fmt.Errorf("username does not match %s", re) } return nil } func (backend *Backend) GetEventByID(id string) events.Event { backend.mutex.RLock() defer backend.mutex.RUnlock() return backend.events.GetByKey(id).Value.(events.Event) } func (backend *Backend) PutEvent(event events.Event) error { backend.mutex.Lock() defer backend.mutex.Unlock() backend.events.AddOrUpdate(event.ID(), sortedset.SCORE(time.Now().Unix()), event) return nil } func (backend *Backend) GetEventsSince(user internal.User, sinceToken string, limit int) []events.Event { sinceEventNode := backend.events.GetByKey(sinceToken) sEvents := backend.events.GetByScoreRange(sinceEventNode.Score(), -1, &sortedset.GetByScoreRangeOptions{ Limit: limit, }) eventsSlice := extractEventsFromNodes(sEvents) var returnEvents []events.Event for _, event := range eventsSlice { if isEventRelatedToUser(event, user) { returnEvents = append(returnEvents, event) } } return returnEvents } func extractEventsFromNodes(nodes []*sortedset.SortedSetNode) []events.Event { var eventsSlice []events.Event for _, e := range nodes { eventsSlice = append(eventsSlice, e.Value.(events.Event)) } return eventsSlice } func isEventRelatedToUser(event events.Event, user internal.User) bool { if roomEvent, ok := event.(*events.RoomEvent); ok { if internal.InArray(roomEvent.RoomID, extractRoomIDsFromModel(user.JoinedRooms())) { return true } } return false } func extractRoomIDsFromModel(rooms []internal.Room) []string { var roomIDs []string for _, room := range rooms { roomIDs = append(roomIDs, room.ID()) } return roomIDs }
// Copyright 2019 The Kubernetes Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package installation import ( "os" "path/filepath" "reflect" "runtime" "testing" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/krew/pkg/index" ) func Test_osArch_default(t *testing.T) { inOS, inArch := runtime.GOOS, runtime.GOARCH outOS, outArch := osArch() if inOS != outOS { t.Fatalf("returned OS=%q; expected=%q", outOS, inOS) } if inArch != outArch { t.Fatalf("returned Arch=%q; expected=%q", outArch, inArch) } } func Test_osArch_override(t *testing.T) { customOS, customArch := "dragons", "v1" os.Setenv("KREW_OS", customOS) defer os.Unsetenv("KREW_OS") os.Setenv("KREW_ARCH", customArch) defer os.Unsetenv("KREW_ARCH") outOS, outArch := osArch() if customOS != outOS { t.Fatalf("returned OS=%q; expected=%q", outOS, customOS) } if customArch != outArch { t.Fatalf("returned Arch=%q; expected=%q", outArch, customArch) } } func Test_matchPlatformToSystemEnvs(t *testing.T) { matchingPlatform := index.Platform{ URI: "A", Selector: &v1.LabelSelector{ MatchLabels: map[string]string{ "os": "foo", }, }, Files: nil, } type args struct { i index.Plugin } tests := []struct { name string args args wantPlatform index.Platform wantFound bool wantErr bool }{ { name: "Test Matching Index", args: args{ i: index.Plugin{ Spec: index.PluginSpec{ Platforms: []index.Platform{ matchingPlatform, { URI: "B", Selector: &v1.LabelSelector{ MatchLabels: map[string]string{ "os": "None", }, }, }, }, }, }, }, wantPlatform: matchingPlatform, wantFound: true, wantErr: false, }, { name: "Test Matching Index Not Found", args: args{ i: index.Plugin{ Spec: index.PluginSpec{ Platforms: []index.Platform{ { URI: "B", Selector: &v1.LabelSelector{ MatchLabels: map[string]string{ "os": "None", }, }, }, }, }, }, }, wantPlatform: index.Platform{}, wantFound: false, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotPlatform, gotFound, err := matchPlatformToSystemEnvs(tt.args.i, "foo", "amdBar") if (err != nil) != tt.wantErr { t.Errorf("GetMatchingPlatform() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(gotPlatform, tt.wantPlatform) { t.Errorf("GetMatchingPlatform() gotPlatform = %v, want %v", gotPlatform, tt.wantPlatform) } if gotFound != tt.wantFound { t.Errorf("GetMatchingPlatform() gotFound = %v, want %v", gotFound, tt.wantFound) } }) } } func Test_getPluginVersion(t *testing.T) { wantVersion := "deadbeef" wantURI := "https://uri.git" platform := index.Platform{ URI: "https://uri.git", Sha256: "dEaDbEeF", } gotVersion, gotURI := getPluginVersion(platform) if gotVersion != wantVersion { t.Errorf("getPluginVersion() gotVersion = %v, want %v", gotVersion, wantVersion) } if gotURI != wantURI { t.Errorf("getPluginVersion() gotURI = %v, want %v", gotURI, wantURI) } } func Test_getDownloadTarget(t *testing.T) { matchingPlatform := index.Platform{ URI: "https://uri.git", Sha256: "deadbeef", Selector: &v1.LabelSelector{ MatchLabels: map[string]string{ "os": runtime.GOOS, }, }, Bin: "kubectl-foo", Files: nil, } type args struct { index index.Plugin } tests := []struct { name string args args wantVersion string wantURI string wantFos []index.FileOperation wantBin string wantErr bool }{ { name: "Find Matching Platform", args: args{ index: index.Plugin{ Spec: index.PluginSpec{ Platforms: []index.Platform{ matchingPlatform, { URI: "https://wrong.com", Selector: &v1.LabelSelector{ MatchLabels: map[string]string{ "os": "None", }, }, }, }, }, }, }, wantVersion: "deadbeef", wantURI: "https://uri.git", wantFos: nil, wantBin: "kubectl-foo", wantErr: false, }, { name: "No Matching Platform", args: args{ index: index.Plugin{ Spec: index.PluginSpec{ Platforms: []index.Platform{ { URI: "https://wrong.com", Selector: &v1.LabelSelector{ MatchLabels: map[string]string{ "os": "None", }, }, }, }, }, }, }, wantVersion: "", wantURI: "", wantFos: nil, wantBin: "", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotVersion, gotURI, gotFos, bin, err := getDownloadTarget(tt.args.index) if (err != nil) != tt.wantErr { t.Errorf("getDownloadTarget() error = %v, wantErr %v", err, tt.wantErr) return } if gotVersion != tt.wantVersion { t.Errorf("getDownloadTarget() gotVersion = %v, want %v", gotVersion, tt.wantVersion) } if bin != tt.wantBin { t.Errorf("getDownloadTarget() bin = %v, want %v", bin, tt.wantBin) } if gotURI != tt.wantURI { t.Errorf("getDownloadTarget() gotURI = %v, want %v", gotURI, tt.wantURI) } if !reflect.DeepEqual(gotFos, tt.wantFos) { t.Errorf("getDownloadTarget() gotFos = %v, want %v", gotFos, tt.wantFos) } }) } } func Test_findInstalledPluginVersion(t *testing.T) { type args struct { installPath string binDir string pluginName string } tests := []struct { name string args args wantName string wantInstalled bool wantErr bool }{ { name: "Find version", args: args{ installPath: filepath.Join(testdataPath(t), "index"), binDir: filepath.Join(testdataPath(t), "bin"), pluginName: "foo", }, wantName: "deadbeef", wantInstalled: true, wantErr: false, }, { name: "No installed version", args: args{ installPath: filepath.Join(testdataPath(t), "index"), binDir: filepath.Join(testdataPath(t), "bin"), pluginName: "not-found", }, wantName: "", wantInstalled: false, wantErr: false, }, { name: "Insecure name", args: args{ installPath: filepath.Join(testdataPath(t), "index"), binDir: filepath.Join(testdataPath(t), "bin"), pluginName: "../foo", }, wantName: "", wantInstalled: false, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotName, gotInstalled, err := findInstalledPluginVersion(tt.args.installPath, tt.args.binDir, tt.args.pluginName) if (err != nil) != tt.wantErr { t.Errorf("getOtherInstalledVersion() error = %v, wantErr %v", err, tt.wantErr) return } if gotName != tt.wantName { t.Errorf("getOtherInstalledVersion() gotName = %v, want %v", gotName, tt.wantName) } if gotInstalled != tt.wantInstalled { t.Errorf("getOtherInstalledVersion() gotInstalled = %v, want %v", gotInstalled, tt.wantInstalled) } }) } } func testdataPath(t *testing.T) string { pwd, err := filepath.Abs(".") if err != nil { t.Fatal(err) } return filepath.Join(pwd, "testdata") } func Test_pluginVersionFromPath(t *testing.T) { type args struct { installPath string pluginPath string } tests := []struct { name string args args want string wantErr bool }{ { name: "normal version", args: args{ installPath: filepath.FromSlash("install/"), pluginPath: filepath.FromSlash("install/foo/HEAD/kubectl-foo"), }, want: "HEAD", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := pluginVersionFromPath(tt.args.installPath, tt.args.pluginPath) if (err != nil) != tt.wantErr { t.Errorf("pluginVersionFromPath() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { t.Errorf("pluginVersionFromPath() = %v, want %v", got, tt.want) } }) } }
package range_sum_bst // TreeNode provides interface for treeNode struct type TreeNode interface { GetValue() int GetRight() TreeNode GetLeft() TreeNode SetRight(TreeNode) SetLeft(TreeNode) } type treeNode struct { val int left TreeNode right TreeNode } func (t *treeNode) GetValue() int { return t.val } func (t *treeNode) GetRight() TreeNode { return t.right } func (t *treeNode) GetLeft() TreeNode { return t.left } func (t *treeNode) SetLeft(treeNode TreeNode) { t.left = treeNode } func (t *treeNode) SetRight(treeNode TreeNode) { t.right = treeNode } // NewTreeNode ... func NewTreeNode(val int) TreeNode { return &treeNode{ val: val, left: nil, right: nil, } }
/* We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible results: -1: Your guess is higher than the number I picked (i.e. num > pick). 1: Your guess is lower than the number I picked (i.e. num < pick). 0: your guess is equal to the number I picked (i.e. num == pick). Return the number that I picked. Example 1: Input: n = 10, pick = 6 Output: 6 Example 2: Input: n = 1, pick = 1 Output: 1 Example 3: Input: n = 2, pick = 1 Output: 1 Constraints: 1 <= n <= 2^31 - 1 1 <= pick <= n */ package main import ( "sort" ) func main() { assert(guess(10, mknum(6)) == 6) assert(guess(1, mknum(1)) == 1) assert(guess(2, mknum(1)) == 1) assert(guess(2e5, mknum(1e4)) == 1e4) } func assert(x bool) { if !x { panic("assertion failed") } } func guess(n int, f func(int) int) int { return sort.Search(n, func(i int) bool { return f(i) <= 0 }) } func mknum(n int) func(int) int { return func(i int) int { switch { case i > n: return -1 case i == n: return 0 default: return 1 } } }
package testing import ( "fmt" "github.com/devspace-cloud/devspace/pkg/util/survey" fakesurvey "github.com/devspace-cloud/devspace/pkg/util/survey/testing" "github.com/sirupsen/logrus" ) // FakeLogger just discards every log statement type FakeLogger struct { Survey *fakesurvey.FakeSurvey } // NewFakeLogger returns a new fake logger func NewFakeLogger() *FakeLogger { return &FakeLogger{ Survey: fakesurvey.NewFakeSurvey(), } } // Debug implements logger interface func (d *FakeLogger) Debug(args ...interface{}) {} // Debugf implements logger interface func (d *FakeLogger) Debugf(format string, args ...interface{}) {} // Info implements logger interface func (d *FakeLogger) Info(args ...interface{}) {} // Infof implements logger interface func (d *FakeLogger) Infof(format string, args ...interface{}) {} // Warn implements logger interface func (d *FakeLogger) Warn(args ...interface{}) {} // Warnf implements logger interface func (d *FakeLogger) Warnf(format string, args ...interface{}) {} // Error implements logger interface func (d *FakeLogger) Error(args ...interface{}) {} // Errorf implements logger interface func (d *FakeLogger) Errorf(format string, args ...interface{}) {} // Fatal implements logger interface func (d *FakeLogger) Fatal(args ...interface{}) { d.Panic(args...) } // Fatalf implements logger interface func (d *FakeLogger) Fatalf(format string, args ...interface{}) { d.Panicf(format, args...) } // Panic implements logger interface func (d *FakeLogger) Panic(args ...interface{}) { panic(fmt.Sprint(args...)) } // Panicf implements logger interface func (d *FakeLogger) Panicf(format string, args ...interface{}) { panic(fmt.Sprintf(format, args...)) } // Done implements logger interface func (d *FakeLogger) Done(args ...interface{}) {} // Donef implements logger interface func (d *FakeLogger) Donef(format string, args ...interface{}) {} // Fail implements logger interface func (d *FakeLogger) Fail(args ...interface{}) {} // Failf implements logger interface func (d *FakeLogger) Failf(format string, args ...interface{}) {} // Print implements logger interface func (d *FakeLogger) Print(level logrus.Level, args ...interface{}) {} // Printf implements logger interface func (d *FakeLogger) Printf(level logrus.Level, format string, args ...interface{}) {} // StartWait implements logger interface func (d *FakeLogger) StartWait(message string) {} // StopWait implements logger interface func (d *FakeLogger) StopWait() {} // SetLevel implements logger interface func (d *FakeLogger) SetLevel(level logrus.Level) {} // GetLevel implements logger interface func (d *FakeLogger) GetLevel() logrus.Level { return logrus.FatalLevel } // Write implements logger interface func (d *FakeLogger) Write(message []byte) (int, error) { return len(message), nil } // WriteString implements logger interface func (d *FakeLogger) WriteString(message string) {} // Question asks a new question func (d *FakeLogger) Question(params *survey.QuestionOptions) (string, error) { return d.Survey.Question(params) }
package leetcode func InOrder(cur *TreeNode, tail **TreeNode) { if cur != nil { InOrder(cur.Left, tail) (**tail).Right = cur (**tail).Left = nil *tail = cur InOrder(cur.Right, tail) } } func increasingBST(root *TreeNode) *TreeNode { tmp := &TreeNode{} out := tmp InOrder(root, &tmp) tmp.Left = nil return out.Right }
package storage import ( "context" "github.com/vitalyisaev2/buildgraph/common" "github.com/vitalyisaev2/buildgraph/vcs" ) // Storage is an abstraction layer above the particular SQL/NoSQL storages; // it should implement all the methods required by front and graph layer; type Storage interface { // PushEvent SavePushEvent(context.Context, vcs.PushEvent) error common.Service }
package piscine func NRune(s string, n int) rune { for index, runes := range s { //the index starts from zero, hence +1 if n == index+1 { return runes } } return 0 }
package Data import ( "golang.org/x/text/encoding" "golang.org/x/text/encoding/charmap" "golang.org/x/text/encoding/unicode" ) type Encoding interface { Encode(str string) ([]byte, error) Decode([]byte) (string, error) } func encode(str string, encoder *encoding.Encoder) ([]byte, error) { return encoder.Bytes([]byte(str)) } func decode(data []byte, decoder *encoding.Decoder) (string, error) { tmp, err := decoder.Bytes(data) if err != nil { return "", err } return string(tmp), nil } // ENC_GSM7BIT_s ... type ENC_GSM7BIT_s struct { } func (c ENC_GSM7BIT_s) Encode(str string) ([]byte, error) { return Encode7Bit(str), nil } func (c ENC_GSM7BIT_s) Decode(data []byte) (string, error) { return Decode7Bit(data) } // ENC_ASCII_s .. type ENC_ASCII_s struct { } func (c ENC_ASCII_s) Encode(str string) ([]byte, error) { return []byte(str), nil } func (c ENC_ASCII_s) Decode(data []byte) (string, error) { return string(data), nil } // ENC_UTF8_s .. type ENC_UTF8_s struct { } func (c ENC_UTF8_s) Encode(str string) ([]byte, error) { return []byte(str), nil } func (c ENC_UTF8_s) Decode(data []byte) (string, error) { return string(data), nil } // ENC_CP1252_s ... type ENC_CP1252_s struct{} func (c ENC_CP1252_s) Encode(str string) ([]byte, error) { return encode(str, charmap.Windows1252.NewEncoder()) } func (c ENC_CP1252_s) Decode(data []byte) (string, error) { return decode(data, charmap.Windows1252.NewDecoder()) } // ENC_ISO8859_1_s ... type ENC_ISO8859_1_s struct{} func (c ENC_ISO8859_1_s) Encode(str string) ([]byte, error) { return encode(str, charmap.ISO8859_1.NewEncoder()) } func (c ENC_ISO8859_1_s) Decode(data []byte) (string, error) { return decode(data, charmap.ISO8859_1.NewDecoder()) } // ENC_UTF16_BEM_s ... type ENC_UTF16_BEM_s struct{} func (c ENC_UTF16_BEM_s) Encode(str string) ([]byte, error) { tmp := unicode.UTF16(unicode.BigEndian, unicode.UseBOM) return encode(str, tmp.NewEncoder()) } func (c ENC_UTF16_BEM_s) Decode(data []byte) (string, error) { tmp := unicode.UTF16(unicode.BigEndian, unicode.UseBOM) return decode(data, tmp.NewDecoder()) } // ENC_UTF16_LEM_s ... type ENC_UTF16_LEM_s struct{} func (c ENC_UTF16_LEM_s) Encode(str string) ([]byte, error) { tmp := unicode.UTF16(unicode.LittleEndian, unicode.UseBOM) return encode(str, tmp.NewEncoder()) } func (c ENC_UTF16_LEM_s) Decode(data []byte) (string, error) { tmp := unicode.UTF16(unicode.LittleEndian, unicode.UseBOM) return decode(data, tmp.NewDecoder()) } // ENC_UTF16_BE_s ... type ENC_UTF16_BE_s struct{} func (c ENC_UTF16_BE_s) Encode(str string) ([]byte, error) { tmp := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) return encode(str, tmp.NewEncoder()) } func (c ENC_UTF16_BE_s) Decode(data []byte) (string, error) { tmp := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) return decode(data, tmp.NewDecoder()) } // ENC_UTF16_LE_s ... type ENC_UTF16_LE_s struct{} func (c ENC_UTF16_LE_s) Encode(str string) ([]byte, error) { tmp := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM) return encode(str, tmp.NewEncoder()) } func (c ENC_UTF16_LE_s) Decode(data []byte) (string, error) { tmp := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM) return decode(data, tmp.NewDecoder()) } // ENC_UTF16_s ... type ENC_UTF16_s struct{} func (c ENC_UTF16_s) Encode(str string) ([]byte, error) { tmp := unicode.UTF16(unicode.BigEndian, unicode.ExpectBOM) return encode(str, tmp.NewEncoder()) } func (c ENC_UTF16_s) Decode(data []byte) (string, error) { tmp := unicode.UTF16(unicode.BigEndian, unicode.ExpectBOM) return decode(data, tmp.NewDecoder()) } // Ascii var ENC_ASCII Encoding = ENC_ASCII_s{} // Ascii var CHAR_ENC Encoding = ENC_ASCII // Windows Latin-1 var ENC_CP1252 Encoding = ENC_CP1252_s{} // GSM 7-bit unpacked var ENC_GSM7BIT Encoding = ENC_GSM7BIT_s{} // Eight-bit Unicode Transformation Format var ENC_UTF8 Encoding = ENC_UTF8_s{} // ISO 8859-1, Latin alphabet No. 1 var ENC_ISO8859_1 Encoding = ENC_ISO8859_1_s{} var ENC_UTF16_BEM Encoding = ENC_UTF16_BEM_s{} var ENC_UTF16_BE Encoding = ENC_UTF16_BE_s{} var ENC_UTF16_LEM Encoding = ENC_UTF16_LEM_s{} var ENC_UTF16_LE Encoding = ENC_UTF16_LE_s{} var ENC_UTF16 Encoding = ENC_UTF16_s{}
package neatly import ( "github.com/stretchr/testify/assert" "github.com/viant/toolbox" "testing" ) func Test_asDataStructure(t *testing.T) { { input := `[1,2,3]` output, err := asDataStructure(input) assert.Nil(t, err) assert.EqualValues(t, []interface{}{float64(1), float64(2), float64(3)}, output) } { input := `{"a":1, "b":2}` output, err := asDataStructure(input) if assert.Nil(t, err) { outputMap := toolbox.AsMap(output) assert.EqualValues(t, map[string]interface{}{ "a": float64(1), "b": float64(2), }, outputMap) } } { input := `{"a":1, "b":2} {"a2":2, "b3":21} {"a3":3, "b4:22} ` output, err := asDataStructure(input) if assert.Nil(t, err) { outputMap := toolbox.AsString(output) assert.EqualValues(t, input, outputMap) } } } func Test_getAssetURIs(t *testing.T) { assert.EqualValues(t, []string{"a", "c", "z"}, getAssetURIs("a|c|z")) assert.EqualValues(t, []string{"a", "c", "z"}, getAssetURIs("a | c | z ")) assert.EqualValues(t, []string{"a", "c", "z"}, getAssetURIs("a c z ")) assert.EqualValues(t, []string{"[a]", "c", "z"}, getAssetURIs("[a] |c | z ")) assert.EqualValues(t, []string{"a", "{c}", "z"}, getAssetURIs("a |{c} | z ")) }
package filters import ( "strconv" "github.com/neuronlabs/neuron-core/query" "github.com/neuronlabs/neuron-postgres/internal" ) // Incrementor is the function that returns next query increment value. // Used to obtain the queries values with the incremented arguments. func Incrementor(s *query.Scope) int { return incrementor(s) } // StringIncrementor is the function that returns next query increment value in a string form. // Used to obtain the queries values with the incremented arguments. func StringIncrementor(s *query.Scope) string { return "$" + strconv.Itoa(incrementor(s)) } /** PRIVATE */ func incrementor(s *query.Scope) int { inc, _ := s.StoreGet(internal.IncrementorKey) if inc == nil { inc = 0 } i := inc.(int) + 1 s.StoreSet(internal.IncrementorKey, i) return i }
package main import ( "context" "log" "os" "strings" "time" "google.golang.org/grpc" "github.com/bradenbass/echo/client/sdk" echopb "github.com/bradenbass/echo/proto" ) func main() { args := os.Args // Create a new Echoer Client echoerClient, err := echo.NewClient("127.0.0.1:9000", true) if err != nil { log.Fatalf("Unable to create a new client: %v", err) } // Limit how long we wait for a reply from the server ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() // Send RPC to Server res, err := echoerClient.Echo(ctx, &echopb.EchoRequest{ Message: strings.Join(args[1:], " "), }, grpc.WaitForReady(true)) if err != nil { log.Fatalf("Error trying to send message to server: %v", err) } log.Printf("Received reply from server: %s", res.Reply) }
package primitives_test import ( "encoding/xml" "fmt" "github.com/plandem/xlsx/format" "github.com/plandem/xlsx/internal/ml/primitives" "github.com/stretchr/testify/require" "testing" ) func TestConditionOperator(t *testing.T) { type Entity struct { Attribute primitives.ConditionOperatorType `xml:"attribute,attr"` } list := map[string]primitives.ConditionOperatorType{ "": primitives.ConditionOperatorType(0), "lessThan": format.ConditionOperatorLessThan, "lessThanOrEqual": format.ConditionOperatorLessThanOrEqual, "equal": format.ConditionOperatorEqual, "notEqual": format.ConditionOperatorNotEqual, "greaterThanOrEqual": format.ConditionOperatorGreaterThanOrEqual, "greaterThan": format.ConditionOperatorGreaterThan, "between": format.ConditionOperatorBetween, "notBetween": format.ConditionOperatorNotBetween, "containsText": format.ConditionOperatorContainsText, "notContains": format.ConditionOperatorNotContains, "beginsWith": format.ConditionOperatorBeginsWith, "endsWith": format.ConditionOperatorEndsWith, } for s, v := range list { t.Run(s, func(tt *testing.T) { entity := Entity{Attribute: v} encoded, err := xml.Marshal(&entity) require.Empty(tt, err) if s == "" { require.Equal(tt, `<Entity></Entity>`, string(encoded)) } else { require.Equal(tt, fmt.Sprintf(`<Entity attribute="%s"></Entity>`, s), string(encoded)) } var decoded Entity err = xml.Unmarshal(encoded, &decoded) require.Empty(tt, err) require.Equal(tt, entity, decoded) require.Equal(tt, s, decoded.Attribute.String()) }) } }
package main import ( "encoding/json" "flag" "fmt" "log" "net/http" "os" "strconv" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/slcjordan/reading" ) var info = log.New(os.Stdout, "", log.LstdFlags) func filename(r *http.Request) string { return map[string]string{ "book-of-mormon": "../books/book-of-mormon.json", "new-testament": "../books/new-testament.json", "old-testament": "../books/old-testament.json", "doctrine-and-covenants": "../books/doctrine-and-covenants.json", "pearl-of-great-price": "../books/pearl-of-great-price.json", }[r.URL.Query().Get("book")] } func breakdowns(r *http.Request) []reading.Breakdown { return map[string][]reading.Breakdown{ "chapter": []reading.Breakdown{reading.Book, reading.Chapter}, "verse": []reading.Breakdown{reading.Reference}, }[r.URL.Query().Get("breakdown")] } func days(r *http.Request) int { days, err := strconv.ParseInt(r.URL.Query().Get("days"), 10, 0) if err != nil { return 0 } return int(days) } func algorithm(r *http.Request) reading.Algorithm { return map[string]reading.Algorithm{ "chapter": reading.Dynamic, "verse": reading.Greedy, }[r.URL.Query().Get("breakdown")] } func handler(w http.ResponseWriter, r *http.Request) { fmt.Printf("%v %v %v %v = %v", filename(r), days(r), breakdowns(r), algorithm(r), reading.Plan( filename(r), days(r), algorithm(r), breakdowns(r)..., )) out := json.NewEncoder(w) err := out.Encode( reading.Plan( filename(r), days(r), algorithm(r), breakdowns(r)..., )) if err != nil { info.Println(err) } } func main() { var addr string var static string flag.StringVar(&addr, "addr", "0.0.0.0:80", "the address to serve from") flag.StringVar(&static, "static", "dist", "the static directory") flag.Parse() defer os.RemoveAll(reading.CacheDirectory) r := mux.NewRouter() r.HandleFunc("/plan", handler) r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir(static)))) info.Println("serving at " + addr) http.ListenAndServe(addr, handlers.RecoveryHandler( handlers.PrintRecoveryStack(true), )( handlers.LoggingHandler(os.Stdout, handlers.CompressHandler(r), ))) }
package biliLiveHelper type CmdType string const ( CmdAll CmdType = "" CmdLive CmdType = "LIVE" CmdPreparing CmdType = "PREPARING" CmdDanmuMsg CmdType = "DANMU_MSG" CmdWelcomeGuard CmdType = "WELCOME_GUARD" CmdWelcome CmdType = "WELCOME" CmdSendGift CmdType = "SEND_GIFT" CmdNoticeMsg CmdType = "NOTICE_MSG" CmdRealTimeMessageUpdate CmdType = "ROOM_REAL_TIME_MESSAGE_UPDATE" CmdOnlineChange CmdType = "ONLINE_CHANGE" CmdInteractWord CmdType = "INTERACT_WORD" ) type MsgHandler interface { Handle(ctx *Context) bool } type Handle func(ctx *Context) bool func (f Handle) Handle(ctx *Context) bool { return f(ctx)} type HandleChain []MsgHandler func (c *Client) RegHandleFunc(cmdType CmdType, handler Handle) { if len(c.handlers) >= abortIndex { panic("too many handlers") } c.handlers[cmdType] = append(c.handlers[cmdType], handler) }
package problem0693 func hasAlternatingBits(n int) bool { // 如果符合条件的话,这里的结果是 11111... tmp := n ^ (n >> 1) return (tmp & (tmp + 1)) == 0 }
package jira import ( "bytes" "errors" "io/ioutil" "net/http" "testing" ) type rt struct { err error response *http.Response } func (r rt) RoundTrip(req *http.Request) (*http.Response, error) { if r.err != nil { return nil, r.err } return r.response, nil } func TestConsumeResponseWithError(t *testing.T) { r := rt{err: errors.New("boom!")} client := DefaultClient{httpClient: &http.Client{Transport: r}} req, err := http.NewRequest("GET", "http://localhost:8080", nil) if err != nil { t.Fatalf("Unexpected error: %v\n", err) } _, _, err = client.consumeResponse(req) if err == nil { t.Fatalf("Expected error\n") } } func TestConsumeResponse(t *testing.T) { buffer := bytes.NewBufferString("hello") body := ioutil.NopCloser(buffer) response := &http.Response{Status: "200 OK", StatusCode: 200, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Body: body} r := rt{response: response} client := DefaultClient{httpClient: &http.Client{Transport: r}} req, err := http.NewRequest("GET", "http://localhost:8080", nil) if err != nil { t.Fatalf("Unexpected error: %v\n", err) } rc, data, err := client.consumeResponse(req) if err != nil { t.Fatalf("Unexpected error: %v\n", err) } if rc != 200 { t.Fatalf("Want 200 but got: %v\n", rc) } if string(data) != "hello" { t.Fatalf("Want hello but got: %v\n", string(data)) } }
package flag_test import ( "github.com/hoenirvili/skapt/argument" "github.com/hoenirvili/skapt/flag" gc "gopkg.in/check.v1" ) type flagsSuite struct{} var _ = gc.Suite(&flagsSuite{}) func (f flagsSuite) newFlags() flag.Flags { return flag.Flags{ {}, {Short: "u", Long: "url"}, {Short: "k", Long: "specialk"}, {Short: "l"}, {Long: "full"}, } } func (f flagsSuite) TestBool(c *gc.C) { flags := flag.Flags{} got := flags.Bool("") c.Assert(got, gc.Equals, false) flags = flag.Flags{{Short: "u", Long: "l"}} got = flags.Bool("u") c.Assert(got, gc.Equals, false) } func (f flagsSuite) TestInt(c *gc.C) { flags := flag.Flags{} got := flags.Int("") c.Assert(got, gc.Equals, 0) flags = flag.Flags{{Short: "u", Long: "l"}} got = flags.Int("u") c.Assert(got, gc.Equals, 0) } func (f flagsSuite) TestString(c *gc.C) { flags := flag.Flags{} got := flags.String("") c.Assert(got, gc.Equals, "") flags = flag.Flags{{Short: "u", Long: "l"}} got = flags.String("u") c.Assert(got, gc.Equals, "") } func (f flagsSuite) TestFloat(c *gc.C) { flags := flag.Flags{} got := flags.Float("") c.Assert(got, gc.DeepEquals, 0.0) flags = flag.Flags{{Short: "l", Long: "length"}} got = flags.Float("l") c.Assert(got, gc.Equals, 0.0) } func (f flagsSuite) TestValidate(c *gc.C) { flags := f.newFlags() err := flags.Validate() c.Assert(err, gc.NotNil) flags = flags[1:] err = flags.Validate() c.Assert(err, gc.IsNil) flags = flag.Flags{} err = flags.Validate() c.Assert(err, gc.IsNil) } func (f flagsSuite) TestValidateWithError(c *gc.C) { flags := flag.Flags{ {Short: "u", Long: "ul"}, {Short: "u", Long: "ul"}, {Short: "ul", Long: "u"}, } err := flags.Validate() c.Assert(err, gc.NotNil) } var empty flag.Flag func (f flagsSuite) TestFlag(c *gc.C) { flags := f.newFlags() fl := flags.Flag("") c.Assert(fl, gc.IsNil) fl = flags.Flag("u") c.Assert(fl, gc.DeepEquals, &flag.Flag{ Short: "u", Long: "url"}) } func (f flagsSuite) TestParse(c *gc.C) { flags := f.newFlags()[1:] test := struct { argss [][]string ups [][]string }{ argss: [][]string{ {"-u", "", "--full", "somevalue", "someothervalue"}, {"noflag", "", ""}, {"--unknown"}, {}, }, ups: [][]string{ {"somevalue", "someothervalue"}, {"noflag"}, {"unknown"}, {}, }, } for key, args := range test.argss { unparsed, err := flags.Parse(args) c.Assert(unparsed, gc.DeepEquals, test.ups[key]) c.Assert(err, gc.IsNil) } } func (f flagsSuite) TestValueParse(c *gc.C) { flags := flag.Flags{ {Short: "u", Long: "url", Type: argument.String}, {Short: "d", Long: "debug", Type: argument.Bool}, {Short: "t", Long: "times", Type: argument.Int}, {Short: "l", Long: "length", Type: argument.Float}, } args := []string{"-u", "www.google.com", "-t", "3", "--debug", "--length=3.25"} unparsed, err := flags.Parse(args) c.Assert(err, gc.IsNil) c.Assert(unparsed, gc.IsNil) link := flags.String("u") n := flags.Int("t") debug := flags.Bool("debug") length := flags.Float("l") c.Assert(link, gc.Equals, "www.google.com") c.Assert(n, gc.Equals, 3) c.Assert(debug, gc.Equals, true) c.Assert(length, gc.DeepEquals, 3.25) } func (f flagsSuite) TestParseWithErrors(c *gc.C) { flags := f.newFlags() flags[0] = flag.Flag{ Short: "t", Long: "ticks", } tests := []struct { args []string t argument.Type }{{[]string{"--ticks=llldsl1iudhaf", "-l"}, argument.Int}, {[]string{"--ticks=llldsl1iudhaf", "-l"}, argument.Bool}, {[]string{"--ticks", "other", "-l"}, argument.String}, {[]string{"--ticks=", "-l"}, argument.Int}, {[]string{"-t", "-l"}, argument.Int}, {[]string{"--ticks=", "-l"}, argument.Type(5)}, {[]string{"--ticks=100", "-t", "3"}, argument.Int}, } for _, test := range tests { flags[0].Type = test.t unparsed, err := flags.Parse(test.args) c.Assert(unparsed, gc.IsNil) c.Assert(err, gc.NotNil) } } func (f *flagsSuite) TestRequiredAreParsedWithError(c *gc.C) { flags := f.newFlags() flags[1].Required = true err := flags.RequiredAreParsed() c.Assert(err, gc.NotNil) } func (f *flagsSuite) TestRequiredAreParsed(c *gc.C) { flgs := flag.Flags{} err := flgs.RequiredAreParsed() c.Assert(err, gc.IsNil) flgs = f.newFlags() flgs = append(flgs, flag.ParsedAndRequired) err = flgs.RequiredAreParsed() c.Assert(err, gc.IsNil) } func (f *flagsSuite) TestAppendHelpIfNotPresent(c *gc.C) { flags := f.newFlags()[1:] flags.AppendHelpIfNotPresent() flag := flags.Flag("help") c.Assert(flag, gc.NotNil) flags.AppendHelpIfNotPresent() err := flags.Validate() c.Assert(err, gc.IsNil) flag = flags.Flag("help") c.Assert(flag, gc.NotNil) } func (f *flagsSuite) TestAppendVersionIfNotPresent(c *gc.C) { flags := f.newFlags()[1:] flags.AppendVersionIfNotPreset() flag := flags.Flag("version") c.Assert(flag, gc.NotNil) flags.AppendVersionIfNotPreset() err := flags.Validate() c.Assert(err, gc.IsNil) flag = flags.Flag("version") c.Assert(flag, gc.NotNil) }
package cwb import ( "context" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" ) const ( libraryVersion = "0.0.1" defaultBaseURL = "https://opendata.cwb.gov.tw/" defaultUserAgent = "go-cwb/" + libraryVersion ) type service struct { client *Client } // A Client manages communication with the CWB API. type Client struct { client *http.Client token string BaseURL *url.URL UserAgent string common service // Reuse a single struct instead of allocating one for each service on the heap. // Services Dataset *DatasetService Forecasts *ForecastsService StationObs *StationObsService TideForecasts *TideForecastsService } // NewClient returns a new CWB API client. The token are required for authentication. // If a nil httpClient is provided, http.DefaultClient will be used. func NewClient(token string, httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } baseURL, _ := url.Parse(defaultBaseURL) c := &Client{ client: httpClient, token: token, BaseURL: baseURL, UserAgent: defaultUserAgent, } c.common.client = c c.Dataset = (*DatasetService)(&c.common) c.Forecasts = (*ForecastsService)(&c.common) c.StationObs = (*StationObsService)(&c.common) c.TideForecasts = (*TideForecastsService)(&c.common) return c } // NewRequest creates an API request. func (c *Client) NewRequest(method, urlStr string, body io.Reader) (*http.Request, error) { rel, err := url.Parse(urlStr) if err != nil { return nil, err } u := c.BaseURL.ResolveReference(rel) req, err := http.NewRequest(method, u.String(), body) if err != nil { return nil, err } req.Header.Set("Authorization", c.token) if c.UserAgent != "" { req.Header.Set("User-Agent", c.UserAgent) } return req, nil } // Do sends an API request, and returns the API response. func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) { req = req.WithContext(ctx) resp, err := c.client.Do(req) if err != nil { // If we got an error, and the context has been canceled, // the context's error is probably more useful. select { case <-ctx.Done(): return nil, ctx.Err() default: } return nil, err } defer resp.Body.Close() if err := checkResponse(resp); err != nil { return resp, err } if v != nil { if w, ok := v.(io.Writer); ok { _, _ = io.Copy(w, resp.Body) } else { err = decodeResponse(resp.Body, v) } } return resp, err } // Get method make a GET HTTP request. func (c *Client) Get(ctx context.Context, url string, v interface{}) (*http.Response, error) { req, err := c.NewRequest("GET", url, nil) if err != nil { return nil, err } return c.Do(ctx, req, v) } func (c *Client) generateURL(dataId string, options url.Values) string { u, _ := url.Parse(fmt.Sprintf("api/v1/rest/datastore/%v", dataId)) u.RawQuery = options.Encode() return u.String() } // ErrorResponse reports error caused by an API request. type ErrorResponse struct { *http.Response Message string } func (e *ErrorResponse) Error() string { return fmt.Sprintf("error: %s", e.Message) } // checkResponse checks the API response for errors. func checkResponse(r *http.Response) error { if c := r.StatusCode; 200 <= c && c <= 299 { return nil } errorResponse := &ErrorResponse{Response: r, Message: "unknown"} switch r.StatusCode { case http.StatusUnauthorized, http.StatusNotFound: data, err := ioutil.ReadAll(r.Body) if err != nil { errorResponse.Message = fmt.Sprintf("reading body, %s", err.Error()) } else { errorResponse.Message = string(data) } } return errorResponse } // decodeResponse decodes the API response. func decodeResponse(body io.Reader, to interface{}) error { data, err := ioutil.ReadAll(body) if err != nil { return err } err = json.Unmarshal(data, to) if err != nil { return fmt.Errorf("error decoding body: %s", err.Error()) } return nil }
package encoding import ( "encoding/json" ) // TransformObject used to transform source object to result object based on json tag func TransformObject(source interface{}, result interface{}) error { sourceBytes, err := json.Marshal(source) if err != nil { return err } err = json.Unmarshal(sourceBytes, &result) if err != nil { return err } return nil }
package msgHandler import ( "encoding/json" "fmt" "github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/reqMsg" "time" com "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/consensusManager/comm/consensusType" "github.com/HNB-ECO/HNB-Blockchain/HNB/ledger" "github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork" "math/rand" ) const ( NORMAL int = iota + 1 VERSION_ERRO HEIGHT_ERRO PARA_NIL_ERRO ) type HeightReqOutBg struct { version uint64 } func NewHeightReqOutBG() *HeightReqOutBg { return &HeightReqOutBg{} } type HeightReq struct { version uint64 min *MinHeightPeer count int } type MinHeightPeer struct { peerID uint64 blkNum uint64 } func NewHeightReq() *HeightReq { return &HeightReq{min: &MinHeightPeer{}} } func (h *TDMMsgHandler) SetMinHeightPeer(peerID uint64, blkNum uint64) { if peerID < 0 || blkNum < 0 { ConsLog.Errorf(CONSENSUS, "(setminheightpeer) peerID (%v) blkNum (%d)", peerID, blkNum) return } h.heightReq.min.peerID = peerID h.heightReq.min.blkNum = blkNum } func (h *TDMMsgHandler) ResetMinHeightPeer() { h.heightReq.version++ h.heightReq.min.peerID = 0 h.heightReq.min.blkNum = 0 h.heightReq.count = 0 } func (h *TDMMsgHandler) GetMinHeightPeer() (uint64, uint64, error) { peerID := h.heightReq.min.peerID blkNum := h.heightReq.min.blkNum return peerID, blkNum, nil } func (h *TDMMsgHandler) Monitor() { h.allRoutineExitWg.Add(1) tick := time.NewTicker(3000 * time.Millisecond) for { select { case <-tick.C: ConsLog.Infof(CONSENSUS, "tick time out") h.ResetMinHeightPeer() //timeout to rest the target min peer witch bloknum biger than me (peer count must +2/3) h.checkBackwardFromBg() case <-h.Quit(): ConsLog.Infof(CONSENSUS, "(msgHandler) sync req stopped") h.allRoutineExitWg.Done() return } } } func (h *TDMMsgHandler) getOtherPeers() ([]uint64, error) { peersInfo := p2pNetwork.GetNeighborAddrs() retPeerEndPointSlice := make([]uint64, 0) for _, peerEndPoint := range peersInfo { retPeerEndPointSlice = append(retPeerEndPointSlice, peerEndPoint.ID) } return retPeerEndPointSlice, nil } func (h *TDMMsgHandler) checkBackwardFromBg() { if h.isSyncStatus.Get() { ConsLog.Warningf(CONSENSUS, "already sync") return } otherVals := p2pNetwork.GetNeighborAddrs() if len(otherVals) == 0 { return } allCount := len(otherVals) + 1 targetCount := (allCount-1)/3 + 1 // f+1 (bft) targetCount = 1 peerCount := len(otherVals) list := make(map[int]struct{}, targetCount) tryTimes := 0 for len(list) < targetCount && peerCount >= targetCount && tryTimes <= 3 { tryTimes++ ConsLog.Debugf(CONSENSUS, "list len %d", len(list)) randomIndex := rand.Intn(len(otherVals)) _, ok := list[randomIndex] if ok { continue } val := otherVals[randomIndex] peerID := val.ID if peerID < 0 { ConsLog.Warningf(CONSENSUS, "not available peer") time.Sleep(1 * time.Second) //choose peer unavailable, sleep 1s to avoid abnormal loop logging } else { err := h.BlockHeightReqFromPeer(peerID, true) if err != nil { ConsLog.Warningf(CONSENSUS, "send blk req msg err [%s]", err.Error()) time.Sleep(1 * time.Second) //"send blk req msg err, sleep 1s to avoid abnormal loop logging } else { list[randomIndex] = struct{}{} } } } } func (h *TDMMsgHandler) BlockHeightReqFromPeer(peeID uint64, isFromBg bool) error { var version uint64 if isFromBg { version = h.heightReq.version } else { version = h.heightReqOutBg.version } heightReq := &com.HeightReq{ Version: version, IsFromBg: isFromBg, } repData, err := json.Marshal(heightReq) if err != nil { return err } tdmMsg := &com.TDMMessage{ Type: com.TDMType_MsgHeightReq, Payload: repData, } tdmMsgSign, err := h.Sign(tdmMsg) if err != nil { return err } tdmData, err := json.Marshal(tdmMsgSign) if err != nil { return fmt.Errorf("marshal err [%s]", err) } conMsg := &consensusType.ConsensusMsg{ Type: int(consensusType.Tendermint), Payload: tdmData, } conData, err := json.Marshal(conMsg) if err != nil { return err } data := &com.PeerMessage{ Sender: h.ID, Msg: conData, IsBroadCast: false, } msg, _ := json.Marshal(data) p2pNetwork.Send(peeID, reqMsg.NewConsMsg(msg), true) ConsLog.Infof(CONSENSUS, "unicast blk height req succ to [%v]", peeID) return nil } func (h *TDMMsgHandler) SendBlockHeightReqToPeer(tdmMsg *com.TDMMessage, peeID uint64) error { if tdmMsg == nil { return fmt.Errorf("tdmMsg is nil") } if peeID < 0 { return fmt.Errorf("peer is nil") } heightReq := &com.HeightReq{} err := json.Unmarshal(tdmMsg.Payload, heightReq) if err != nil { return fmt.Errorf("unmarshal err [%s]", err.Error()) } height, err := ledger.GetBlockHeight() if err != nil { return fmt.Errorf("getblockheight err [%s]", err.Error()) } blk, err := ledger.GetBlock(height - 1) if err != nil { return fmt.Errorf("getblock err [%s]", err.Error()) } if blk == nil { return fmt.Errorf("blk is nil") } respMsg := &com.HeightResp{ BlockNum: height - 1, Header: blk.Header, Version: heightReq.Version, IsFromBg: heightReq.IsFromBg, } respData, err := json.Marshal(respMsg) if err != nil { return err } tdmMsgData := &com.TDMMessage{ Type: com.TDMType_MsgHeihtResp, Payload: respData, } tdmMsgSign, err := h.Sign(tdmMsgData) if err != nil { return err } tdmData, err := json.Marshal(tdmMsgSign) if err != nil { return err } conMsg := &consensusType.ConsensusMsg{ Type: int(consensusType.Tendermint), Payload: tdmData, } conData, err := json.Marshal(conMsg) if err != nil { return err } data := &com.PeerMessage{ Sender: h.ID, Msg: conData, IsBroadCast: false, } msg, _ := json.Marshal(data) p2pNetwork.Send(peeID, reqMsg.NewConsMsg(msg), true) ConsLog.Infof(CONSENSUS, "unicast blk height resp succ to [%v]", peeID) return nil } func (h *TDMMsgHandler) ReciveHeihtResp(tdmMsg *com.TDMMessage, peeID uint64) error { if tdmMsg == nil { return fmt.Errorf("tdmMsg is nil") } heightResp := &com.HeightResp{} err := json.Unmarshal(tdmMsg.Payload, heightResp) if err != nil { return fmt.Errorf("unmarshal err [%s]", err.Error()) } typ, err := h.VerifHeihtRespAll(heightResp) if err != nil { if typ != HEIGHT_ERRO { ConsLog.Warningf(CONSENSUS, "verif failed [%s]", err.Error()) } return nil } if heightResp.IsFromBg { h.heightReq.count++ height := h.Height peerID, blkNum, err := h.GetMinHeightPeer() if err != nil { return fmt.Errorf("getminheightpeer err [%s]", err.Error()) } if heightResp.BlockNum < blkNum || blkNum == 0 { h.SetMinHeightPeer(peeID, heightResp.BlockNum) peerID = peeID blkNum = heightResp.BlockNum } ok := h.checkHeightRespCount() if ok { if height < blkNum+1 { ConsLog.Infof(CONSENSUS, "(sync blk) backward local height [%d] remote height [%d] <-%v", height, heightResp.BlockNum+1, peerID) h.SyncEntrance(heightResp.BlockNum+1, peerID) } } } else { if h.Height < heightResp.BlockNum+1 { ConsLog.Infof(CONSENSUS, "(sync blk) OutBg backward local height [%d] remote height [%d] <-%v", h.Height, heightResp.BlockNum+1, peeID) h.SyncEntrance(heightResp.BlockNum+1, peeID) } } return nil } func (h *TDMMsgHandler) checkHeightRespCount() bool { allCount := len(h.getOtherVals()) + 1 targetCount := (allCount-1)/3 + 1 // f+1 (bft) targetCount = 1 // todo 这里先改成收到一个就先进行同步 ConsLog.Debugf(CONSENSUS, "heightresp now (%d) target (%d)", h.heightReq.count, targetCount) if h.heightReq.count >= targetCount { return true } return false } func (h *TDMMsgHandler) VerifHeihtRespAll(heightResp *com.HeightResp) (int, error) { if heightResp == nil { return PARA_NIL_ERRO, fmt.Errorf("heightResp is nil") } if heightResp.IsFromBg { return h.VerifHeihtResp(heightResp) } else { return h.VerifHeihtRespOutBG(heightResp) } } func (h *TDMMsgHandler) VerifHeihtResp(heightResp *com.HeightResp) (int, error) { if heightResp.Version != h.heightReq.version { return VERSION_ERRO, fmt.Errorf("Resp version (%d) not match version (%d)", heightResp.Version, h.heightReq.version) } if heightResp.BlockNum+1 <= h.Height { return HEIGHT_ERRO, fmt.Errorf("Resp blkheight (%d) <= my blkblkheightnum (%d)", heightResp.BlockNum+1, h.Height) } return NORMAL, nil } func (h *TDMMsgHandler) VerifHeihtRespOutBG(heightResp *com.HeightResp) (int, error) { if heightResp.Version != h.heightReqOutBg.version { return VERSION_ERRO, fmt.Errorf("Resp OutBg version (%d) not match version (%d)", heightResp.Version, h.heightReqOutBg.version) } if heightResp.BlockNum+1 <= h.Height { return HEIGHT_ERRO, fmt.Errorf("Resp OutBg blkheight (%d) <= my blkblkheightnum (%d)", heightResp.BlockNum+1, h.Height) } return NORMAL, nil }
package main import "fmt" func main() { // convertion: []bytes to string fmt.Println(string([]byte{'h', 'e', 'l', 'l', 'o'})) // we'll learn about []bytes soon }
package appengine import ( "github.com/maykonlf/go-api-debugger/handlers" "net/http" ) func init() { http.HandleFunc("/", handlers.MainHandler) //appengine.Main() //port := os.Getenv("PORT") //if port == "" { // port = "8080" //} // //log.Printf("Listening on port %s", port) //log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil)) }