text
stringlengths
11
4.05M
package Common import ( "errors" "github.com/andrewz1/gosmpp/Exception" "github.com/andrewz1/gosmpp/Utils" ) type IByteDataList interface { CreateValue() IByteData } type ByteDataList struct { ByteData Values []IByteData MaxSize int LengthOfSize byte } func NewByteDataList() *ByteDataList { a := &ByteDataList{} a.Construct() return a } func NewByteDataListWithSize(max int, lengthOfSize int) (*ByteDataList, error) { a := NewByteDataList() a.MaxSize = max if lengthOfSize != Utils.SZ_BYTE && lengthOfSize != Utils.SZ_SHORT && lengthOfSize != Utils.SZ_INT { return nil, errors.New("ByteDataList: constructor with size length not valid") } a.LengthOfSize = byte(lengthOfSize) return a, nil } func (c *ByteDataList) Construct() { c.ByteData.Construct() c.SetRealReference(c) c.Values = make([]IByteData, 0) } func (c *ByteDataList) ResetValues() { c.Values = make([]IByteData, 0) } func (c *ByteDataList) SetData(buffer *Utils.ByteBuffer) (err *Exception.Exception) { c.ResetValues() var nrValues int switch int(c.LengthOfSize) { case Utils.SZ_BYTE: v, err := buffer.Read_Byte() if err != nil { return err } nrValues = int(DecodeUnsigned(v)) case Utils.SZ_SHORT: v, err := buffer.Read_Short() if err != nil { return err } nrValues = DecodeUnsignedFromInt16(v) case Utils.SZ_INT: v, err := buffer.Read_Int() if err != nil { return err } nrValues = int(v) } test := c.This.(IByteDataList).CreateValue() if test == nil { return nil } c.Values = make([]IByteData, nrValues) for i := 0; i < nrValues; i++ { c.Values[i] = c.This.(IByteDataList).CreateValue() err := c.Values[i].SetData(buffer) if err != nil { c.ResetValues() return err } } return nil } func (c *ByteDataList) GetCount() int { if c.Values == nil { c.Values = make([]IByteData, 0) } return len(c.Values) } func (c *ByteDataList) GetData() (*Utils.ByteBuffer, *Exception.Exception) { buf := Utils.NewBuffer([]byte{}) numberValues := c.GetCount() switch int(c.LengthOfSize) { case Utils.SZ_BYTE: err := buf.Write_Byte(EncodeUnsigned(uint16(numberValues))) buf.Grow(numberValues * Utils.SZ_BYTE) if err != nil { return nil, err } case Utils.SZ_SHORT: err := buf.Write_Short(EncodeUnsignedFromInt(int(numberValues))) buf.Grow(numberValues * Utils.SZ_SHORT) if err != nil { return nil, err } case Utils.SZ_INT: err := buf.Write_Int(uint32(numberValues)) buf.Grow(numberValues * Utils.SZ_INT) if err != nil { return nil, err } } for _, val := range c.Values { if val == nil { return nil, Exception.ValueNotSetException } tmp, err := val.GetData() if err != nil { return nil, err } err = buf.Write_Buffer(tmp) if err != nil { return nil, err } } return buf, nil } func (c *ByteDataList) AddValue(val IByteData) *Exception.Exception { if c.GetCount() > c.MaxSize { return Exception.TooManyValuesException } if val != nil { c.Values = append(c.Values, val) } return nil } func (c *ByteDataList) GetValue(index int) IByteData { if index < c.GetCount() { return c.Values[index] } return nil }
package api import ( "encoding/json" "fmt" "net/http" "github.com/azzzak/fakecast/store" ) type overview struct { Channel *store.Channel `json:"info"` Podcasts []store.Podcast `json:"podcasts"` } type updateChannel struct { Channel *store.Channel `json:"channel"` OldAlias string `json:"old_alias"` } type updateResponse struct { Cover string `json:"cover"` Error bool `json:"error,omitempty"` } func checkChannels(cfg *Cfg, cs []store.Channel) []store.Channel { ix := 0 for _, c := range cs { if cfg.FS.IsDirExist(c.Alias) { cs[ix] = c ix++ continue } cfg.Store.DeleteChannel(c.ID) } for j := ix; j < len(cs); j++ { cs[j] = store.Channel{} } return cs[:ix] } func checkPodcasts(cfg *Cfg, alias string, ps []store.Podcast) []store.Podcast { ix := 0 for _, p := range ps { if cfg.FS.IsPodcastExist(alias, p.Filename) { ps[ix] = p ix++ continue } cfg.Store.DeletePodcast(p.ID) } for j := ix; j < len(ps); j++ { ps[j] = store.Podcast{} } return ps[:ix] } func (cfg *Cfg) createChannel(w http.ResponseWriter, r *http.Request) error { cid, err := cfg.Store.AddChannel() if err != nil { return err } if err = cfg.FS.CreateDir(cid); err != nil { return err } c, err := cfg.Store.ChannelInfo(cid) if err != nil { return err } c.ID = cid c.Title = fmt.Sprintf("New channel %d", cid) c.Alias = fmt.Sprintf("%d", cid) if err = cfg.Store.UpdateChannel(c); err != nil { return err } encoder := json.NewEncoder(w) if err := encoder.Encode(c); err != nil { return err } return nil } func (cfg *Cfg) list(w http.ResponseWriter, r *http.Request) error { cs, err := cfg.Store.ListChannels() if err != nil { return err } cs = checkChannels(cfg, cs) encoder := json.NewEncoder(w) if err := encoder.Encode(cs); err != nil { return err } return nil } func (cfg *Cfg) overview(w http.ResponseWriter, r *http.Request) error { cid := r.Context().Value(CID).(int64) info, err := cfg.Store.ChannelInfo(cid) if err != nil { return err } info.Host = cfg.Host setCoverURL(cfg, info) ps, err := cfg.Store.ListPodcastsFrom(cid) if err != nil { return err } ps = checkPodcasts(cfg, info.Alias, ps) overview := overview{ Channel: info, Podcasts: ps, } encoder := json.NewEncoder(w) if err := encoder.Encode(overview); err != nil { return err } return nil } func (cfg *Cfg) updateChannel(w http.ResponseWriter, r *http.Request) error { var u *updateChannel var out interface{} decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&u); err != nil { return err } var aliasError bool if u.Channel.Alias != u.OldAlias { err := cfg.FS.RenameDir(u.OldAlias, u.Channel.Alias) if err != nil { u.Channel.Alias = u.OldAlias aliasError = true } } err := cfg.Store.UpdateChannel(u.Channel) if err != nil { return err } if u.Channel.Cover != "" { setCoverURL(cfg, u.Channel) } out = updateResponse{ Cover: u.Channel.Cover, Error: aliasError, } encoder := json.NewEncoder(w) if err := encoder.Encode(out); err != nil { return err } return nil } func (cfg *Cfg) deleteChannel(w http.ResponseWriter, r *http.Request) error { cid := r.Context().Value(CID).(int64) alias, err := cfg.Store.SwapCIDForAlias(cid) if err != nil { return err } if err = cfg.Store.DeleteChannel(cid); err != nil { return err } if err = cfg.FS.RemoveDir(alias); err != nil { return err } return nil }
package main import ( "github.com/astaxie/beego/logs" "encoding/json" "fmt" ) /** LevelEmergency = iota LevelAlert LevelCritical LevelError LevelWarning LevelNotice LevelInformational LevelDebug */ func convertLogLevel(loglevel string) int { switch loglevel { case "debug": return logs.LevelDebug case "trace": return logs.LevelTrace case "info": return logs.LevelInfo } return logs.LevelDebug } func initLogger() { config := make(map[string]interface{}) config["filename"] = appConfig.LogPath config["level"] = convertLogLevel(appConfig.LogLevel) configStr, err := json.Marshal(config) if err != nil { fmt.Println("marshal failed, err:", err) return } logs.SetLogger(logs.AdapterFile, string(configStr)) }
package main import ( "fmt" ) type TemplateContainer struct { ContainerCommon } func (temp TemplateContainer) Build() bool { fmt.Println("Template build", temp.Distribution) return true } func (temp TemplateContainer) Pull() bool { return true } func (temp TemplateContainer) Deploy() bool { return true } func (temp TemplateContainer) Run() bool { return true } func (temp TemplateContainer) Collect() bool { return true } func (temp TemplateContainer) Destroy() bool { return true } func (temp TemplateContainer) Status() string { return "{\"status\": \"ok\"}" }
package worker import ( "bufio" "fmt" "net" "strings" "time" // "regexp" ) type PopResp struct { // Error error Error string Flag string Message string TimeDur float64 } /* func isLikePopResp(s *string) bool { news := strings.TrimRight(*s, "\n") // !!! trim first popregex := regexp.MustCompile(`^(\+OK)|(\-ERR) .+$`) return popregex.MatchString(news) } */ func parseFlagLine(s string) (flag string, message string, err error) { if string(s[0:3]) == "+OK" { flag = string(s[0:3]) message = string(s[3:]) } else if string(s[0:4]) == "-ERR" { flag = string(s[0:4]) message = string(s[4:]) } else { err = fmt.Errorf(s) return } return } func PopPing(addr *string, verbose bool) (result PopResp) { t1 := time.Now() conn, errdial := net.Dial("tcp", *addr) if errdial != nil { result.Error = errdial.Error() return } defer func() { conn.Close() }() welcome, errread := bufio.NewReader(conn).ReadString('\n') // !!! must be '\n' as ReadString() want byte if errread != nil { result.Error = fmt.Sprintf("read line on server response failed: [%s]", errread.Error()) return } welcome = strings.TrimSpace(welcome) flag, message, errparse := parseFlagLine(welcome) if errparse != nil { result.Error = fmt.Sprintf("parse welcome response failed: [%s]", errparse.Error()) return } if flag != "+OK" { result.Error = fmt.Sprintf(welcome) return } t2 := time.Now() duration := t2.Sub(t1).Seconds() result.TimeDur = duration result.Flag = flag if verbose { result.Message = strings.TrimRight(message, "\r\n") } return }
package message import ( "testing" "github.com/airbloc/airbloc-go/account" "github.com/klaytn/klaytn/common" "github.com/klaytn/klaytn/common/hexutil" "github.com/klaytn/klaytn/crypto" "github.com/perlin-network/noise" "github.com/perlin-network/noise/payload" uuid "github.com/satori/go.uuid" . "github.com/smartystreets/goconvey/convey" ) var _ Message = (*TestResponse)(nil) type TestResponse struct { MessageId uuid.UUID Sign hexutil.Bytes } func (resp TestResponse) Read(payload.Reader) (noise.Message, error) { return nil, nil } func (resp TestResponse) Write() []byte { return nil } func (resp TestResponse) ID() uuid.UUID { return resp.MessageId } func (resp *TestResponse) SetID(id uuid.UUID) { resp.MessageId = id } func (resp TestResponse) Signature() hexutil.Bytes { return resp.Sign } func (resp *TestResponse) SetSignature(sign hexutil.Bytes) { resp.Sign = sign } func TestResponseMessageUtils(t *testing.T) { Convey("Test Response Message Utils", t, func() { key, err := crypto.GenerateKey() So(err, ShouldBeNil) acc := account.NewKeyedAccount(key) Convey("#SignResponseMessage", func() { Convey("Should done correctly", func() { msg := &TestResponse{MessageId: uuid.NewV4()} err = SignResponseMessage(msg, acc) So(err, ShouldBeNil) So(msg.Sign, ShouldNotEqual, (hexutil.Bytes)(nil)) }) Convey("Should fail if response is nil", func() { err = SignResponseMessage(nil, acc) So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "nil response") }) Convey("Should fail if response.ID is empty", func() { err = SignResponseMessage(&TestResponse{}, acc) So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "empty uuid") }) }) Convey("#VerifyResponseMessage", func() { Convey("Should done correctly", func() { msg := &TestResponse{MessageId: uuid.NewV4()} var id [32]byte copy(id[:], msg.ID().Bytes()) sig, err := crypto.Sign(id[:], key) So(err, ShouldBeNil) msg.SetSignature(sig) ok, err := VerifyResponseMessage(msg, acc.Address()) So(ok, ShouldBeTrue) So(err, ShouldBeNil) }) Convey("Should fail if response is nil", func() { ok, err := VerifyResponseMessage(nil, common.Address{}) So(ok, ShouldBeFalse) So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "nil response") }) Convey("Should fail if response.ID is empty", func() { ok, err := VerifyResponseMessage(&TestResponse{}, common.Address{}) So(ok, ShouldBeFalse) So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "empty uuid") }) Convey("Should fail when ecrecover fails", func() { ok, err := VerifyResponseMessage(&TestResponse{ MessageId: uuid.NewV4(), Sign: []byte{0xde, 0xed, 0xbe, 0xef, 0xde, 0xed, 0xbe, 0xef}, }, common.Address{}) So(ok, ShouldBeFalse) So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "failed to recover signer's public key from signature") }) }) }) }
package app import ( "net/http" "github.com/superbkibbles/bookstore_items-api/src/controllers" ) func mapUrls() { // Ping controller router.HandleFunc("/ping", controllers.PingController.Ping) // Item controller router.HandleFunc("/items", controllers.ItemController.Create).Methods(http.MethodPost) router.HandleFunc("/items/{id}", controllers.ItemController.Get).Methods(http.MethodGet) router.HandleFunc("/items/search", controllers.ItemController.Search).Methods(http.MethodPost) }
package aliyun import ( "errors" "path" "strconv" "github.com/JointFaaS/Manager/env" "github.com/aliyun/fc-go-sdk" ) var service = "jointfaas" // CreateFunction : // sourceURL can be created by UploadSourceCode func (m *Manager) CreateFunction(funcName string, dir string, e env.Env, memoryS string, timeoutS string) (error) { var err error memorySizeI, err := strconv.Atoi(memoryS) memorySize := int32(memorySizeI) if err != nil { return err } timeoutI, err := strconv.Atoi(timeoutS) timeout := int32(timeoutI) if err != nil { return err } if e == env.PYTHON3 { err = m.createPython3Function(path.Join(dir, "code")) }else if e == env.JAVA8 { err = m.createJava8Function(path.Join(dir, "code")) } else { return errors.New("Not support Env") } if err != nil { return err } aliyunZip := path.Join(dir, "aliyun.zip") err = compressDir(path.Join(dir, "code"), aliyunZip) if err != nil { return err } err = m.aliCodeBucket.PutObjectFromFile(funcName, aliyunZip) if err != nil { return err } runtime, handler, initializer := envToAliyunEnv(e) _, err = m.fcClient.CreateFunction(&fc.CreateFunctionInput{ ServiceName: &service, FunctionCreateObject: fc.FunctionCreateObject{ FunctionName: &funcName, Runtime: &runtime, Initializer: &initializer, Handler: &handler, Code: fc.NewCode().WithOSSBucketName(m.aliCodeBucket.BucketName).WithOSSObjectName(funcName), MemorySize: &memorySize, Timeout: &timeout, }, }) if err != nil { return err } return nil } func envToAliyunEnv(e env.Env) (string, string, string) { if e == env.PYTHON3 { return "python3", "jointfaas.handler", "" } else if e == env.JAVA8 { return "java8", "jointfaas.AliIndex::handleRequest", "jointfaas.AliIndex::initialize" } return "", "", "" }
package public import ( "context" "fmt" "tpay_backend/merchantapi/internal/common" "tpay_backend/model" "tpay_backend/merchantapi/internal/svc" "tpay_backend/merchantapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type PlatformBankCardListLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewPlatformBankCardListLogic(ctx context.Context, svcCtx *svc.ServiceContext) PlatformBankCardListLogic { return PlatformBankCardListLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *PlatformBankCardListLogic) PlatformBankCardList(merchantId int64, req types.PlatformBankCardListReq) (*types.PlatformBankCardListReply, error) { merchant, err := model.NewMerchantModel(l.svcCtx.DbEngine).FindOneById(merchantId) if err != nil { l.Errorf("查询商户[%v]信息失败, err=%v", merchantId, err) return nil, common.NewCodeError(common.SysDBGet) } q := model.FindPlatformBankCardList{ Page: req.Page, PageSize: req.PageSize, Currency: merchant.Currency, Status: model.PlatformBankCardEnable, } dataList, total, err := model.NewPlatformBankCardModel(l.svcCtx.DbEngine).FindList(q) if err != nil { l.Errorf("查询平台收款卡列表失败,err=%v", err) return nil, common.NewCodeError(common.SysDBGet) } imageUrl, err := model.NewGlobalConfigModel(l.svcCtx.DbEngine).FindValueByKey(model.ConfigImageBaseUrl) if err != nil { l.Errorf("查询图片域名地址失败[%v], err=%v", model.ConfigImageBaseUrl, err) return nil, common.NewCodeError(common.SysDBGet) } var list []types.PlatformBankCardList for _, data := range dataList { d := types.PlatformBankCardList{ Id: data.Id, BankName: data.BankName, // 银行名称 AccountName: data.AccountName, // 开户名 CardNumber: data.CardNumber, // 银行卡号 BranchName: data.BranchName, // 支行名称 Currency: data.Currency, // 币种 MaxAmount: data.MaxAmount, // 最大收款额度 QrCode: data.QrCode, // 收款二维码 } if d.QrCode != "" { d.QrCode = fmt.Sprintf("%s/%s", imageUrl, data.QrCode) } list = append(list, d) } return &types.PlatformBankCardListReply{ Total: total, List: list, }, nil }
package main import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "os" "regexp" "strings" "sync" "time" "github.com/kyf/postwx" ) func fetchWxMedia(fpath string) (string, error) { data := make(url.Values) data.Set("fpath", fpath) dir, err := uploadDir(UPLOAD_PATH) if err != nil { return "", err } fp := fmt.Sprintf("%s/%s", dir, fmt.Sprintf("%v", time.Now().UnixNano())) fullpath, err := postwx.GetMedia(fpath, fp) if err != nil { return "", err } newpath := strings.Replace(string(fullpath), UPLOAD_PATH, "", -1) return newpath, nil } func Pathinfo(file string) (map[string]string, error) { if len(file) == 0 { return nil, errors.New("file path is empty!") } var result map[string]string = make(map[string]string) info := strings.Split(file, "/") info_len := len(info) if info_len == 1 { result["basepath"] = "" result["filename"] = file } else { result["filename"] = info[info_len-1] result["basepath"] = strings.Replace(file, result["filename"], "", -1) } name := strings.Split(result["filename"], ".") result["extension"] = "" name_len := len(name) if name_len > 1 { result["extension"] = name[name_len-1] } return result, nil } func IsImage(file string) bool { pathinfo, err := Pathinfo(file) if err != nil { return false } exts := []string{"jpeg", "jpg", "png", "gif"} extension := strings.ToLower(pathinfo["extension"]) for _, e := range exts { if strings.EqualFold(extension, e) { return true } } return false } func cbResponseJson(writer io.Writer, status bool, msg, cb string, data ...interface{}) { if len(msg) == 0 { msg = "success" } result := map[string]interface{}{ "status": status, "msg": msg, } if len(data) > 0 { result["data"] = data[0] } re, _ := json.Marshal(result) writer.Write([]byte(fmt.Sprintf("<script type='text/javascript'>%s(%s)</script>", cb, string(re)))) } func responseJson(writer io.Writer, status bool, msg string, data ...interface{}) { if len(msg) == 0 { msg = "success" } result := map[string]interface{}{ "status": status, "msg": msg, } if len(data) > 0 { result["data"] = data[0] } re, _ := json.Marshal(result) writer.Write(re) } func fetchTop(admin_name string) ([]byte, error) { top, err := fetchFile("./tpl/top.html") if err != nil { return nil, err } _top := strings.Replace(string(top), "{admin_name}", admin_name, -1) return []byte(_top), nil } func fetchLeft() ([]byte, error) { return fetchFile("./tpl/left.html") } func fetchFile(path string) ([]byte, error) { fp, err := os.Open(path) if err != nil { return nil, err } defer fp.Close() content, err := ioutil.ReadAll(fp) if err != nil { return nil, err } return content, nil } func StringSliceContains(it string, its []string) bool { for _, item := range its { if strings.EqualFold(item, it) { return true } } return false } func getAccessToken() (string, error) { res, err := http.Get("http://m.6renyou.com/weixin_service/getAccessToken?account_type=1") if err != nil { return "", err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return "", err } return string(body), nil } func postWeb(openid, message, msgType string) error { data := make(url.Values) data.Set("content", message) data.Set("openid", openid) data.Set("msgType", msgType) res, err := http.PostForm("http://localhost:6067/receive", data) if err != nil { return err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return err } response := new(struct { Status bool `json:"status"` Message string `json:"msg"` }) err = json.Unmarshal(body, response) if err != nil { return err } if !response.Status { return errors.New(response.Message) } return nil } type CacheAutoReplyStruct struct { locker sync.RWMutex ar []AutoReply far []FirstAutoReply } var ( CacheAutoReply = &CacheAutoReplyStruct{ar: make([]AutoReply, 0)} ) func (car *CacheAutoReplyStruct) update(mgo *Mongo, logger *log.Logger) { car.locker.RLock() defer car.locker.RUnlock() ar, err := AutoReplyList(mgo) if err != nil { logger.Printf("AutoReplyList err:%v", err) return } far, err := FirstAutoReplyList(mgo) if err != nil { logger.Printf("FirstAutoReplyList err:%v", err) return } car.ar = ar car.far = far } func (car *CacheAutoReplyStruct) arlist() []AutoReply { return car.ar } func (car *CacheAutoReplyStruct) farlist() []FirstAutoReply { return car.far } func autoReply(openid string, source int, logger *log.Logger) { ar := CacheAutoReply.arlist() now := time.Now() year, month, day, location, st := now.Year(), now.Month(), now.Day(), now.Location(), now.Unix() for _, it := range ar { if it.Source > 0 && it.Source != source { continue } from := time.Date(year, month, day, it.FromHour, it.FromMinute, 0, 0, location) to := time.Date(year, month, day, it.ToHour, it.ToMinute, 0, 0, location) if st >= from.Unix() && st <= to.Unix() { var posterr error switch source { case MSG_SOURCE_WX: _, posterr = postwx.PostText(openid, it.Content) case MSG_SOURCE_PC: posterr = postWeb(openid, it.Content, fmt.Sprintf("%v", MSG_TYPE_TEXT)) } if posterr != nil { logger.Printf("posterr is %v", posterr) } else { msg := Message{Fromtype: MSG_FROM_TYPE_OP, Openid: openid, Created: time.Now().Unix(), Content: it.Content, MsgType: MSG_TYPE_TEXT, Opid: SYSTEM} msg.Source = source mgo := NewMongoClient() err := mgo.Connect() if err != nil { logger.Printf("mgo.Connect err:%v", err) } else { defer mgo.Close() err = storeMessage(msg, mgo) if err != nil { logger.Printf("storeMessage err:%v", err) } } } } } } func welcome(openid string) error { far := CacheAutoReply.farlist() if far == nil || len(far) == 0 { return nil } posterr := postWeb(openid, far[0].Content, fmt.Sprintf("%v", MSG_TYPE_TEXT)) if posterr != nil { return posterr } else { msg := Message{Fromtype: MSG_FROM_TYPE_OP, Openid: openid, Created: time.Now().Unix(), Content: far[0].Content, MsgType: MSG_TYPE_TEXT, Opid: SYSTEM} msg.Source = MSG_SOURCE_PC mgo := NewMongoClient() err := mgo.Connect() if err != nil { return err } else { defer mgo.Close() err = storeMessage(msg, mgo) if err != nil { return err } } } return nil } func filterHTML(content string) ([]byte, error) { reg, err := regexp.Compile("<[^>]+>") if err != nil { return nil, err } result := reg.ReplaceAll([]byte(content), []byte("")) return result, nil }
package config import ( "database/sql" "fmt" "log" "os" _ "github.com/go-sql-driver/mysql" "github.com/joho/godotenv" ) func InitDatabase() *sql.DB { db := db() return db } func db() *sql.DB { err := godotenv.Load() if err != nil { log.Println(err) } user := os.Getenv("DB_USER") password := os.Getenv("DB_PASSWORD") _db := os.Getenv("DB") db, _ := sql.Open("mysql", user+":"+password+"@tcp(127.0.0.1:3306)/"+_db) err = db.Ping() if err != nil { panic(err) } fmt.Println("Database opened.") return db }
package gateway import ( "context" "github.com/google/go-github/github" ) // PullRequestReviewState indicates whether a PR has been accepted or not. type PullRequestReviewState string const ( // PullRequestApproved indicates that a pull request was accepted. PullRequestApproved PullRequestReviewState = "APPROVED" // PullRequestChangesRequested indicates that changes were requested for a // pull request. PullRequestChangesRequested PullRequestReviewState = "CHANGES_REQUESTED" ) // PullRequestReview is a review of a pull request. type PullRequestReview struct { // User who did the review. User string // Whether they approved or requested changes. Status PullRequestReviewState } // BuildState indicates whether a build succeeded, failed or is pending. type BuildState string // All possible BuildStates. const ( BuildError BuildState = "error" BuildFailure BuildState = "failure" BuildPending BuildState = "pending" BuildSuccess BuildState = "success" ) //BuildContextStatus is the status of a specific build context. type BuildContextStatus struct { Name string Message string State BuildState } // BuildStatus indicates the build status of a ref. type BuildStatus struct { State BuildState Statuses []*BuildContextStatus } // GitHub is a gateway that provides access to GitHub operations on a specific // repository. type GitHub interface { // Checks if the given pull request branch is owned by the same // repository. IsOwned(ctx context.Context, br *github.PullRequestBranch) bool // Lists reviews for a pull request. ListPullRequestReviews(ctx context.Context, number int) ([]*PullRequestReview, error) // Get the build status of a specific ref. GetBuildStatus(ctx context.Context, ref string) (*BuildStatus, error) // List pull requests on this repository with the given head. If owner is // empty, the current repository should be used. ListPullRequestsByHead(ctx context.Context, owner, branch string) ([]*github.PullRequest, error) // List pull requests on this repository with the given merge base. ListPullRequestsByBase(ctx context.Context, branch string) ([]*github.PullRequest, error) // Retrieve the raw patch for the given pull request. GetPullRequestPatch(ctx context.Context, number int) (string, error) // Change the merge base for the given pull request. SetPullRequestBase(ctx context.Context, number int, base string) error // Merges the given pull request. SquashPullRequest(context.Context, *github.PullRequest) error // TODO: SquashPullRequest should accept an explicit SquashRequest // Delete the given branch. DeleteBranch(ctx context.Context, name string) error }
package main import ( "fmt" "time" ) var nums = []byte{'1', '2', '3', '4', '5', '6', '7', '8', '9'} func solveSudoku(board [][]byte) { solve(board, 0, 0) } func solve(board [][]byte, i, j int) bool { if i == 9 { fmt.Println("====") return true } if j == 9 { fmt.Println("====") return solve(board, i + 1, 0) } if board[i][j] == '.' { for _, v := range nums { board[i][j] = v if isValid(board, i, j) { if solve(board, i, j+1) { return true } fmt.Println(board) time.Sleep(time.Second) } } board[i][j] = '.' } else { return solve(board, i, j+1) } fmt.Println("====") return false } func isValid(board [][]byte, i, j int) bool { for row := 0; row < 9; row ++ { if board[i][j] == board[row][j] { return false } } for col := 0; col < 9; col ++ { if board[i][j] == board[i][col] { return false } } x := i / 3 * 3 y := j / 3 * 3 for row := x; row < x + 3; row ++ { for col := y; col < y + 3; col ++ { if board[i][j] == board[row][col] { return false } } } return true } func modify(b []byte) { b[0] = 'z' } func main() { d := [][]byte{[]byte{'5','3','.','.','7','.','.','.','.'},{'6','.','.','1','9','5','.','.','.'},{'.','9','8','.','.','.','.','6','.'},{'8','.','.','.','6','.','.','.','3'},{'4','.','.','8','.','3','.','.','1'},{'7','.','.','.','2','.','.','.','6'},{'.','6','.','.','.','.','2','8','.'},{'.','.','.','4','1','9','.','.','5'},{'.','.','.','.','8','.','.','7','9'}} fmt.Println(d) solveSudoku(d) modify(nums) fmt.Println(nums) }
package main import ( "sort" "github.com/heartchord/jxonline/gamestruct" "github.com/lxn/walk" ) // RoleSkillDataItem : type RoleSkillDataItem struct { DataModelItemBase SkillID string // 数据名称 SkillLv string // 数据内容 SkillExp string // 数据说明 } // RoleSkillDataModel : type RoleSkillDataModel struct { DataModelBase items []*RoleSkillDataItem } // NewRoleSkillDataModel : func NewRoleSkillDataModel() *RoleSkillDataModel { var err error m := new(RoleSkillDataModel) m.itemIcon, err = walk.NewIconFromFile("../../gameresource/img/right-arrow2.ico") if err != nil { } m.ResetRows(nil) return m } // RowCount : func (m *RoleSkillDataModel) RowCount() int { return len(m.items) } // Value : func (m *RoleSkillDataModel) Value(row, col int) interface{} { item := m.items[row] switch col { case 0: return item.Index case 1: return item.SkillID case 2: return item.SkillLv case 3: return item.SkillExp } panic("unexpected col") } // Checked : func (m *RoleSkillDataModel) Checked(row int) bool { return m.items[row].checked } // SetChecked : func (m *RoleSkillDataModel) SetChecked(row int, checked bool) error { m.items[row].checked = checked return nil } // Sort : func (m *RoleSkillDataModel) Sort(col int, order walk.SortOrder) error { m.sortColumn, m.sortOrder = col, order sort.Stable(m) return m.SorterBase.Sort(col, order) } // Len : func (m *RoleSkillDataModel) Len() int { return len(m.items) } // Less : 数据排序小于运算符 func (m *RoleSkillDataModel) Less(i int, j int) bool { a, b := m.items[i], m.items[j] f := func(ls bool) bool { if m.sortOrder == walk.SortAscending { // 升序 return ls } // 降序 return !ls } switch m.sortColumn { case 0: return f(a.Index < b.Index) case 1: return f(a.SkillID < b.SkillID) case 2: return f(a.SkillLv < b.SkillLv) case 3: return f(a.SkillExp < b.SkillExp) } panic("Unreachable Column Index!") } // Swap : 数据交换 func (m *RoleSkillDataModel) Swap(i, j int) { m.items[i], m.items[j] = m.items[j], m.items[i] } // Image : 获取数据Item图标 func (m *RoleSkillDataModel) Image(row int) interface{} { return m.itemIcon } // ResetRows : func (m *RoleSkillDataModel) ResetRows(data []gamestruct.SkillData) { if data == nil { return } dataCount := len(data) if dataCount <= 0 { return } m.items = make([]*RoleSkillDataItem, dataCount) for i := 0; i < dataCount; i++ { fieldStrings := getStructFieldStrings(data[i]) m.items[i] = &RoleSkillDataItem{} m.items[i].Index = i m.items[i].SkillID = fieldStrings[0] m.items[i].SkillLv = fieldStrings[1] m.items[i].SkillExp = fieldStrings[2] } // Notify TableView and other interested parties about the reset. m.PublishRowsReset() m.Sort(m.sortColumn, m.sortOrder) } // SwitchRowCheckedState : func (m *RoleSkillDataModel) SwitchRowCheckedState(idx int) { checked := m.Checked(idx) m.SetChecked(idx, !checked) m.PublishRowChanged(idx) } // Items : func (m *RoleSkillDataModel) Items() []*RoleSkillDataItem { return m.items }
/* Using one single statement, numerically assign the IEEE 754 : +INF to variable a — inf also acceptable -INF to variable b +NaN to variable c — a sign-less nan being displayed is acceptable as long as the code demonstrates how it arrives at a positive nan -NaN to variable d — a sign-less nan being displayed is acceptable as long as the code demonstrates how it arrives at a negative nan The assignment must be without using string concat The assignment must be interconnected, ie. — the assignment of any 3 out of 4 must be via any combo of each other's value(s) instead of performing 4 independent assigns into a 4-way tuple casing is irrelevant. Single v. double v. quadruple floating point precision is also irrelevant. Full spellings of infinity | not-a-number, or their hex representations (e.g. FFF0000000000000 for -INF), are also acceptable Shortest code wins. — reference solution exists Good Luck Everyone */ package main import ( "fmt" "math" ) func main() { a, b, c, d := math.Inf(1), math.Inf(-1), math.NaN(), -math.NaN() fmt.Println(a, b, c, d) }
package main import ( "fmt" "io/ioutil" "log" "os" ) func main() { logFile := os.Getenv("LOGFILE") message := "Writing to " + logFile + " from setup" err := ioutil.WriteFile(logFile, []byte(message), 0644) if err != nil { log.Fatal(err) } fmt.Printf("First message: %s", message) }
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" ) type Configuration struct { Address string ReadTimeout int64 WriteTimeout int64 Static string } var config Configuration var logger *log.Logger func p(a ...interface{}) { fmt.Println(a) } func init() { file, err := os.Open("etc/config.json") defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { panic("加载配置文件失败") } config = Configuration{} err = json.Unmarshal(data, &config) if err != nil { panic("解析配置文件失败") } } // 版本 func version() string { return "0.8" //基础 //外域访问 //增加Token //base64解密 //base64图片上传 //静态文件服务 //每天更新机制 //推荐算法 }
package register import ( "io/ioutil" "testing" "github.com/stretchr/testify/require" ) func TestFindMax(t *testing.T) { assert := require.New(t) m, h := findMax(` b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10`) assert.Equal(1, m) assert.Equal(10, h) } func TestSolveFindMax(t *testing.T) { assert := require.New(t) data, _ := ioutil.ReadFile("./input.txt") m, h := findMax(string(data)) assert.Equal(6061, m) assert.Equal(0, h) }
package simplestake import ( "testing" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" ) func TestBondMsgValidation(t *testing.T) { privKey := ed25519.GenPrivKey() cases := []struct { valid bool msgBond MsgBond }{ {true, NewMsgBond(sdk.AccAddress{}, sdk.NewInt64Coin("mycoin", 5), privKey.PubKey())}, {false, NewMsgBond(sdk.AccAddress{}, sdk.NewInt64Coin("mycoin", 0), privKey.PubKey())}, } for i, tc := range cases { err := tc.msgBond.ValidateBasic() if tc.valid { require.Nil(t, err, "%d: %+v", i, err) } else { require.NotNil(t, err, "%d", i) } } }
// +build linux package fscommon import ( "io/ioutil" "os" "syscall" securejoin "github.com/cyphar/filepath-securejoin" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) func WriteFile(dir, file, data string) error { if dir == "" { return errors.Errorf("no directory specified for %s", file) } path, err := securejoin.SecureJoin(dir, file) if err != nil { return err } if err := retryingWriteFile(path, []byte(data), 0700); err != nil { return errors.Wrapf(err, "failed to write %q to %q", data, path) } return nil } func ReadFile(dir, file string) (string, error) { if dir == "" { return "", errors.Errorf("no directory specified for %s", file) } path, err := securejoin.SecureJoin(dir, file) if err != nil { return "", err } data, err := ioutil.ReadFile(path) return string(data), err } func retryingWriteFile(filename string, data []byte, perm os.FileMode) error { for { err := ioutil.WriteFile(filename, data, perm) if isInterruptedWriteFile(err) { logrus.Infof("interrupted while writing %s to %s", string(data), filename) continue } return err } } func isInterruptedWriteFile(err error) bool { if patherr, ok := err.(*os.PathError); ok { errno, ok2 := patherr.Err.(syscall.Errno) if ok2 && errno == syscall.EINTR { return true } } return false }
package tstune import ( "fmt" "io" "os" "path" "path/filepath" "strings" "time" ) const ( backupFilePrefix = "timescaledb_tune.backup" backupDateFmt = "200601021504" errBackupNotCreatedFmt = "could not create backup at %s: %v" ) // allows us to substitute mock versions in tests var filepathGlobFn = filepath.Glob var osCreateFn = func(path string) (io.WriteCloser, error) { return os.Create(path) } // backup writes the conf file state to the system's temporary directory // with a well known name format so it can potentially be restored. func backup(cfs *configFileState) (string, error) { backupName := backupFilePrefix + time.Now().Format(backupDateFmt) backupPath := path.Join(os.TempDir(), backupName) bf, err := osCreateFn(backupPath) if err != nil { return backupPath, fmt.Errorf(errBackupNotCreatedFmt, backupPath, err) } _, err = cfs.WriteTo(bf) return backupPath, err } // getBackups returns a list of files that match timescaledb-tune's backup // filename format. func getBackups() ([]string, error) { backupPattern := path.Join(os.TempDir(), backupFilePrefix+"*") files, err := filepathGlobFn(backupPattern) if err != nil { return nil, err } ret := []string{} stripPrefix := path.Join(os.TempDir(), backupFilePrefix) for _, f := range files { datePart := strings.Replace(f, stripPrefix, "", -1) _, err := time.Parse(backupDateFmt, datePart) if err != nil { continue } ret = append(ret, f) } return ret, nil } type restorer interface { Restore(string, string) error } type fsRestorer struct{} func (r *fsRestorer) Restore(backupPath, confPath string) error { backupFile, err := os.Open(backupPath) if err != nil { return err } defer backupFile.Close() backupCFS, err := getConfigFileState(backupFile) if err != nil { return err } confFile, err := os.OpenFile(confPath, os.O_WRONLY, 0644) if err != nil { return err } defer confFile.Close() _, err = backupCFS.WriteTo(confFile) if err != nil { return err } return nil }
package bench import ( "bytes" stdjson "encoding/json" "fmt" "testing" wish "github.com/warpfork/go-wish" "github.com/polydawn/refmt" ) func exerciseMarshaller( b *testing.B, subj refmt.Marshaller, buf *bytes.Buffer, val interface{}, expect []byte, ) { var err error for i := 0; i < b.N; i++ { buf.Reset() err = subj.Marshal(val) } if err != nil { panic(err) } if !bytes.Equal(buf.Bytes(), expect) { panic(fmt.Errorf("result \"% x\"\nmust equal \"% x\"", buf.Bytes(), expect)) } } func exerciseStdlibJsonMarshaller( b *testing.B, val interface{}, expect []byte, ) { var err error var buf bytes.Buffer subj := stdjson.NewEncoder(&buf) for i := 0; i < b.N; i++ { buf.Reset() err = subj.Encode(val) } if err != nil { panic(err) } buf.Truncate(buf.Len() - 1) // Stdlib suffixes a linebreak. if !bytes.Equal(buf.Bytes(), expect) { panic(fmt.Errorf("result \"% x\"\nmust equal \"% x\"", buf.Bytes(), expect)) } } func exerciseUnmarshaller( b *testing.B, subj refmt.Unmarshaller, buf *bytes.Buffer, src []byte, blankFn func() interface{}, expect interface{}, ) { var err error var targ interface{} for i := 0; i < b.N; i++ { targ = blankFn() buf.Reset() buf.Write(src) err = subj.Unmarshal(targ) } if err != nil { panic(err) } if detail, pass := wish.ShouldEqual(targ, expect); !pass { panic(fmt.Errorf("difference:\n%s", detail)) } } func exerciseStdlibJsonUnmarshaller( b *testing.B, src []byte, blankFn func() interface{}, expect interface{}, ) { var err error var targ interface{} for i := 0; i < b.N; i++ { targ = blankFn() subj := stdjson.NewDecoder(bytes.NewBuffer(src)) err = subj.Decode(targ) } if err != nil { panic(err) } if detail, pass := wish.ShouldEqual(fixFloatsToInts(targ), fixFloatsToInts(expect)); !pass { panic(fmt.Errorf("difference:\n%s", detail)) } } // This function normalizes floats to ints, and we use it so the same fixtures // work for CBOR and refmt-JSON and stdlib-JSON -- the latter of which only // produces floats when unmarshalling into an empty interface. // // The whole function is fairly absurd, but so is refusing to admit ints exist. func fixFloatsToInts(in interface{}) interface{} { switch in2 := in.(type) { case *map[string]interface{}: return fixFloatsToInts(*in2) case map[string]interface{}: out := make(map[string]interface{}, len(in2)) for k, v := range in2 { out[k] = fixFloatsToInts(v) } return out case []interface{}: out := make([]interface{}, len(in2)) for i, v := range in2 { out[i] = fixFloatsToInts(v) } return out case float64: return int(in2) default: return in } }
// Copyright 2018 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 lockstats import ( "context" "github.com/pingcap/errors" "github.com/pingcap/tidb/domain" "github.com/pingcap/tidb/executor/internal/exec" "github.com/pingcap/tidb/parser/ast" "github.com/pingcap/tidb/util/chunk" ) var _ exec.Executor = &UnlockExec{} // UnlockExec represents a unlock statistic executor. type UnlockExec struct { exec.BaseExecutor Tables []*ast.TableName } // Next implements the Executor Next interface. func (e *UnlockExec) Next(context.Context, *chunk.Chunk) error { do := domain.GetDomain(e.Ctx()) h := do.StatsHandle() if h == nil { return errors.New("Unlock Stats: handle is nil") } if len(e.Tables) == 0 { return errors.New("Unlock Stats: table should not empty ") } is := do.InfoSchema() tids, pids, err := populateTableAndPartitionIDs(e.Tables, is) if err != nil { return err } msg, err := h.RemoveLockedTables(tids, pids, e.Tables) if err != nil { return err } if msg != "" { e.Ctx().GetSessionVars().StmtCtx.AppendWarning(errors.New(msg)) } return nil } // Close implements the Executor Close interface. func (*UnlockExec) Close() error { return nil } // Open implements the Executor Open interface. func (*UnlockExec) Open(context.Context) error { return nil }
package core // global variables in this case are ok since: // 1 - the package handles only one dataset at a time // 2 - most of the functions use the images manager const ( cosMinAngle = 0.9396926207859084 //math.Cos(20 * math.Pi / 180) cosMaxAngle = 0.5 //math.Cos(60 * math.Pi / 180) featMaxDist = 2.0 patchGridSize = 5 cellSize = 2 ) var ( imgsManager *ImagesManager )
package plug import ( "fmt" ) type Plug interface { Connect() error Loop() Changes() <-chan Change Send(string) error } type Change struct { User string Channel string Server string Data string } func (c Change) String() string { return fmt.Sprintf( "%s%s@%s> %s", c.User, c.Channel, c.Server, c.Data, ) }
package g2util import ( "encoding/json" "reflect" ) // MergeBean ... // @Description: merge struct's point, merge src to dst // @param dst // @param src func MergeBean(dst interface{}, src Map) (err error) { dv1 := reflect.ValueOf(dst) if dv1.Kind() != reflect.Ptr { panic("dst needs pointer kind") } dstBs, err := json.Marshal(dst) if err != nil { return } tmp1 := make(map[string]interface{}) if err = json.Unmarshal(dstBs, &tmp1); err != nil { return } for k, v := range src { tmp1[k] = v } dstBs, err = json.Marshal(tmp1) if err != nil { return } err = json.Unmarshal(dstBs, dst) return }
package main import ( "net" "errors" "strings" "io/ioutil" "encoding/pem" "crypto" "crypto/tls" "crypto/x509" "crypto/rsa" "crypto/ecdsa" "flag" "log" "net/http" "fmt" ) var url = flag.String("url", "https://127.0.0.1:8443", "the url to get") var certFile = flag.String("certFile", "cert.pem", "the cert for client auth") var keyFile = flag.String("keyFile", "key.pem", "the key for client auth") func handler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprintln(w, "Your conn state is: ", req.TLS); fmt.Fprintln(w, "Your client cert is: ", req.TLS.PeerCertificates); } func loadX509KeyPair(certFile, keyFile string) (cert tls.Certificate, err error) { certPEMBlock, err := ioutil.ReadFile(certFile) if err != nil { return } keyPEMBlock, err := ioutil.ReadFile(keyFile) if err != nil { return } return X509KeyPair(certPEMBlock, keyPEMBlock, []byte("password")) } func X509KeyPair(certPEMBlock, keyPEMBlock, pw []byte) (cert tls.Certificate, err error) { var certDERBlock *pem.Block for { certDERBlock, certPEMBlock = pem.Decode(certPEMBlock) if certDERBlock == nil { break } if certDERBlock.Type == "CERTIFICATE" { cert.Certificate = append(cert.Certificate, certDERBlock.Bytes) } } if len(cert.Certificate) == 0 { err = errors.New("crypto/tls: failed to parse certificate PEM data") return } var keyDERBlock *pem.Block for { keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) if keyDERBlock == nil { err = errors.New("crypto/tls: failed to parse key PEM data") return } if x509.IsEncryptedPEMBlock(keyDERBlock) { out, err2 := x509.DecryptPEMBlock(keyDERBlock, pw) if err2 != nil { err = err2 return } keyDERBlock.Bytes = out break } if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") { break } } cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes) if err != nil { return } // We don't need to parse the public key for TLS, but we so do anyway // to check that it looks sane and matches the private key. x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { return } switch pub := x509Cert.PublicKey.(type) { case *rsa.PublicKey: priv, ok := cert.PrivateKey.(*rsa.PrivateKey) if !ok { err = errors.New("crypto/tls: private key type does not match public key type") return } if pub.N.Cmp(priv.N) != 0 { err = errors.New("crypto/tls: private key does not match public key") return } case *ecdsa.PublicKey: priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey) if !ok { err = errors.New("crypto/tls: private key type does not match public key type") return } if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 { err = errors.New("crypto/tls: private key does not match public key") return } default: err = errors.New("crypto/tls: unknown public key algorithm") return } return } // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { return key, nil } if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { switch key := key.(type) { case *rsa.PrivateKey, *ecdsa.PrivateKey: return key, nil default: return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping") } } if key, err := x509.ParseECPrivateKey(der); err == nil { return key, nil } return nil, errors.New("crypto/tls: failed to parse private key") } func main() { flag.Parse() cert, err := loadX509KeyPair(*certFile, *keyFile) if err != nil { log.Fatal(err) } tlscfg := &tls.Config{ Certificates: []tls.Certificate{cert}, } srv := &http.Server{Addr: ":8443", Handler: nil} l, err := net.Listen("tcp", srv.Addr) if err != nil { log.Fatal(err) } tl := tls.NewListener(l, tlscfg) http.HandleFunc("/", handler) srv.Serve(tl) }
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 main import ( "fmt" "os" "os/signal" "runtime" "syscall" "github.com/Tencent/bk-bcs/bcs-common/common" "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/app" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/options" v1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/pkg/ipscheduler/v1" v2 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/pkg/ipscheduler/v2" v3 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/pkg/ipscheduler/v3" ) const ( ipSchedulerV1Type = "IpSchedulerV1" ipSchedulerV2Type = "IpSchedulerV2" ipSchedulerV3Type = "IpSchedulerV3" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) op := options.NewServerOption() if err := options.Parse(op); err != nil { fmt.Printf("parse options failed: %v\n", err) os.Exit(1) } blog.InitLogs(op.LogConfig) defer blog.CloseLogs() conf := app.ParseConfig(op) app.RunPrometheusMetricsServer(conf) app.Run(conf) // pid if err := common.SavePid(op.ProcessConfig); err != nil { blog.Error("fail to save pid: err:%s", err.Error()) } switch conf.CustomSchedulerType { case ipSchedulerV1Type: v1.DefaultIpScheduler = v1.NewIpScheduler(conf) v1.DefaultIpScheduler.UpdateNetPoolsPeriodically() case ipSchedulerV2Type: defaultIpScheduler, err := v2.NewIpScheduler(conf) if err != nil { blog.Errorf("failed to build IpSchedulerV2: %s", err.Error()) os.Exit(1) } v2.DefaultIpScheduler = defaultIpScheduler defer v2.DefaultIpScheduler.Stop() case ipSchedulerV3Type: defaultIpScheduler, err := v3.NewIpScheduler(conf) if err != nil { blog.Errorf("failed to build IpSchedulerV3: %s", err.Error()) os.Exit(1) } v3.DefaultIpScheduler = defaultIpScheduler } // listening OS shutdown singal signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) <-signalChan blog.Infof("Got OS shutdown signal, shutting down bcs-cc-agent server gracefully...") return }
package log import "testing" func TestLog(t *testing.T) { ConfigZapLog(&LogSettings{ EnableConsole: true, }) logger.Info("111") }
// problem 10.2 package chapter10 func sgn(a, b int) int { if a < b { return 1 } else { return -1 } } func reverse(arr []int) { n := len(arr) for i := 0; i < n/2; i++ { arr[i], arr[n-1-i] = arr[n-1-i], arr[i] } } func SortKIncreasingDecreasingArray(arr []int) []int { arrs := make([][]int, 0) currSgn := sgn(arr[0], arr[1]) begin := 0 for i := 1; i < len(arr); i++ { if sgn(arr[i-1], arr[i]) != currSgn { if currSgn == -1 { reverse(arr[begin:i]) } arrs = append(arrs, arr[begin:i]) begin = i currSgn = sgn(arr[i-1], arr[i]) } } if currSgn == -1 { reverse(arr[begin:]) } arrs = append(arrs, arr[begin:]) return MergeSortedArrays(arrs) }
// Copyright 2016 Kranz. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package fakeApi import ( "fmt" "os" "path" "strconv" "strings" "time" "gopkg.in/macaron.v1" "github.com/rodkranz/fakeApi/modules/log" ) type ApiFakeOptions struct { DefaultApi string BaseFolder string } type ApiFake struct { *macaron.Context Default string Folder string Domain string Delay int Headers map[string]string ResponseIndex int } // GetMethodAndStatusCode return method, status code and bool if found or not func (a *ApiFake) GetMethodAndStatusCode() (string, int, bool) { // Get status code and method if it doesn't exist get random status, has := a.getHeaderData("X-Fake-Response-Code") if !has { return a.Context.Req.Method, a.Context.Resp.Status(), false } i, err := strconv.ParseInt(status, 10, 32) if err != nil { return a.Context.Req.Method, a.Context.Resp.Status(), false } return a.Context.Req.Method, int(i), true } // GetSeedPath returns the path of seed file. func (a *ApiFake) GetSeedPath(seed string) (string, error) { seed = strings.Replace(seed, "__", "#", -1) seed = strings.Replace(seed, "/", "_", -1) seed = strings.Replace(seed, "#", "_", -1) filePath := fmt.Sprintf("%v/%v.json", a.Folder, seed) if isNotExist(filePath) && !isNotExist(fmt.Sprintf("%v/%v.json", a.Default, seed)) { filePath = fmt.Sprintf("%v/%v.json", a.Default, seed) } return filePath, nil } // RegisterResponseSlice define position of slice for response 'X-Fake-Response-Index' func (a *ApiFake) registerResponseSlice() { responseIndex, has := a.getHeaderData("X-Fake-Response-Index") if !has { return } // try to convert of string to int64 if has error keep 0 delay i, err := strconv.ParseInt(responseIndex, 10, 32) if err != nil { return } a.ResponseIndex = int(i) } // RegisterDomain change domain 'default' to 'X-Fake-Domain' // if the folder exists with same name of 'X-Fake-Domain' // it will use this folder as base func (a *ApiFake) registerDomain() { if domain, has := a.getHeaderData("X-Fake-Domain"); has { a.Domain = domain } folder := fmt.Sprintf("%s/%s", a.Folder, a.Domain) if isNotExist(folder) { return } a.Folder = folder } // RegisterDelay if has header for dela register at fakeApi func (a *ApiFake) registerDelay() { delay, has := a.getHeaderData("X-Fake-Delay") if !has { return } // try to convert of string to int64 if has error keep 0 delay i, err := strconv.ParseInt(delay, 10, 32) if err != nil { return } a.Delay = int(i) } // getHeaderData returns first data from header func (a *ApiFake) getHeaderData(name string) (string, bool) { values, has := a.Context.Req.Header[name] if has && len(values) > 0 { if strings.Contains(values[0], ",") { values = strings.Split(values[0], ",") } return values[0], true } return "", false } // isNotExists return if file exists or not func isNotExist(path string) bool { _, err := os.Stat(path) return os.IsNotExist(err) } // Register Register fake api service func Register(opt ApiFakeOptions) macaron.Handler { // Check if fakes folder exist if isNotExist(opt.BaseFolder) { if err := os.Mkdir(opt.BaseFolder, 0755); err != nil { log.Fatal(4, "Please create a 'fakes' folder: [%v]", opt.BaseFolder) } } // Check if default folder in faker exist p := path.Join(opt.BaseFolder, opt.DefaultApi) if isNotExist(p) { if err := os.Mkdir(path.Join(p), 0755); err != nil { log.Fatal(4, "Please create a 'default' folder: [%v]", p) } } return func(ctx *macaron.Context) { api := &ApiFake{ Delay: 0, Domain: "default", Default: opt.DefaultApi, Folder: opt.BaseFolder, Context: ctx, ResponseIndex: -1, } // AutoConfig load method itself api.registerDomain() api.registerDelay() api.registerResponseSlice() // Share FakeApi Module for all handlers ctx.Map(api) // Execute handlers ctx.Next() // Apply delay time.Sleep(time.Duration(api.Delay) * time.Millisecond) } }
package boltrepo import ( "github.com/boltdb/bolt" "github.com/scjalliance/drivestream/commit" "github.com/scjalliance/drivestream/resource" ) var _ commit.TreeGroup = (*CommitTreeGroup)(nil) // CommitTreeGroup is an unordered group of tree changes sharing a common // parent. type CommitTreeGroup struct { db *bolt.DB drive resource.ID commit commit.SeqNum parent resource.ID } // Parent returns the parent resource ID of the group. func (ref CommitTreeGroup) Parent() resource.ID { return ref.parent } // Changes returns the set of changes contained in the group. func (ref CommitTreeGroup) Changes() (changes []commit.TreeChange, err error) { err = ref.db.View(func(tx *bolt.Tx) error { com := commitBucket(tx, ref.drive, ref.commit) if com == nil { return commit.NotFound{Drive: ref.drive, Commit: ref.commit} } tree := com.Bucket([]byte(TreeBucket)) if tree == nil { return commit.TreeGroupNotFound{Drive: ref.drive, Commit: ref.commit, Parent: ref.parent} } group := tree.Bucket([]byte(ref.parent)) if group == nil { return commit.TreeGroupNotFound{Drive: ref.drive, Commit: ref.commit, Parent: ref.parent} } cursor := group.Cursor() for k, v := cursor.First(); k != nil; k, v = cursor.Next() { if len(v) != 1 { return commit.TreeGroupInvalid{Drive: ref.drive, Commit: ref.commit, Parent: ref.parent} } changes = append(changes, commit.TreeChange{ Parent: ref.parent, Child: resource.ID(k), Removed: v[0] != 0, }) } return nil }) return changes, err }
// Copyright 2020-present Kuei-chun Chen. All rights reserved. package keyhole import ( "fmt" "io/ioutil" "github.com/simagix/gox" "go.mongodb.org/mongo-driver/bson" ) const ( compareClusters = "compare_clusters" printConnections = "print_connections" ) // Config stores keyhole configuration type Config struct { Action string `bson:"action,omitempty"` Filename string `bson:"filename,omitempty"` NoColor bool `bson:"no_color,omitempty"` Signature string `bson:"signature,omitempty"` URI string `bson:"uri,omitempty"` Verbose bool `bson:"verbose,omitempty"` IsDeepCompare bool `bson:"deep_compare,omitempty"` Filters []Filter `bson:"filters,omitempty"` SampleSize int `bson:"sample_size,omitempty"` SourceURI string `bson:"source_uri,omitempty"` TargetURI string `bson:"target_uri,omitempty"` } // Filter holds query filter of a namespace type Filter struct { NS string `bson:"ns"` Query bson.D `bson:"query"` TargetNS string `bson:"target_ns,omitempty"` } // Exec executes a plan based on a configuration file func Exec(filename string, signature string) error { var err error var cfg *Config var data []byte if data, err = ioutil.ReadFile(filename); err != nil { return err } else if err = bson.UnmarshalExtJSON(data, false, &cfg); err != nil { return err } else if cfg.Action == "" { return fmt.Errorf(`action is required`) } if cfg.Signature == "" { cfg.Signature = signature } gox.GetLogger(cfg.Signature).Infof("executing %v", cfg.Action) if cfg.Action == compareClusters { return CompareClusters(cfg) } else if cfg.Action == printConnections { return PrintConnections(cfg) } return err }
// SPDX-License-Identifier: Unlicense OR MIT package material import ( "github.com/gop9/olt/gio/layout" "github.com/gop9/olt/gio/text" "github.com/gop9/olt/gio/unit" "github.com/gop9/olt/gio/widget" ) type RadioButton struct { checkable Key string } // RadioButton returns a RadioButton with a label. The key specifies // the value for the Enum. func (t *Theme) RadioButton(key, label string) RadioButton { return RadioButton{ checkable: checkable{ Label: label, Color: t.Color.Text, IconColor: t.Color.Primary, Font: text.Font{ Size: t.TextSize.Scale(14.0 / 16.0), }, Size: unit.Dp(26), shaper: t.Shaper, checkedStateIcon: t.radioCheckedIcon, uncheckedStateIcon: t.radioUncheckedIcon, }, Key: key, } } func (r RadioButton) Layout(gtx *layout.Context, enum *widget.Enum) { r.layout(gtx, enum.Value(gtx) == r.Key) enum.Layout(gtx, r.Key) }
package manager import ( "github.com/roberthafner/bpmn-engine/domain/model" "github.com/roberthafner/bpmn-engine/domain/model/database" ) type EntityManager interface { Insert(e model.Entity) Update(e model.Entity) Delete(e model.Entity) } type DeploymentEntityManager struct { db database.Database } func NewDeploymentEntityManager(db database.Database) DeploymentEntityManager { dem := DeploymentEntityManager{} dem.db = db return dem } func (dem DeploymentEntityManager) Insert(e model.Entity) { d := e.(model.DeploymentEntity) dem.db.Insert(d) resources := d.Resources for _, r := range resources { r.DeploymentId = d.Id dem.db.Insert(r) } } func (dem DeploymentEntityManager) Update(e model.Entity) { d := e.(model.DeploymentEntity) dem.db.Update(d) } func (dem DeploymentEntityManager) Delete(e model.Entity) { d := e.(model.DeploymentEntity) dem.db.Delete(d) }
//author: https://github.com/5k3105 package main import ( "os" "strconv" "github.com/emirpasic/gods/lists/arraylist" "github.com/therecipe/qt/core" "github.com/therecipe/qt/gui" "github.com/therecipe/qt/widgets" ) var statusbar *widgets.QStatusBar func main() { widgets.NewQApplication(len(os.Args), os.Args) // Main Window var window = widgets.NewQMainWindow(nil, 0) window.SetWindowTitle("Table") // Main Widget var table = NewArgsTable() // Set Central Widget window.SetCentralWidget(table) // Statusbar statusbar = widgets.NewQStatusBar(window) window.SetStatusBar(statusbar) // Run App widgets.QApplication_SetStyle2("fusion") window.Show() widgets.QApplication_Exec() } var ( list *arraylist.List model *core.QAbstractTableModel view *widgets.QTableView textIndex *core.QModelIndex currentRow int ) type Delegate struct { widgets.QStyledItemDelegate //don't use *pointers or it won't work } func NewArgsTable() *widgets.QTableView { view = widgets.NewQTableView(nil) model = core.NewQAbstractTableModel(nil) delegate := InitDelegate() view.SetItemDelegate(delegate) view.SetFont(gui.NewQFont2("verdana", 13, 1, false)) view.ConnectKeyPressEvent(keypressevent) view.ConnectCurrentChanged(currentchanged) model.ConnectRowCount(rowcount) model.ConnectColumnCount(columncount) model.ConnectData(data) model.ConnectSetData(setdata) model.ConnectInsertRows(insertrows) model.ConnectFlags(flags) model.ConnectRemoveRows(removerows) model.ConnectHeaderData(headerdata) list = arraylist.New() for i := 0; i < 6; i++ { list.Add(strconv.Itoa(i + i)) } list.Add("") // blank view.SetModel(model) return view } func keypressevent(e *gui.QKeyEvent) { if e.Key() == int(core.Qt__Key_Delete) { if currentRow < list.Size()-1 { model.RemoveRows(currentRow, 1, core.NewQModelIndex()) } } else { view.KeyPressEventDefault(e) } } func currentchanged(current *core.QModelIndex, previous *core.QModelIndex) { currentRow = current.Row() } func InitDelegate() *Delegate { item := NewDelegate(nil) //will be generated in moc.go item.ConnectCreateEditor(createEditor) item.ConnectSetEditorData(setEditorData) item.ConnectSetModelData(setModelData) item.ConnectUpdateEditorGeometry(updateEditorGeometry) return item } func createEditor(parent *widgets.QWidget, option *widgets.QStyleOptionViewItem, index *core.QModelIndex) *widgets.QWidget { editor := widgets.NewQLineEdit(parent) textIndex = index if index.Row() == list.Size()-1 { model.InsertRow(index.Row(), core.NewQModelIndex()) } editor.ConnectTextChanged(textchanged) return editor.QWidget_PTR() } func textchanged(text string) { model.SetData(textIndex, core.NewQVariant1(text), 2) // edit role } func setEditorData(editor *widgets.QWidget, index *core.QModelIndex) { value, _ := list.Get(index.Row()) lineedit := widgets.NewQLineEditFromPointer(editor.Pointer()) lineedit.SetText(value.(string)) } func setModelData(editor *widgets.QWidget, model *core.QAbstractItemModel, index *core.QModelIndex) { lineedit := widgets.NewQLineEditFromPointer(editor.Pointer()) text := lineedit.Text() model.SetData(index, core.NewQVariant1(text), int(core.Qt__EditRole)) } func updateEditorGeometry(editor *widgets.QWidget, option *widgets.QStyleOptionViewItem, index *core.QModelIndex) { editor.SetGeometry(option.Rect()) } func headerdata(section int, orientation core.Qt__Orientation, role int) *core.QVariant { if orientation == 1 && role == 0 { // Qt__Horizontal, Qt__DisplayRole return core.NewQVariant1("column" + strconv.Itoa(section+1)) } if orientation == 2 && role == 0 { if section < list.Size()-1 { return core.NewQVariant1(strconv.Itoa(section + 1)) } else { return core.NewQVariant1("*") } } return core.NewQVariant() } func rowcount(parent *core.QModelIndex) int { return list.Size() } func columncount(parent *core.QModelIndex) int { return 1 } func data(index *core.QModelIndex, role int) *core.QVariant { if role == 0 && index.IsValid() { // display role text, exists := list.Get(index.Row()) if exists { switch deducedText := text.(type) { case int: { return core.NewQVariant1(deducedText) } case string: { return core.NewQVariant1(deducedText) } } } } return core.NewQVariant() } func setdata(index *core.QModelIndex, value *core.QVariant, role int) bool { if (role == 2 || role == 0) && index.IsValid() { // edit role list.Remove(index.Row()) list.Insert(index.Row(), value.ToString()) return true } return true } func insertrows(row int, count int, parent *core.QModelIndex) bool { model.BeginInsertRows(core.NewQModelIndex(), row, row) list.Add("") model.EndInsertRows() view.SelectRow(row) return true } func removerows(row int, count int, parent *core.QModelIndex) bool { model.BeginRemoveRows(core.NewQModelIndex(), row, row) list.Remove(row) model.EndRemoveRows() return true } func flags(index *core.QModelIndex) core.Qt__ItemFlag { return 35 // ItemIsSelectable || ItemIsEditable || ItemIsEnabled }
/* Copyright (c) 2017 GigaSpaces Technologies Ltd. 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 cloudify import ( rest "github.com/cloudify-incubator/cloudify-rest-go-client/cloudify/rest" ) // Event - infromation about cloudify event type Event struct { NodeInstanceID string `json:"node_instance_id"` EventType string `json:"event_type"` Operation string `json:"operation"` BlueprintID string `json:"blueprint_id"` NodeName string `json:"node_name"` WorkflowID string `json:"workflow_id"` ErrorCauses string `json:"error_causes"` ReportedTimestamp string `json:"reported_timestamp"` DeploymentID string `json:"deployment_id"` Type string `json:"type"` ExecutionID string `json:"execution_id"` Timestamp string `json:"timestamp"` Message string `json:"message"` } // Events - cloudify response with events list type Events struct { rest.BaseMessage Metadata rest.Metadata `json:"metadata"` Items []Event `json:"items"` } // GetEvents - get events list filtered by params func (cl *Client) GetEvents(params map[string]string) (*Events, error) { var events Events values := cl.stringMapToURLValue(params) err := cl.Get("events?"+values.Encode(), &events) if err != nil { return nil, err } return &events, nil }
/* * Copyright (c) 2019. Alexey Shtepa <as.shtepa@gmail.com> LICENSE MIT * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. */ package uuid import ( "crypto/rand" "encoding/hex" "math/big" "strings" ) // GenerateBytesUUID returns a UUID based on RFC 4122 returning the generated bytes func GenerateBytesUUID() []byte { uuid := make([]byte, 16) if _, err := rand.Read(uuid[:]); err != nil { panic(err) } // variant bits; see section 4.1.1 uuid[8] = uuid[8]&^0xc0 | 0x80 // version 4 (pseudo-random); see section 4.1.3 uuid[6] = uuid[6]&^0xf0 | 0x40 return uuid } // GenerateIntUUID returns a UUID based on RFC 4122 returning a big.Int func GenerateIntUUID() *big.Int { uuid := GenerateBytesUUID() z := big.NewInt(0) return z.SetBytes(uuid) } // GenerateUUID returns a UUID based on RFC 4122 func GenerateUUID() string { uuid := GenerateBytesUUID() return idBytesToStr(uuid) } func UUIDFromString(s string) (u []byte, err error) { u = make([]byte, 16) hexStr := strings.ReplaceAll(s, "-", "") _, err = hex.Decode(u, []byte(hexStr)) return } func StringFromUUID(u []byte) string { return idBytesToStr(u) } func idBytesToStr(id []byte) (str string) { str += hex.EncodeToString(id[0:4]) str += "-" + hex.EncodeToString(id[4:6]) str += "-" + hex.EncodeToString(id[6:8]) str += "-" + hex.EncodeToString(id[8:10]) str += "-" + hex.EncodeToString(id[10:]) return }
package mongo_test import ( // Standard Library Imports "testing" "time" // External Imports "github.com/ory/fosite" "github.com/pborman/uuid" // Public Imports "github.com/matthewhartstonge/storage" ) func expectedSessionCache() storage.SessionCache { return storage.SessionCache{ ID: uuid.New(), CreateTime: time.Now().Unix(), UpdateTime: time.Now().Unix() + 600, Signature: "Yhte@ensa#ei!+suu$re%sta^viik&oss*aha(joaisiaut)ta-is+ie%to_n==", } } func TestCacheManager_Create(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := expectedSessionCache() got, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected) if err != nil { AssertError(t, err, nil, "create should return no database errors") } if got != expected { AssertError(t, got, expected, "cache object not equal") } } func TestCacheManager_Create_ShouldConflict(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := expectedSessionCache() got, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected) if err != nil { AssertError(t, err, nil, "create should return no database errors") } if got != expected { AssertError(t, got, expected, "cache object not equal") } _, err = store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected) if err == nil { AssertError(t, err, nil, "create should return an error on conflict") } if err != storage.ErrResourceExists { AssertError(t, err, nil, "create should return conflict") } } func TestCacheManager_Get(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := expectedSessionCache() created, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected) if err != nil { AssertError(t, err, nil, "create should return no database errors") } if created != expected { AssertError(t, created, expected, "cache object not equal") } got, err := store.CacheManager.Get(ctx, storage.EntityCacheAccessTokens, expected.Key()) if err != nil { AssertError(t, err, nil, "get should return no database errors") } if got != expected { AssertError(t, got, expected, "cache object not equal") } } func TestCacheManager_Get_ShouldReturnNotFound(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := fosite.ErrNotFound got, err := store.CacheManager.Get(ctx, storage.EntityCacheAccessTokens, "lolNotFound") if err != expected { AssertError(t, got, expected, "get should return not found") } } func TestCacheManager_Update(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := expectedSessionCache() created, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected) if err != nil { AssertError(t, err, nil, "create should return no database errors") } if created != expected { AssertError(t, created, expected, "cache object not equal") } // Perform an update.. updatedSignature := "something completely different!" created.Signature = updatedSignature got, err := store.CacheManager.Update(ctx, storage.EntityCacheAccessTokens, created) if err != nil { AssertError(t, err, nil, "update should return no database errors") } if expected.UpdateTime == 0 { AssertError(t, got.UpdateTime, time.Now().Unix(), "update time was not set") } // override update time on expected with got. The time stamp received // should match time.Now().Unix() but due to the nature of time based // testing against time.Now().Unix(), it can fail on crossing over the // second boundary. expected.UpdateTime = got.UpdateTime expected.Signature = updatedSignature if got != expected { AssertError(t, got, expected, "cache update object not equal") } } func TestCacheManager_Update_ShouldReturnNotFound(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() _, err := store.CacheManager.Update(ctx, storage.EntityCacheAccessTokens, expectedSessionCache()) if err == nil { AssertError(t, err, nil, "update should return an error on not found") } if err != fosite.ErrNotFound { AssertError(t, err, nil, "update should return not found") } } func TestCacheManager_Delete(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := expectedSessionCache() created, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected) if err != nil { AssertError(t, err, nil, "create should return no database errors") } if created != expected { AssertError(t, created, expected, "cache object not equal") } err = store.CacheManager.Delete(ctx, storage.EntityCacheAccessTokens, created.Key()) if err != nil { AssertError(t, err, nil, "delete should return no database errors") } // Double check that the original reference was deleted expectedErr := fosite.ErrNotFound got, err := store.CacheManager.Get(ctx, storage.EntityCacheAccessTokens, created.Key()) if err != expectedErr { AssertError(t, got, expectedErr, "get should return not found") } } func TestCacheManager_Delete_ShouldReturnNotFound(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := expectedSessionCache() err := store.CacheManager.Delete(ctx, storage.EntityCacheAccessTokens, expected.Key()) if err == nil { AssertError(t, err, nil, "delete should return an error on not found") } if err != fosite.ErrNotFound { AssertError(t, err, nil, "delete should return not found") } } func TestCacheManager_DeleteByValue(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := expectedSessionCache() created, err := store.CacheManager.Create(ctx, storage.EntityCacheAccessTokens, expected) if err != nil { AssertError(t, err, nil, "create should return no database errors") } if created != expected { AssertError(t, created, expected, "cache object not equal") } err = store.CacheManager.DeleteByValue(ctx, storage.EntityCacheAccessTokens, created.Value()) if err != nil { AssertError(t, err, nil, "DeleteByValue should return no database errors") } // Double check that the original reference was deleted expectedErr := fosite.ErrNotFound got, err := store.CacheManager.Get(ctx, storage.EntityCacheAccessTokens, created.Key()) if err != expectedErr { AssertError(t, got, expectedErr, "get should return not found") } } func TestCacheManager_DeleteByValue_ShouldReturnNotFound(t *testing.T) { store, ctx, teardown := setup(t) defer teardown() expected := expectedSessionCache() err := store.CacheManager.DeleteByValue(ctx, storage.EntityCacheAccessTokens, expected.Value()) if err == nil { AssertError(t, err, nil, "DeleteByValue should return an error on not found") } if err != fosite.ErrNotFound { AssertError(t, err, nil, "DeleteByValue should return not found") } }
package commands import ( "context" "encoding/json" "io" "os" "path/filepath" "github.com/pkg/errors" "github.com/spf13/cobra" ) // Inspect runs the command to inspect a cluster func Inspect(ctx context.Context, stateDir string) *cobra.Command { cmd := &cobra.Command{ Use: "inspect", Short: "Get details about an existing cluster", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return runInspect(ctx, stateDir, args[0], cmd.OutOrStdout(), cmd.OutOrStderr()) }, } return cmd } type inspectItem struct { State state Model apiModel } func runInspect(ctx context.Context, stateDir, name string, outW, errW io.Writer) error { dir := filepath.Join(stateDir, name) var errs []error var inspect inspectItem if _, err := os.Stat(dir); os.IsNotExist(err) { return clusterNotFound(name) } model, err := readAPIModel(dir) if err != nil { errs = append(errs, err) } inspect.Model = model s, err := readState(dir) if err != nil { errs = append(errs, err) } inspect.State = s data, err := json.MarshalIndent(inspect, "", "\t") if err != nil { return errors.Wrap(err, "error marshaling final output") } outW.Write(data) io.WriteString(outW, "\n") for _, e := range errs { io.WriteString(errW, e.Error()+"\n") } return nil }
/* Copyright © 2020 Vlad Krava <vkrava4@gmail.com> 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/spf13/cobra" "os" "github.com/mitchellh/go-homedir" "github.com/spf13/viper" ) var cfgFile string var rootCmd = &cobra.Command{ Use: "curlson", Short: "A command-line project which is designed to perform thousands of concurrent requests with specified data " + "based on user-templates or static values to destination address with handy statistic reports and tracing options.", Long: ` A command-line project which is designed to perform thousands of concurrent requests with specified data based on user-templates or static values to destination address with handy statistic reports and tracing options. Features: - Document and request templating - Multithreading - Performance monitoring / Statistics - Results reporting - Tracing Visit official GitHub: 'https://github.com/vkrava4/curlson' for additional information`, } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func init() { cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports persistent flags, which, if defined here, // will be global for your application. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.curlson.yaml)") } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } // Search config in home directory with name ".curlson" (without extension). viper.AddConfigPath(home) viper.SetConfigName(".curlson") } viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } }
package main import ( "net" "log" "fmt" ) /** net包实现服务端的核心部分是: net.Listen()在给定的本地网络地址上来创建新的监听器。如果只传端口号给它,例如":61000", 那么监听器会监听所有可用的网络接口。 这相当方便,因为计算机通常至少提供两个活动接口,回环接口和最少一个真实网卡。 这个函数成功的话返回Listener。 Listener接口有一个Accept()方法用来等待请求进来。然后它接受请求,并给调用者返回新的连接。Accept()一般来说都是在循环中调用,能够同时服务多个连接。每个连接可以由一个单独的goroutine处理,正如下面代码所示的。 */ const( Port=":3130" ) // 入口函数 func main() { ln, err := net.Listen("tcp", Port) if err != nil { log.Println(err) return } fmt.Println("echo server start working...") for { conn, err := ln.Accept() if err != nil { log.Println(err) continue } go echoFunc(conn) } } func echoFunc(conn net.Conn) { buf := make([]byte, 1024) var body = `HTTP/1.1 200 OK Content-type:application/html who are u..... ` for { n, err := conn.Read(buf) if err != nil { log.Println(err) return } fmt.Println(n) fmt.Println(conn.LocalAddr()) conn.Write([]byte(body)) conn.Close() } }
package cli import ( "errors" "fmt" "reflect" ) func CombineStructs(structs ...interface{}) (interface{}, error) { fields := []reflect.StructField{} for _, s := range structs { v := reflect.Indirect(reflect.ValueOf(s)) if v.Kind() != reflect.Struct { return nil, fmt.Errorf("invalid value type, must be struct: %T", s) } t := v.Type() for i := 0; i < v.NumField(); i++ { fields = append(fields, t.Field(i)) } } result := reflect.New(reflect.StructOf(fields)) // Copy data resultIndirect := reflect.Indirect(result) for _, s := range structs { v := reflect.Indirect(reflect.ValueOf(s)) for i := 0; i < v.NumField(); i++ { src := v.Field(i) dest := resultIndirect.FieldByName(v.Type().Field(i).Name) dest.Set(src) } } return result.Interface(), nil } func CopyStruct(src, dest interface{}) error { destValue := reflect.Indirect(reflect.ValueOf(dest)) if !destValue.CanSet() { return errors.New("unable to set destination, must be pointer") } if destValue.Kind() != reflect.Struct { return fmt.Errorf("invalid value type, must be struct: %T", dest) } srcValue := reflect.Indirect(reflect.ValueOf(src)) if srcValue.Kind() != reflect.Struct { return fmt.Errorf("invalid value type, must be struct: %T", src) } destType := destValue.Type() for i := 0; i < destValue.NumField(); i++ { dest := destValue.Field(i) src := srcValue.FieldByName(destType.Field(i).Name) if !src.IsValid() { continue } if src.Type().AssignableTo(dest.Type()) { dest.Set(src) } } return nil }
package main import "fmt" func main() { x := []int{42, 43, 44, 45, 46, 47, 48, 49, 50, 51} a := x[:5] fmt.Println(a) a = x[5:] fmt.Println(a) a = x[2:7] fmt.Println(a) a = x[1:6] fmt.Println(a) }
package controllers import ( "github.com/revel/revel" "github.com/revel/modules/db/app" "goblog/app/models" "time" "goblog/app/routes" "database/sql" "fmt" ) type Post struct { *revel.Controller db.Transactional } func (c Post) Index() revel.Result { var posts []models.Post rows, err := c.Txn.Query("select id, title, body, created_at, updated_at from posts order by created_at desc") if err != nil { panic(err) } for rows.Next() { post := models.Post{} if err := rows.Scan(&post.Id, &post.Title, &post.Body, &post.CreatedAt, &post.UpdatedAt); err != nil { panic(err) } posts = append(posts, post) } return c.Render(posts) } func (c Post) New() revel.Result { post := models.Post{} return c.Render(post) } func (c Post) Create(title, body string) revel.Result { result, err := c.Txn.Exec("insert into posts(title, body, created_at, updated_at) values(?,?,?,?)", title, body, time.Now(), time.Now()) id, err := result.LastInsertId() if err != nil { panic(err) } return c.Redirect(routes.Post.Show(int(id))) } func (c Post) Show(id int) revel.Result { post, err := getPost(c.Txn, id) if err != nil { panic(err) } return c.Render(post) } func getPost(txn *sql.Tx, id int) (models.Post, error) { post := models.Post{} err := txn.QueryRow("select id, title, body, created_at, updated_at from posts where id=?", id). Scan(&post.Id, &post.Title, &post.Body, &post.CreatedAt, &post.UpdatedAt) switch { case err == sql.ErrNoRows: return post, fmt.Errorf("No post with that ID - %d.", id) case err != nil: return post, err } return post, nil } func (c Post) Edit(id int) revel.Result { post, err := getPost(c.Txn, id) if err != nil { panic(err) } return c.Render(post) } func (c Post) Update(id int, title, body string) revel.Result { if _, err := c.Txn.Exec("update posts set title=?, body=?, updated_at=? where id=?", title, body, time.Now(), id); err != nil { panic(err) } return c.Redirect(routes.Post.Show(id)) } func (c Post) Destroy(id int) revel.Result { if _, err := c.Txn.Exec("delete from posts where id=?", id); err != nil { panic(err) } return c.Redirect(routes.Post.Index()) }
package envoy import "fmt" type Collector struct { AdminHost string } // Value by quantile (P75, P90, etc.) type Histogram map[string]float64 type Counters struct { // Counters UpstreamReq, UpstreamResp2xx, UpstreamResp4xx, UpstreamResp5xx float64 } func (c *Counters) String() string { return fmt.Sprintf( "UpstreamReq: %g, UpstreamResp2xx: %g, UpstreamResp4xx: %g, UpstreamResp5xx: %g\n", c.UpstreamReq, c.UpstreamResp2xx, c.UpstreamResp4xx, c.UpstreamResp5xx) } type UpstreamCluster string type CountersByUpstream map[string]*Counters type HistogramsByUpstream map[string]Histogram
// Copyright 2017 The Bazel Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The skylark command interprets a Skylark file. // // With no arguments, it starts a read-eval-print loop (REPL). // If an input line can be parsed as an expression, // the REPL parses and evaluates it and prints its result. // Otherwise the REPL reads lines until a blank line, // then tries again to parse the multi-line input as an // expression. If the input still cannot be parsed as an expression, // the REPL parses and executes it as a file (a list of statements), // for side effects. package main // TODO(adonovan): // // - Distinguish expressions from statements more precisely. // Otherwise e.g. 1 is parsed as an expression but // 1000000000000000000000000000 is parsed as a file // because the scanner fails to convert it to an int64. // The spec should clarify limits on numeric literals. // // - Unparenthesized tuples are not parsed as a single expression: // >>> (1, 2) // (1, 2) // >>> 1, 2 // ... // >>> // This is not necessarily a bug. import ( "bufio" "bytes" "flag" "fmt" "io" "log" "os" "runtime/pprof" "sort" "strings" "github.com/google/skylark" "github.com/google/skylark/resolve" "github.com/google/skylark/syntax" ) // flags var ( cpuprofile = flag.String("cpuprofile", "", "gather CPU profile in this file") showenv = flag.Bool("showenv", false, "on success, print final global environment") ) // non-standard dialect flags func init() { flag.BoolVar(&resolve.AllowFloat, "fp", resolve.AllowFloat, "allow floating-point numbers") flag.BoolVar(&resolve.AllowFreeze, "freeze", resolve.AllowFreeze, "add freeze built-in function") flag.BoolVar(&resolve.AllowSet, "set", resolve.AllowSet, "allow set data type") flag.BoolVar(&resolve.AllowLambda, "lambda", resolve.AllowLambda, "allow lambda expressions") flag.BoolVar(&resolve.AllowNestedDef, "nesteddef", resolve.AllowNestedDef, "allow nested def statements") } func main() { log.SetPrefix("skylark: ") log.SetFlags(0) flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal(err) } if err := pprof.StartCPUProfile(f); err != nil { log.Fatal(err) } defer pprof.StopCPUProfile() } switch len(flag.Args()) { case 0: repl() case 1: execfile(flag.Args()[0]) default: log.Fatal("want at most one Skylark file name") } } func execfile(filename string) { thread := &skylark.Thread{Load: load} globals := make(skylark.StringDict) if err := skylark.ExecFile(thread, filename, nil, globals); err != nil { printError(err) os.Exit(1) } // Print the global environment. if *showenv { var names []string for name := range globals { if !strings.HasPrefix(name, "_") { names = append(names, name) } } sort.Strings(names) for _, name := range names { fmt.Fprintf(os.Stderr, "%s = %s\n", name, globals[name]) } } } func repl() { thread := &skylark.Thread{Load: load} globals := make(skylark.StringDict) sc := bufio.NewScanner(os.Stdin) outer: for { io.WriteString(os.Stderr, ">>> ") if !sc.Scan() { break } line := sc.Text() if l := strings.TrimSpace(line); l == "" || l[0] == '#' { continue // blank or comment } // If the line contains a well-formed // expression, evaluate it. if expr, err := syntax.ParseExpr("<stdin>", line); err == nil { if isLoad(expr) { if err := execFileNoFreeze(thread, line, globals); err != nil { printError(err) } } else if v, err := skylark.Eval(thread, "<stdin>", line, globals); err != nil { printError(err) } else if v != skylark.None { fmt.Println(v) } continue } // Otherwise assume it is the first of several // comprising a file, followed by a blank line. var buf bytes.Buffer fmt.Fprintln(&buf, line) for { io.WriteString(os.Stderr, "... ") if !sc.Scan() { break outer } line := sc.Text() if l := strings.TrimSpace(line); l == "" { break // blank } fmt.Fprintln(&buf, line) } text := buf.Bytes() // Try parsing it once more as an expression, // such as a call spread over several lines: // f( // 1, // 2 // ) if expr, err := syntax.ParseExpr("<stdin>", text); err == nil && !isLoad(expr) { if v, err := skylark.Eval(thread, "<stdin>", text, globals); err != nil { printError(err) } else if v != skylark.None { fmt.Println(v) } continue } // Execute it as a file. if err := execFileNoFreeze(thread, text, globals); err != nil { printError(err) } } fmt.Println() } // execFileNoFreeze is skylark.ExecFile without globals.Freeze(). func execFileNoFreeze(thread *skylark.Thread, src interface{}, globals skylark.StringDict) error { // parse f, err := syntax.Parse("<stdin>", src) if err != nil { return err } // resolve if err := resolve.File(f, globals.Has, skylark.Universe.Has); err != nil { return err } // execute fr := thread.Push(globals, len(f.Locals)) defer thread.Pop() return fr.ExecStmts(f.Stmts) } type entry struct { globals skylark.StringDict err error } var cache = make(map[string]*entry) // load is a simple sequential implementation of module loading. func load(thread *skylark.Thread, module string) (skylark.StringDict, error) { e, ok := cache[module] if e == nil { if ok { // request for package whose loading is in progress return nil, fmt.Errorf("cycle in load graph") } // Add a placeholder to indicate "load in progress". cache[module] = nil // Load it. thread := &skylark.Thread{Load: load} globals := make(skylark.StringDict) err := skylark.ExecFile(thread, module, nil, globals) e = &entry{globals, err} // Update the cache. cache[module] = e } return e.globals, e.err } func printError(err error) { if evalErr, ok := err.(*skylark.EvalError); ok { fmt.Fprintln(os.Stderr, evalErr.Backtrace()) } else { fmt.Fprintln(os.Stderr, err) } } // isLoad reports whether e is a load(...) function call. // If so, we must parse it again as a file, not an expression, // so that it is is converted to a load statement. // ("load" should really be a reserved word.) func isLoad(e syntax.Expr) bool { if call, ok := e.(*syntax.CallExpr); ok { if id, ok := call.Fn.(*syntax.Ident); ok && id.Name == "load" { return true } } return false }
package main func main() { } func i() chan int { return make(chan int) }
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package flare import "github.com/pkg/errors" // Pagination used to fetch a slice of a given entity. type Pagination struct { Limit int Offset int Total int } // Valid indicates if the current pagination is valid. func (p *Pagination) Valid() error { if p.Offset < 0 { return errors.Errorf("invalid offset '%d'", p.Offset) } if p.Limit < 0 { return errors.Errorf("invalid limit '%d'", p.Limit) } return nil }
package logger import ( "fmt" "github.com/sirupsen/logrus" ) type elasticHook struct{} func NewElasticHook() logrus.Hook { return new(elasticHook) } func (eh *elasticHook) Levels() []logrus.Level { return logrus.AllLevels } func (eh *elasticHook) Fire(entry *logrus.Entry) error { var levelText string // Add log level to the log.level data key switch entry.Level { case logrus.PanicLevel: levelText = "panic" case logrus.FatalLevel: levelText = "fatal" case logrus.ErrorLevel: levelText = "error" case logrus.WarnLevel: levelText = "warn" case logrus.InfoLevel: levelText = "info" case logrus.DebugLevel: levelText = "debug" case logrus.TraceLevel: levelText = "trace" default: return fmt.Errorf("unknown log level %s", entry.Level) } if entry.Data["log"] == nil { entry.Data["log"] = make(map[string]interface{}) } logData := entry.Data["log"].(map[string]interface{}) logData["level"] = levelText entry.Data["log"] = logData // All done return nil }
package testdata import ( "github.com/frk/gosql" "github.com/frk/gosql/internal/testdata/common" ) type SelectWithOrderByDirectiveQuery struct { Users []*common.User `rel:"test_user:u"` _ gosql.OrderBy `sql:"-u.created_at"` }
package main import ( "bufio" "io" "io/ioutil" "strings" "unicode" "github.com/BurntSushi/toml" ) // Updater represents updater type Updater struct { Name string URL string Params map[string]string } // Update executes update and returns result func (updater *Updater) Update() (string, error) { url, err := updater.parse() if err != nil { return "", err } resp, err := httpClient.Get(url) if err != nil { return "", err } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(b), nil } // LoadUpdater loads updater from file func LoadUpdater(fileName string) (*Updater, error) { b, err := ioutil.ReadFile(fileName) if err != nil { return nil, err } var updater Updater err = toml.Unmarshal(b, &updater) if err != nil { return nil, err } return &updater, nil } func (updater *Updater) parse() (string, error) { r := strings.NewReader(updater.URL) reader := bufio.NewReader(r) result := "" vari := "" readingVar := false for { r, _, err := reader.ReadRune() if err == io.EOF { if readingVar && len(vari) != 0 { val, ok := updater.Params[vari] if !ok { return "", wrapError(errVarNotFound, vari) } result += val } break } if err != nil { return "", err } if r == '$' { if !readingVar { readingVar = true continue } val, ok := updater.Params[vari] if !ok { return "", wrapError(errVarNotFound, vari) } result += val vari = "" continue } if !unicode.IsLetter(r) && !unicode.IsDigit(r) && readingVar { readingVar = false val, ok := updater.Params[vari] if !ok { return "", wrapError(errVarNotFound, vari) } result += val vari = "" } if readingVar { vari += string(r) continue } result += string(r) } return result, nil }
package eeautil import "math/rand" // Contains returns true if the given slice contains the given int. func Contains(list []int, ind int) bool { for _, v := range list { if ind == v { return true } } return false } // RandomSubset sets the destintation slice to be a random subset of the // numbers 0, ..., l of size n. func RandomSubset(dst *[]int, n, l int) { *dst = (*dst)[:0] for i := 0; i < n; i++ { ind := rand.Intn(l) for Contains(*dst, ind) { if ind == l-1 { ind = 0 } else { ind++ } } *dst = append(*dst, ind) } }
package ethos import ( "io/ioutil" "os" "os/exec" "strconv" "strings" "time" "github.com/ka2n/masminer/machine/metal/gpu/gpustat" ) // Stat : gpuの情報をethOSのAPIで取得します func Stat() ([]gpustat.GPUStat, error) { return nil, nil } func GPUs() (string, error) { c, err := readFile("/var/run/ethos/gpucount.file") if err != nil { return "", err } return c, nil } func Driver() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readconf driver`) if err != nil { return "", err } return c, nil } func Miner() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readconf miner`) if err != nil { return "", err } return c, nil } func Defunct() (int64, error) { c, err := readFile("/var/run/ethos/defunct.file") if err != nil { return -1, err } return strconv.ParseInt(c, 10, 64) } func Off() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readconf off`) if err != nil { return "", err } return c, nil } func Allowed() (int64, error) { c, err := readFile("/opt/ethos/etc/allow.file") if err != nil { return -1, err } return strconv.ParseInt(c, 10, 64) } func Overheat() (int64, error) { c, err := readFile("/var/run/ethos/overheat.file") if err != nil { return -1, err } return strconv.ParseInt(c, 10, 64) } func PoolInfo() (string, error) { c, err := runScript(`cat /home/ethos/local.conf | grep -v '^#' | egrep -i 'pool|wallet|proxy'`) if err != nil { return "", err } return c, nil } func Pool() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readconf proxypool1`) if err != nil { return "", err } return c, nil } func MinerVersion() (string, error) { c, err := runScript(`cat /var/run/ethos/miner.versions | grep '$miner ' | cut -d" " -f2 | head -1`) if err != nil { return "", err } return c, nil } func BootMode() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata bootmode`) if err != nil { return "", err } return c, nil } func RackLoc() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readconf loc`) if err != nil { return "", err } return c, nil } func Motherboard() (string, error) { c, err := readFile("/var/run/ethos/motherboard.file") if err != nil { return "", err } return c, nil } func Rofs() (time.Duration, error) { c, err := readFile("/opt/ethos/etc/check-ro.file") if err != nil { return -1, err } i, err := strconv.ParseInt(c, 10, 64) if err != nil { return -1, err } t := time.Unix(i, 0) return time.Now().Sub(t), nil } func DriveName() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata driveinfo`) if err != nil { return "", err } return c, nil } func Temp() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata temps`) if err != nil { return "", err } return c, nil } func Version() (string, error) { c, err := readFile("/opt/ethos/etc/version") if err != nil { return "", err } return c, nil } func MinerSecs() (int64, error) { miner, err := Miner() if err != nil { return -1, err } c, err := runScript(`ps -eo pid,etime,command | grep ` + miner + ` | grep -v grep | head -1 | awk '{print $2}' | /opt/ethos/bin/convert_time.awk`) if err != nil { return -1, err } return strconv.ParseInt(c, 10, 64) } func AdlError() (string, error) { c, err := readFile("/var/run/ethos/adl_error.file") if err != nil { return "", err } return c, nil } func ProxyProblem() (string, error) { c, err := readFile("/var/run/ethos/proxy_error.file") if err != nil { return "", err } return c, nil } func Updating() (string, error) { c, err := readFile("/var/run/ethos/updating.file") if err != nil { return "", err } return c, nil } func ConnectedDisplays() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata connecteddisplays`) if err != nil { return "", err } return c, nil } func Resolution() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata resolution`) if err != nil { return "", err } return c, nil } func Gethelp() (string, error) { c, err := runScript(`tail -1 /var/log/gethelp.log`) if err != nil { return "", err } return c, nil } func ConfigError() (string, error) { c, err := runScript(`cat /var/run/ethos/config_mode.file`) if err != nil { return "", err } return c, nil } func SendRemote() (string, error) { c, err := runScript(`cat /var/run/ethos/send_remote.file`) if err != nil { return "", err } return c, nil } func Autorebooted() (string, error) { c, err := runScript(`cat /opt/ethos/etc/autorebooted.file`) if err != nil { return "", err } return c, nil } func Status() (string, error) { c, err := runScript(`cat /var/run/ethos/status.file`) if err != nil { return "", err } return c, nil } func SelectedGPUs() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readconf selectedgpus`) if err != nil { return "", err } return c, nil } func FanRPM() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata fanrpm | xargs | tr -s ' '`) if err != nil { return "", err } return c, nil } func FanPercent() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata fan | xargs | tr -s ' '`) if err != nil { return "", err } return c, nil } func Hash() (float64, error) { c, err := runScript(`tail -10 /var/run/ethos/miner_hashes.file | sort -V | tail -1 | tr ' ' '\n' | awk '{sum += $1} END {print sum}'`) if err != nil { return -1, err } return strconv.ParseFloat(c, 64) } func MinerHashes() (string, error) { c, err := runScript(`tail -10 /var/run/ethos/miner_hashes.file | sort -V | tail -1`) if err != nil { return "", err } return c, nil } func GPUModels() (string, error) { c, err := readFile("/var/run/ethos/gpulist.file") if err != nil { return "", err } return c, nil } func Bioses() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata bios | xargs | tr -s ' '`) if err != nil { return "", err } return c, err } func DefaultCore() (string, error) { c, err := readFile("/var/run/ethos/defaultcore.file") if err != nil { return "", err } return c, nil } func DefaultMem() (string, error) { c, err := readFile("/var/run/ethos/defaultmem.file") if err != nil { return "", err } return c, nil } func VRAMSize() (string, error) { c, err := readFile("/var/run/ethos/vrams.file") if err != nil { return "", err } return c, nil } func Core() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata core | xargs | tr -s ' '`) if err != nil { return "", err } return c, nil } func Mem() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata mem | xargs | tr -s ' '`) if err != nil { return "", err } return c, nil } func MemStates() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata memstate | xargs | tr -s ' '`) if err != nil { return "", err } return c, nil } func MemInfo() (string, error) { c, err := readFile("/var/run/ethos/meminfo.file") if err != nil { return "", err } return c, nil } func Voltage() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata voltage | xargs | tr -s ' '`) if err != nil { return "", err } return c, nil } func OverheatedGPU() (string, error) { c, err := readFile("/var/run/ethos/overheatedgpu.file") if err != nil { return "", err } return c, nil } func Throttled() (string, error) { c, err := readFile("/var/run/ethos/throttled.file") if err != nil { return "", err } return c, nil } func Powertune() (string, error) { c, err := runScript(`/opt/ethos/sbin/ethos-readdata powertune | xargs | tr -s ' '`) if err != nil { return "", err } return c, nil } func runScript(cmdStr string) (string, error) { out, err := exec.Command("bash", "-c", cmdStr).Output() return strings.TrimSpace(string(out)), err } func readFile(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { return "", err } return strings.TrimSpace(string(b)), nil }
package fastrbac // A trust is a list of permissions for a holder on an object that it isn't owner for. type Trust struct { HolderId int64 HolderType string ObjectId int64 ObjectType string Permissions []string } // A role defines what permissions that a holder has on objects that are owned by another holder type Role struct { Title string HolderIds []int64 RoleTargetId int64 } func HasPermission(repository Repository, owner Owner, object Object, access string) bool { // Owner always has full permission to the object if object.GetOwner() == owner.GetID() { return true } trust, _ := repository.GetTrust(owner, object) if trust != nil { for _, permission := range trust.Permissions { if permission == access { return true } } } return false } func GrantPermission(repository Repository, owner Owner, object Object, access string) error { if HasPermission(repository, owner, object, access) { return nil } _, err := repository.AddPermission(owner, object, access) return err } func GetTrustsByObjectType(repository *Repository, owner Owner, objectType string) { return }
package main import "fmt" import "os" import "strings" import "io/ioutil" import "path/filepath" import "time" import "syscall" import "golang.org/x/crypto/ssh/terminal" import "gopkg.in/src-d/go-git.v4" import gitconfig "gopkg.in/src-d/go-git.v4/config" import "gopkg.in/src-d/go-git.v4/plumbing/object" import "gopkg.in/src-d/go-git.v4/plumbing/transport" import "gopkg.in/src-d/go-git.v4/plumbing/transport/http" func Deploy(config *Config) { config.ValidateForDeploy() if config.DeployToGithub != "" { deployToGithub(config) } // TODO: more deployment options } func deployToGithub(config *Config) { // prompt for password when using https var auth *http.BasicAuth if strings.HasPrefix(config.DeployToGithub, "https:") { auth = getAuth("github", config.GithubUsername, "GITHUB_USERNAME", config.GithubPassword, "GITHUB_PASSWORD") } dir, err := ioutil.TempDir("", "petrify-deploy-") checkError(err) defer os.RemoveAll(dir) repo, err := git.PlainClone(dir, false, &git.CloneOptions{ URL: config.DeployToGithub, Progress: os.Stdout, Auth: auth, }) if err != transport.ErrEmptyRemoteRepository { checkError(err) } else { repo, err = git.PlainInit(dir, false) checkError(err) _, err = repo.CreateRemote(&gitconfig.RemoteConfig{ Name: "origin", URLs: []string{config.DeployToGithub}, }) checkError(err) } tree, err := repo.Worktree() checkError(err) tree.RemoveGlob("*") CopyDir(config.BuildDir, dir) if len(config.Path404) > 0 && config.Path404 != "/404.html" { // TODO: github expects the filename to be 404.html } if len(config.CNAME) > 0 { checkError(ioutil.WriteFile(filepath.Join(dir, "CNAME"), []byte(config.CNAME+"\n"), FILE_BITMASK)) tree.Add("CNAME") } files, err := ioutil.ReadDir(config.BuildDir) checkError(err) for _, file := range files { if !strings.HasPrefix(file.Name(), ".") { tree.Add(file.Name()) } } status, err := tree.Status() checkError(err) if len(status) == 0 { info("Nothing to commit") return } _, err = tree.Commit(time.Now().Format("petrify commit @ "+time.ANSIC), &git.CommitOptions{ Author: &object.Signature{ Name: "Petrify", Email: "", When: time.Now(), }, }) checkError(err) checkError(repo.Push(&git.PushOptions{ RemoteName: "origin", Progress: os.Stdout, Auth: auth, })) } func getAuth(siteName, username, usernameEnv, password, passwordEnv string) *http.BasicAuth { if username == "" { username = os.Getenv(usernameEnv) } if username == "" { fmt.Printf("%s username: ", siteName) username = strings.TrimRight(ReadLine(), "\r\n") } if password == "" { password = os.Getenv(passwordEnv) } if password == "" { fmt.Printf("%s password: ", siteName) passwordBytes, err := terminal.ReadPassword(int(syscall.Stdin)) checkError(err) password = string(passwordBytes) } return &http.BasicAuth{ Username: username, Password: password, } }
package session import ( "fmt" "go/internal/pkg/api/app/request" ) func (uc *sessionUsecase) FindDetailUseCase(req request.SessionRequest) (interface{}, error) { criteria := map[string]interface{}{ "id": req.ID, } session, err := uc.sessionRepo.FindOneBy(criteria) if err != nil { return nil, fmt.Errorf("get data failed: %v", err) } if session.ID == 0 { return nil, fmt.Errorf("session data doesn't exist") } return session, nil }
package services import ( "strings" "time" "github.com/ne7ermore/gRBAC/common" "github.com/ne7ermore/gRBAC/plugin" ) type perMap map[string]plugin.Permission type Role struct { Id string `json:"id"` Name string `json:"name"` Permissions perMap `json:"permissions"` CreateTime time.Time `json:"createTime"` UpdateTime time.Time `json:"updateTime"` } func NewRoleFromModel(r plugin.Role, pp plugin.PermissionPools) *Role { _map := make(perMap) for _, p := range strings.Split(r.GetPermissions(), common.MongoRoleSep) { // skip empty str while m.Permissions is "" if p == "" { continue } if _, found := _map[p]; found { continue } if perm, err := pp.Get(p); err == nil { _map[p] = perm } } return &Role{ Id: r.Getid(), Name: r.GetName(), Permissions: _map, CreateTime: r.GetCreateTime(), UpdateTime: r.GetUpdateTime(), } } func CreateRole(name string, rp plugin.RolePools, pp plugin.PermissionPools) (*Role, error) { id, err := rp.New(name) if err != nil { return nil, err } mr, err := GetRoleById(id, rp, pp) if err != nil { return nil, err } common.Get().NewRole(common.NewStdRole(id)) return mr, nil } func GetRoleById(id string, rp plugin.RolePools, pp plugin.PermissionPools) (*Role, error) { mr, err := rp.Get(id) if err != nil { return nil, err } return NewRoleFromModel(mr, pp), nil } func UpdateRole(id string, update map[string]string, rp plugin.RolePools, pp plugin.PermissionPools) (*Role, error) { if err := rp.Update(id, update); err != nil { return nil, err } return GetRoleById(id, rp, pp) } func Assign(rid, pid string) error { auth := common.Get() p, err := auth.GetPerm(pid) if err != nil { return err } r, err := auth.GetRole(rid) if err != nil { return err } return auth.Assign(r, p) } func Revoke(rid, pid string) error { auth := common.Get() p, err := auth.GetPerm(pid) if err != nil { return err } r, err := auth.GetRole(rid) if err != nil { return err } return auth.Revoke(r, p) } func GetRoles(skip, limit int, field string, rp plugin.RolePools, pp plugin.PermissionPools) ([]*Role, error) { rs, err := rp.Gets(skip, limit, field) if err != nil { return nil, err } roles := make([]*Role, 0, limit) for _, r := range rs { roles = append(roles, NewRoleFromModel(r, pp)) } return roles, nil } // get role from db by role name func GetRoleByName(name string, r plugin.RolePools, pp plugin.PermissionPools) (*Role, error) { rr, err := r.GetByName(name) if err != nil { return nil, err } return NewRoleFromModel(rr, pp), nil } func GetRolesCount(rp plugin.RolePools) int { return rp.Counts() }
package core import ( "strconv" ) type PriceTarget struct { Operator string Value float64 } func (t PriceTarget) Test(price float64) bool { switch t.Operator { case "+": return price > t.Value case "-": return price < t.Value } return false } // Expected format: "10+,5-, etc" func convertTargets(rawTargets []string) []PriceTarget { targets := make([]PriceTarget, len(rawTargets)) for index, rawTarget := range rawTargets { lastIndex := len(rawTarget) - 1 operator := rawTarget[lastIndex:] rawValue := rawTarget[:lastIndex] value, _ := strconv.ParseFloat(rawValue, 64) targets[index] = PriceTarget{ Operator: operator, Value: value, } } return targets }
package lib import ( "golang.org/x/crypto/bcrypt" ) func HashPassword(password string) string { hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { panic(err) } return string(hash) } func VerifyPassword(hashedPassword, password string) (bool, error) { err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) if err != nil { if err == bcrypt.ErrMismatchedHashAndPassword { return false, err } return false, err } return true, nil }
package lruCache import ( "bytes" "container/list" "errors" "fmt" "github.com/cockroachdb/pebble" "log" "sync" ) // https://github.com/hashicorp/golang-lru/blob/master/simplelru/lru.go // https://github.com/golang/groupcache/blob/master/lru/lru.go // https://github.com/hashicorp/golang-lru/blob/master/lru.go type Cache struct { // The amount of disk space you're willing to let this take up MaxSizeInBytes uint64 // Counts the number of sets. Used to only call file.Stat() every certain number of sets hitCounter int // Clears this many items from the cache. Gives time for cache to regrow and then // re-shrink aggressively, rather than deleting on every set RemoveThisManyItemsFromTheCache int // Location of the DB FileLocation string // To move an accessed element to the front, this stores the actual list element // Therefore, when we look for it, we're calling the actual element // The string key is the same key for the list element AND the key set into the // bbolt database listOfEvictList map[string]*list.Element // All of the items set through the interface in this package. // They are all available for eviction at any time. evictList *list.List lock sync.RWMutex } // Creates a new cache with a specified byte size func NewCache(maxSizeInBytes uint64, removeThisManyItemsFromTheCache int, fileLocation string) (*Cache, error) { c := &Cache{ MaxSizeInBytes: maxSizeInBytes, hitCounter: 0, RemoveThisManyItemsFromTheCache: removeThisManyItemsFromTheCache, FileLocation: fileLocation, listOfEvictList: make(map[string]*list.Element), evictList: list.New(), lock: sync.RWMutex{}, } return c, nil } var nilError = errors.New("nil") // Retrieves the item // If it exists, pushes the item to the front of the cache func (c *Cache) Get(key []byte, db *pebble.DB) (value []byte, err error) { val, closer, err := db.Get(key) if err != nil { return nil, err } if err := closer.Close(); err != nil { return nil, err } if val == nil { return nil, nilError } c.lock.Lock() c.moveItemToFront(key) c.lock.Unlock() return val, nil } // Public Interface for setting cache item // Recalculates the average size of the documents // Evicts if the size of the cache is too large // Updates the current size of the cache // Adds the key and value to the bolt bucket // Adds the key to the list of keys // Adds the key to evict list func (c *Cache) Set(key []byte, val []byte, db *pebble.DB) error { c.lock.Lock() c.moveItemToFront(key) c.hitCounter = c.hitCounter + 1 c.lock.Unlock() // Manage clearing the cache only once every 20 sets // Adjust this number back to 20 after debugging for better // performance if c.hitCounter%1 == 0 { tableSize := getTableSize(db) if tableSize > c.MaxSizeInBytes { err := c.evictFromCache(db) if err != nil { log.Fatal(err) } } } err := db.Set(key, val, pebble.Sync) if err != nil { return err } return nil } func getTableSize(db *pebble.DB) uint64 { tables := db.SSTables() var size uint64 for _, table := range tables { for _, info := range table { size = size + info.Size } } return size } // Used to add to the list, as the list takes in a raw interface type listEl struct { val interface{} } // After access, the item is retrieved from the "list of the list" if it exists // And added to the front // If it doesn't exist yet, it is added to the "list of the list" and pushed to the // front func (c *Cache) moveItemToFront(val []byte) { // Move an existing key to the front if ent, ok := c.listOfEvictList[string(val)]; ok { c.evictList.MoveToFront(ent) //fmt.Println("debug spot") } else { ent := listEl{val: val} newEntry := c.evictList.PushFront(ent) c.listOfEvictList[string(val)] = newEntry //fmt.Println("debug spot") } } // Used for bulk removing keys func (c *Cache) RemoveSpecificItemsFromCache(db *pebble.DB, items [][]byte) error { panic("oof") } // Removes from the evict list // Removes from the list of the evict list // Removes from the bolt bucket // WARNING: If this is called for an existing database, this will not work. // This cache only works for fresh databases because func (c *Cache) evictFromCache(db *pebble.DB) error { c.lock.Lock() valuesRemoved := 0 valsToRemove := [][]byte{} elementsToRemove := []*list.Element{} for e := c.evictList.Back(); e != nil; e = e.Prev() { // Item Value is stored as a listEl. //The val in there (an interface) is a byte array val := e.Value.(listEl).val.([]byte) valsToRemove = append(valsToRemove, val) elementsToRemove = append(elementsToRemove, e) // Alerts if a key is being deleted if bytes.Equal(val, []byte("a")) { fmt.Println("Deleting A") } delete(c.listOfEvictList, string(val)) valuesRemoved += 1 if valuesRemoved >= c.RemoveThisManyItemsFromTheCache { break } } for _, val := range elementsToRemove { c.evictList.Remove(val) } c.lock.Unlock() for _, val := range valsToRemove { err := db.Delete(val, pebble.Sync) if err != nil { log.Fatal(err) } } return nil }
package day5 import ( loader "aoc/dataloader" "aoc/test" "testing" ) func TestPart1(t *testing.T) { cases := []test.Case[[]string, string]{ {loader.Load("sample.txt"), "CMZ"}, {loader.Load("input.txt"), "MQSHJMWNH"}, } err := test.Execute(cases, Part1) if err != nil { t.Error(err) } } func TestPart2(t *testing.T) { cases := []test.Case[[]string, string]{ {loader.Load("sample.txt"), "MCD"}, {loader.Load("input.txt"), "LLWJRBHVZ"}, } err := test.Execute(cases, Part2) if err != nil { t.Error(err) } }
package main /** 最长有效括号 给定一个只包含 `'('` 和 `')'` 的字符串,找出最长的包含有效括号的子串的长度。 示例1: ``` 输入: "(()" 输出: 2 解释: 最长有效括号子串为 "()" ``` 示例2: ``` 输入: ")()())" 输出: 4 解释: 最长有效括号子串为 "()()" ``` */ /** 栈 + 辅助数组 */ func LongestValidParentheses(s string) int { var stack []int res := make([]bool, len(s)) for i := 0; i < len(s); i++ { if s[i] == '(' { stack = append(stack, i) } else if len(stack) > 0 { idx := stack[len(stack)-1] stack = stack[:len(stack)-1] res[idx], res[i] = true, true res[i] = true } } max, count := 0, 0 for i := 0; i < len(res); i++ { if res[i] { count++ } else { max = maxN(max, count) count = 0 } } max = maxN(max, count) return max } func maxN(a, b int) int { if a > b { return a } return b }
//lorawanWrapper.go package main import "C" import ( "bytes" "fmt" "os" "time" "unsafe" "math" . "github.com/matiassequeira/lorawan" log "github.com/sirupsen/logrus" ) //export marshalJsonToPHYPayload func marshalJsonToPHYPayload(jsonPointer *C.char, keyPointer *C.char, nwkskeyPointer *C.char) *C.char { var jsonStr string = C.GoString(jsonPointer) var key string = C.GoString(keyPointer) var nwkskey string = C.GoString(nwkskeyPointer) b64 := parseJSONtoPHY(jsonStr, key, nwkskey) return C.CString(b64) } //export getJoinEUI func getJoinEUI(dataPointer *C.char) *C.char { var dataBytes string = C.GoString(dataPointer) var phy PHYPayload if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { fmt.Println(err) fmt.Println("Join request data: " + dataBytes) return C.CString("Error") } jrPL, ok := phy.MACPayload.(*JoinRequestPayload) if !ok { fmt.Println("MACPayload must be a *JoinRequestPayload") return C.CString("Error") } return C.CString(fmt.Sprintf("%v", jrPL.JoinEUI)) } //export getMType func getMType(dataPointer *C.char) C.int { var dataBytes string = C.GoString(dataPointer) var phy PHYPayload if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { fmt.Println("Unmarshall error with PHYPayload trying to get MType") return -1 } return C.int(phy.MHDR.MType) } //export getMajor func getMajor(dataPointer *C.char) C.int { var dataBytes string = C.GoString(dataPointer) var phy PHYPayload if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { fmt.Println("Unmarshall error with PHYPayload trying to get major") return -1 } return C.int(phy.MHDR.Major) } //export getCounter func getCounter(dataPointer *C.char) C.int { var dataBytes string = C.GoString(dataPointer) var phy PHYPayload if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { fmt.Println("Unmarshall error with PHYPayload") return C.int(-1) } macPL, ok := phy.MACPayload.(*MACPayload) if ok { return C.int(macPL.FHDR.FCnt) } else { fmt.Println("Couldn't get counter") return C.int(-1) } } //export getDevNonce func getDevNonce(dataPointer *C.char) C.int { var dataBytes string = C.GoString(dataPointer) var phy PHYPayload if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { fmt.Println(err) fmt.Println("Join request data: " + dataBytes) return C.int(-1) } jrPL, ok := phy.MACPayload.(*JoinRequestPayload) if !ok { fmt.Println("MACPayload must be a *JoinRequestPayload") return C.int(-1) } //return C.CString(fmt.Sprintf("%v", jrPL.DevNonce)) return C.int(jrPL.DevNonce) } //export generateSessionKeysFromJoins func generateSessionKeysFromJoins(joinRequestPointer *C.char, JoinAcceptPointer *C.char, appKeyPointer *C.char) *C.char { var key AES128Key var joinEui EUI64 var joinReq PHYPayload var joinAcc PHYPayload key.UnmarshalText([]byte(C.GoString(appKeyPointer))) if err := joinReq.UnmarshalText([]byte(C.GoString(joinRequestPointer))); err != nil { fmt.Println(err) return C.CString("") } jrPL, ok := joinReq.MACPayload.(*JoinRequestPayload) if !ok { fmt.Println("MACPayload must be a *JoinRequestPayload") return C.CString("") } if err := joinAcc.UnmarshalText([]byte(C.GoString(JoinAcceptPointer))); err != nil { fmt.Println(err) return C.CString("") } if err := joinAcc.DecryptJoinAcceptPayload(key); err != nil { fmt.Println("Error decrypting JoinAccept: ", err) return C.CString("") } jaPL, ok := joinAcc.MACPayload.(*JoinAcceptPayload) if !ok { fmt.Println("MACPayload must be a *JoinAcceptPayload") return C.CString("") } nwkSKey, err := getFNwkSIntKey(false, key, jaPL.HomeNetID, joinEui, jaPL.JoinNonce, jrPL.DevNonce) if err != nil { fmt.Println("Error when generating the NwkSKey ", err) return C.CString("") } appSkey, err := getAppSKey(false, key, jaPL.HomeNetID, joinEui, jaPL.JoinNonce, jrPL.DevNonce) if err != nil { fmt.Println("Error when generating the AppSKey: ", err) return C.CString("") } nKey, _ := nwkSKey.MarshalText() aKey, _ := appSkey.MarshalText() return C.CString(fmt.Sprintf("{\"nwkSKey\": \"%s\", \"appSKey\": \"%s\"}", string(nKey), string(aKey))) } //export getDevAddrFromMACPayload func getDevAddrFromMACPayload(dataPointer *C.char) *C.char { var dataBytes string = C.GoString(dataPointer) var phy PHYPayload if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { fmt.Println("Unmarshall error with PHYPayload") return C.CString("Error") } macPL, ok := phy.MACPayload.(*MACPayload) if ok { return C.CString(fmt.Sprintf("%v", macPL.FHDR.DevAddr)) } else { fmt.Println("Couldn't get devAddr") return C.CString("") } } //export getDevAddr func getDevAddr(appKeyPointer *C.char, dataPointer *C.char) *C.char { var dataBytes string = C.GoString(dataPointer) var key AES128Key var phy PHYPayload if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { fmt.Println("Unmarshall error with PHYPayload") return C.CString("Error") } if err := key.UnmarshalText([]byte(C.GoString(appKeyPointer))); err != nil { fmt.Println("Unmarshall error with AppKey") return C.CString("Error") } if err := phy.DecryptJoinAcceptPayload(key); err != nil { fmt.Println("getDevAddr(): Error decrypting PHYPayload") return C.CString("Error") } jaPL, ok := phy.MACPayload.(*JoinAcceptPayload) if ok { return C.CString(fmt.Sprintf("%v", jaPL.DevAddr)) } return C.CString("Error") } //export getDevEUI func getDevEUI(dataPointer *C.char) *C.char { var dataBytes string = C.GoString(dataPointer) return C.CString(returnDevEUI(dataBytes)) } //export generateValidMIC func generateValidMIC(dataPointer *C.char, newKeyPointer *C.char, jaKeyPointer *C.char) *C.char { var dataBytes string = C.GoString(dataPointer) var newKey string = C.GoString(newKeyPointer) var jaKey string = C.GoString(jaKeyPointer) return C.CString(signPacket(dataBytes, newKey, jaKey)) } func returnDevEUI(dataBytes string) string { var phy PHYPayload if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { fmt.Println(err) fmt.Println("Join request data: " + dataBytes) return "" } jrPL, ok := phy.MACPayload.(*JoinRequestPayload) if !ok { fmt.Println("MACPayload must be a *JoinRequestPayload") return "Error" } return fmt.Sprintf("%v", jrPL.DevEUI) } func reverseArray(array []byte) []byte { for i, j := 0, len(array)-1; i < j; i, j = i+1, j-1 { array[i], array[j] = array[j], array[i] } return array } //export testAppKeysWithJoinRequest func testAppKeysWithJoinRequest(appKeysPointer **C.char, keysLen C.int, joinRequestDataPointer *C.char, generateKeys C.int) *C.char { var dataBytes string = C.GoString(joinRequestDataPointer) var phy PHYPayload var testCounter int64 = 0 var key AES128Key var foundKeys string = "" setLogLevel() if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { log.Error("JoinRequest data: ", dataBytes, "Error: ", err) return C.CString(foundKeys) } /********************************************************************* Form possible keys using AppEUI+JoinEUI / JoinEUI/AppEUI combination ********************************************************************/ jrPL, ok := phy.MACPayload.(*JoinRequestPayload) if !ok { fmt.Println("MACPayload must be a *JoinRequestPayload") return C.CString("Error") } joinEUI, _ := jrPL.JoinEUI.MarshalBinary() devEUI, _ := jrPL.DevEUI.MarshalBinary() vendorsKeys := [][]byte{append(joinEUI, devEUI...), append(devEUI, joinEUI...)} log.Debug("DevEUI: ", devEUI, "AppEUI: ", joinEUI) for _, vendorKey := range vendorsKeys { if err := key.UnmarshalBinary(vendorKey); err != nil { log.Error("Unmarshall error with AppKey: ", vendorKey, err) } result, err := testAppKeyWithJoinRequest(key, phy, &testCounter) if err != nil { log.Error("Error with JoinRequest :", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } } /******************************************************************** Test keys given in keys file ********************************************************************/ length := int(keysLen) var temp *C.char tmpslice := (*[(math.MaxInt32 -1)/unsafe.Sizeof(temp)]*C.char)(unsafe.Pointer(appKeysPointer))[:length:length] for _, s := range tmpslice { element := C.GoString(s) if err := key.UnmarshalText([]byte(element)); err != nil { log.Error("Unmarshall error with AppKey: ", element, err) } result, err := testAppKeyWithJoinRequest(key, phy, &testCounter) if err != nil { log.Error("Error with JoinRequest :", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } } if int(generateKeys) != 0 { start := time.Now() var i uint8 var j uint8 /******************************************************************** Try with hashes MD5, SHA-1, SHA-2, SHA-3 of AppEUI, DevEUI, AppEUI+DevEUI and DevEUI+AppEUI. Truncate before and after 16 bytes ********************************************************************/ euisArray := [][]byte{joinEUI, devEUI, append(joinEUI, devEUI...), append(devEUI, joinEUI...)} cryptoHashes := generateHashes(euisArray) for _, hash := range cryptoHashes { if err := key.UnmarshalBinary(hash); err != nil { log.Error("Unmarshall error with AppKey: ", hash, err) } result, err := testAppKeyWithJoinRequest(key, phy, &testCounter) if err != nil { log.Error("Error with JoinRequest :", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } } /******************************************************************** Try with DevEUI[0] + AppEUI[0] + DevEUI[1] .., AppEUI[0] + DevEUI[0] + AppEUI[1] + .., and vice-versa ********************************************************************/ devEuiAppEui := make([]byte, 16, 16) devEuiAppEui[0], devEuiAppEui[2], devEuiAppEui[4], devEuiAppEui[6], devEuiAppEui[8], devEuiAppEui[10], devEuiAppEui[12], devEuiAppEui[14] = devEUI[0], devEUI[1], devEUI[2], devEUI[3], devEUI[4], devEUI[5], devEUI[6], devEUI[7] devEuiAppEui[1], devEuiAppEui[3], devEuiAppEui[5], devEuiAppEui[7], devEuiAppEui[9], devEuiAppEui[11], devEuiAppEui[13], devEuiAppEui[15] = joinEUI[0], joinEUI[1], joinEUI[2], joinEUI[3], joinEUI[4], joinEUI[5], joinEUI[6], joinEUI[7] appEuiDevEui := make([]byte, 16, 16) appEuiDevEui[0], appEuiDevEui[2], appEuiDevEui[4], appEuiDevEui[6], appEuiDevEui[8], appEuiDevEui[10], appEuiDevEui[12], appEuiDevEui[14] = joinEUI[0], joinEUI[1], joinEUI[2], joinEUI[3], joinEUI[4], joinEUI[5], joinEUI[6], joinEUI[7] appEuiDevEui[1], appEuiDevEui[3], appEuiDevEui[5], appEuiDevEui[7], appEuiDevEui[9], appEuiDevEui[11], appEuiDevEui[13], appEuiDevEui[15] = devEUI[0], devEUI[1], devEUI[2], devEUI[3], devEUI[4], devEUI[5], devEUI[6], devEUI[7] keysToTest := [][]byte{devEuiAppEui, appEuiDevEui, reverseArray(devEuiAppEui), reverseArray(appEuiDevEui)} for _, euiKey := range keysToTest { if err := key.UnmarshalBinary(euiKey); err != nil { log.Error("Unmarshall error with AppKey (DevEUI/AppEUI combination): ", euiKey, err) } result, err := testAppKeyWithJoinRequest(key, phy, &testCounter) if err != nil { log.Error("Error with JoinRequest :", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } } /******************************************************************** Try with the DevEUI or the AppEUI + 8 more repeated bytes. Do the same with these bytes at first ********************************************************************/ for i = 0; i <= 255; i++ { var repeatedBytes = []byte{i, i, i, i, i, i, i, i} euiKeys := [][]byte{append(joinEUI, repeatedBytes...), append(devEUI, repeatedBytes...), append(repeatedBytes, devEUI...), append(repeatedBytes, joinEUI...)} for _, euiKey := range euiKeys { if err := key.UnmarshalBinary(euiKey); err != nil { log.Error("Unmarshall error with AppKey (*EUI+bytes): ", euiKey, err) } result, err := testAppKeyWithJoinRequest(key, phy, &testCounter) if err != nil { log.Error("Error with JoinRequest :", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } } if i == 255 { break } } /********************************************************************/ // key1 variates the first byte and the last fifteeen bytes var key1 = make([]byte, 16, 16) // key2 variates even and odd bytes position equally var key2 = make([]byte, 16, 16) // key3 has the first 14 bytes in 0 and changes the last 2 var key3 = make([]byte, 16, 16) key3[0], key3[1], key3[2], key3[3], key3[4], key3[5], key3[6], key3[7], key3[8], key3[9], key3[10], key3[11], key3[12], key3[13] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /********************************************************************/ for i = 0; i <= 255; i++ { key1[0] = i key2[0], key2[2], key2[4], key2[6], key2[8], key2[10], key2[12], key2[14] = i, i, i, i, i, i, i, i key3[14] = i for j = 0; j <= 255; j++ { key1[2], key1[4], key1[6], key1[8], key1[10], key1[12], key1[14], key1[1], key1[3], key1[5], key1[7], key1[9], key1[11], key1[13], key1[15] = j, j, j, j, j, j, j, j, j, j, j, j, j, j, j key2[1], key2[3], key2[5], key2[7], key2[9], key2[11], key2[13], key2[15] = j, j, j, j, j, j, j, j key3[15] = j if err := key.UnmarshalBinary(key1); err != nil { log.Error("Unmarshall error with AppKey: ", key1, err) } // Testing key1 result, err := testAppKeyWithJoinRequest(key, phy, &testCounter) if err != nil { log.Error("Error with JoinRequest with data: ", dataBytes, " Error: ", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } if err := key.UnmarshalBinary(key2); err != nil { log.Error("Unmarshall error with AppKey: ", key2, err) } // Testing key2 result, err = testAppKeyWithJoinRequest(key, phy, &testCounter) if err != nil { log.Error("Error with JoinRequest with data: ", dataBytes, " Error: ", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } if err := key.UnmarshalBinary(key3); err != nil { log.Error("Unmarshall error with AppKey: ", key1, err) } // Testing key3 result, err = testAppKeyWithJoinRequest(key, phy, &testCounter) if err != nil { log.Error("Error with JoinRequest with data: ", dataBytes, " Error: ", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } // Added some breaks to avoid uint8 overflow if j == 255 { break } } if i == 255 { break } } elapsed := time.Since(start) log.Debug("Bruteforcing the JoinRequest took:", elapsed, ". Keys tested: ", testCounter) } if len(foundKeys) > 0 { return C.CString(foundKeys) } else { log.Debug("Key not found for JoinRequest with DevEui: ", returnDevEUI(dataBytes), " with data: ", dataBytes, " \n") return C.CString("") } } func testAppKeyWithJoinRequest(key AES128Key, phy PHYPayload, counter *int64) (string, error) { *counter++ result, err := phy.ValidateUplinkJoinMIC(key) if err != nil { log.Error("Error validating JoinRequest MIC: ", err) return "", nil } if result { foundKey, _ := key.MarshalText() return string(foundKey), nil } else { return "", nil } } //export testAppKeysWithJoinAccept func testAppKeysWithJoinAccept(appKeysPointer **C.char, keysLen C.int, joinAcceptDataPointer *C.char, generateKeys C.int) *C.char { var dataBytes string = C.GoString(joinAcceptDataPointer) var phy PHYPayload var key AES128Key var decryptCounter int64 = 0 var foundKeys string = "" setLogLevel() if err := phy.UnmarshalText([]byte(dataBytes)); err != nil { log.Error("Error with Join accept with data: "+dataBytes, ". Error: ", err) return C.CString(foundKeys) } length := int(keysLen) var temp *C.char tmpslice := (*[(math.MaxInt32 - 1)/unsafe.Sizeof(temp)]*C.char)(unsafe.Pointer(appKeysPointer))[:length:length] for _, s := range tmpslice { element := C.GoString(s) if err := key.UnmarshalText([]byte(element)); err != nil { log.Error("Unmarshall error with AppKey:", element, ".", err) } result, err := testAppKeyWithJoinAccept(key, phy, &decryptCounter) if err != nil { log.Error("Error with JoinAccept with data: ", dataBytes, " Error: ", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } } if int(generateKeys) != 0 { start := time.Now() // key1 variates the first byte and the last fifteeen bytes var key1 = make([]byte, 16, 16) // key2 variates even and odd bytes position equally var key2 = make([]byte, 16, 16) // key3 has the first 14 bytes in 0 and changes the last 2 var key3 = make([]byte, 16, 16) key3[0], key3[1], key3[2], key3[3], key3[4], key3[5], key3[6], key3[7], key3[8], key3[9], key3[10], key3[11], key3[12], key3[13] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 var i uint8 var j uint8 for i = 0; i <= 255; i++ { key1[0] = i key2[0], key2[2], key2[4], key2[6], key2[8], key2[10], key2[12], key2[14] = i, i, i, i, i, i, i, i key3[14] = i for j = 0; j <= 255; j++ { key1[2], key1[4], key1[6], key1[8], key1[10], key1[12], key1[14], key1[1], key1[3], key1[5], key1[7], key1[9], key1[11], key1[13], key1[15] = j, j, j, j, j, j, j, j, j, j, j, j, j, j, j key2[1], key2[3], key2[5], key2[7], key2[9], key2[11], key2[13], key2[15] = j, j, j, j, j, j, j, j key3[15] = j if err := key.UnmarshalBinary(key1); err != nil { log.Error("Unmarshall error with AppKey: ", key1, err) } // Testing key1 result, err := testAppKeyWithJoinAccept(key, phy, &decryptCounter) if err != nil { log.Error("Error with JoinAccept with data: ", dataBytes, " Error: ", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } if err := key.UnmarshalBinary(key2); err != nil { log.Error("Unmarshall error with AppKey: ", key2, err) } // Testing key2 result, err = testAppKeyWithJoinAccept(key, phy, &decryptCounter) if err != nil { log.Error("Error with JoinAccept with data: ", dataBytes, " Error: ", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } if err := key.UnmarshalBinary(key3); err != nil { log.Error("Unmarshall error with AppKey: ", key1, err) } // Testing key3 result, err = testAppKeyWithJoinAccept(key, phy, &decryptCounter) if err != nil { log.Error("Error with JoinAccept with data: ", dataBytes, " Error: ", err) return C.CString(foundKeys) } else if len(result) > 0 { foundKeys += result + " " } // Added some breaks to avoid uint8 ovdrflow if j == 255 { break } } if i == 255 { break } } elapsed := time.Since(start) log.Debug("Bruteforcing the JoinAccept took:", elapsed) } if len(foundKeys) > 0 { return C.CString(foundKeys) } else { log.Debug("Key not found for JoinAccept with data: ", dataBytes, ". Keys tested: ", decryptCounter, " \n") return C.CString("") } } func testAppKeyWithJoinAccept(key AES128Key, phy PHYPayload, counter *int64) (string, error) { *counter++ if err := phy.DecryptJoinAcceptPayload(key); err != nil { // Here we return nil instead of the error since this error is caused by a wrong key return "", nil } joinEUI := EUI64{8, 7, 6, 5, 4, 3, 2, 1} devNonce := DevNonce(258) result, err := phy.ValidateDownlinkJoinMIC(JoinRequestType, joinEUI, devNonce, key) if err != nil { // Here we return nil instead of the error since this error is caused by a wrong key //fmt.Println("Error validating Join MIC: ", err) return "", nil } if result == true { foundKey, _ := key.MarshalText() return string(foundKey), nil } else { return "", nil } } //export printPHYPayload func printPHYPayload(phyPointer *C.char, keyPointer *C.char) *C.char { var buffer bytes.Buffer var phyBytes string = C.GoString(phyPointer) var key AES128Key var phy PHYPayload setLogLevel() if err := phy.UnmarshalText([]byte(phyBytes)); err != nil { log.Error("Unmarshal error with PHYPayload: ", phyBytes, " Error: ", err) return C.CString(fmt.Sprintln("")) } if keyPointer != nil { key.UnmarshalText([]byte(C.GoString(keyPointer))) if phy.MHDR.MType == UnconfirmedDataUp || phy.MHDR.MType == ConfirmedDataUp || phy.MHDR.MType == UnconfirmedDataDown || phy.MHDR.MType == ConfirmedDataDown { if err := phy.DecryptFRMPayload(key); err != nil { log.Error("Cannot decrypt FRMPayload:", err) } } else if phy.MHDR.MType == JoinAccept { if err := phy.DecryptJoinAcceptPayload(key); err != nil { log.Error("Cannot decrypt Join Accept:", err) } } } _, ok := phy.MACPayload.(*MACPayload) if ok { if err := phy.DecodeFOptsToMACCommands(); err != nil { log.Error("Error decoding FOpts:", err) } } phyJSON, err := phy.MarshalJSON() if err != nil { panic(err) } buffer.WriteString(fmt.Sprintf("%s", string(phyJSON))) return C.CString(buffer.String()) } func setLogLevel() { if env := os.Getenv("ENVIRONMENT"); env == "PROD" { log.SetLevel(log.InfoLevel) } else { log.SetLevel(log.DebugLevel) } } func main() { } // TO BUILD THIS LIBRARY //go build -o lorawanWrapper.so -buildmode=c-shared *.go // DEPENDENCIES //go get github.com/tidwall/sjson //go get github.com/tidwall/gjson //go get github.com/matiassequeira/lorawan
package main import "fmt" func main() { fmt.Println(reverseLeftWords2("abcdefg", 2)) fmt.Println(reverseLeftWords2("lrloseumgh", 6)) } func reverseLeftWords(s string, n int) string { return s[n:] + s[:n] } func reverseLeftWords2(s string, n int) string { bs := []byte(s) reverse := func(left, right int) { for left < right { bs[left], bs[right] = bs[right], bs[left] left++ right-- } } reverse(0, n-1) reverse(n, len(bs)-1) reverse(0, len(bs)-1) return string(bs) } //func reverseLeftWords(s string, n int) string { // b := []byte(s) // // 1. 反转前n个字符 // // 2. 反转第n到end字符 // // 3. 反转整个字符 // reverse(b, 0, n-1) // reverse(b, n, len(b)-1) // reverse(b, 0, len(b)-1) // return string(b) //} //// 切片是引用传递 //func reverse(b []byte, left, right int){ // for left < right{ // b[left], b[right] = b[right],b[left] // left++ // right-- // } //}
package main import ( "github.com/nurblieh/restos/lib" "flag" "fmt" ) var ( address = flag.String("address", "", "Address to geocode.") ) func main() { flag.Parse() ll, e := lib.Geocode(*address) if e != nil { fmt.Println("Error.", e) panic("foo") } fmt.Printf("%v\n", ll) }
package register import ( "github.com/Azer0s/quacktors" "sync" ) var register = make(map[string]*quacktors.Pid) var registerMu = &sync.RWMutex{} //ModifyUnsafe passes both the actual pid-register as well as //the pid-register-mutex to a callback function so they can be //modified directly. This should be used with caution! func ModifyUnsafe(action func(register *map[string]*quacktors.Pid, mu *sync.RWMutex)) { action(&register, registerMu) } //SetPid associates a *quacktors.Pid with a name. func SetPid(name string, pid *quacktors.Pid) { registerMu.Lock() defer registerMu.Unlock() register[name] = pid } //UsePid passes the *quacktors.Pid associated with a name //to a callback function so it can be used safely. func UsePid(name string, action func(pid *quacktors.Pid)) { registerMu.RLock() defer registerMu.RUnlock() action(register[name]) } //ChangePid expects a *quacktors.Pid from a supplier function //so it can safely change the pid-mapping from one *quacktors.Pid //to another. func ChangePid(name string, supplier func() *quacktors.Pid) { registerMu.Lock() defer registerMu.Unlock() register[name] = supplier() } //DeletePid deletes the association from a *quacktors.Pid to a name. func DeletePid(name string) { registerMu.Lock() defer registerMu.Unlock() delete(register, name) }
package command import ( "fmt" "strconv" "strings" "time" "github.com/jixwanwang/jixbot/channel" ) type money struct { cp *CommandPool cash *subCommand stats *subCommand give *subCommand giveAll *subCommand } func (T *money) Init() { T.cash = &subCommand{ command: "!cash", numArgs: 0, cooldown: 200 * time.Millisecond, clearance: channel.VIEWER, } T.stats = &subCommand{ command: "!toponepercent", numArgs: 0, cooldown: 1 * time.Minute, clearance: channel.MOD, } T.give = &subCommand{ command: "!give", numArgs: 2, cooldown: 200 * time.Millisecond, clearance: channel.VIEWER, } T.giveAll = &subCommand{ command: "!giveall", numArgs: 1, cooldown: 1 * time.Minute, clearance: channel.BROADCASTER, } } func (T *money) ID() string { return "money" } func (T *money) Response(username, message string, whisper bool) { if whisper { return } viewer, ok := T.cp.channel.InChannel(username) if !ok { return } clearance := T.cp.channel.GetLevel(username) _, err := T.stats.parse(message, clearance) if err == nil { T.cp.Say(T.calculateRichest()) return } args, err := T.give.parse(message, clearance) if err == nil { amount, _ := strconv.Atoi(args[1]) if amount <= 0 { T.cp.Whisper(username, "Please enter a valid amount.") return } to_viewer, ok := T.cp.channel.InChannel(strings.ToLower(args[0])) if !ok { T.cp.Whisper(username, "That user isn't in the chat.") return } viewer, _ := T.cp.channel.InChannel(username) if clearance != channel.GOD && clearance != channel.BROADCASTER { if viewer.GetMoney() < amount { T.cp.Whisper(username, fmt.Sprintf("You don't have enough %ss", T.cp.channel.Currency)) return } viewer.AddMoney(-amount) } to_viewer.AddMoney(amount) T.cp.Whisper(username, fmt.Sprintf("You gave %s %d %ss!", to_viewer.Username, amount, T.cp.channel.Currency)) T.cp.Whisper(to_viewer.Username, fmt.Sprintf("You received %d %ss from %s!", amount, T.cp.channel.Currency, username)) return } _, err = T.cash.parse(message, clearance) if err == nil { T.cp.Whisper(username, fmt.Sprintf("You have %d %ss in %s's channel", viewer.GetMoney(), T.cp.channel.Currency, T.cp.channel.Username)) return } args, err = T.giveAll.parse(message, clearance) if err == nil { amount, _ := strconv.Atoi(args[0]) T.cp.channel.AddMoney(amount) T.cp.channel.Flush() T.cp.Say(fmt.Sprintf("Everyone gets %d %ss, go nuts!", amount, T.cp.channel.Currency)) } return } func (T *money) calculateRichest() string { counts, err := T.cp.db.HighestCount(T.cp.channel.GetChannelName(), "money") if err != nil { return "" } output := "Richest people: " for _, c := range counts { output = fmt.Sprintf("%s%s - %d %ss, ", output, c.Username, c.Count, T.cp.channel.Currency) } return output[:len(output)-2] }
package models import ( "container/list" ) type EventType int const ( EVENT_JOIN = iota EVENT_LEAVE EVENT_MESSAGE ) type Event struct { Type EventType // JOIN, LEAVE, MESSAGE User string Timestamp int Content string } const wsSize = 20 // Event ws. var ws = list.New() // NewWs saves new event to ws list. func NewWs(event Event) { if ws.Len() >= wsSize { ws.Remove(ws.Front()) } ws.PushBack(event) } // GetEvents returns all events after lastReceived. func GetEvents(lastReceived int) []Event { events := make([]Event, 0, ws.Len()) for event := ws.Front(); event != nil; event = event.Next() { e := event.Value.(Event) if e.Timestamp > int(lastReceived) { events = append(events, e) } } return events }
package main import ( "sort" "testing" ) func TestRespace(t *testing.T) { dict := []string{"abc", "deff", "cccccc"} sort.Slice(dict, func(i, j int) bool { return len(dict[i]) > len(dict[j]) }) }
// Copyright Amazon.com Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 testutil import "github.com/aws-controllers-k8s/dev-tools/pkg/config" // Returns a new config.Config object used for testing purposes. func NewConfig(services ...string) *config.Config { return &config.Config{ Repositories: config.RepositoriesConfig{ Core: []string{ "runtime", "code-generator", }, Services: services, }, Github: config.GithubConfig{ ForkPrefix: "ack-", Username: "ack-bot", }, } }
package demo import ( "fmt" ) func test1() { var a int fmt.Printf("a的内存地址: %p \n", &a) } func test2() { var a *int fmt.Printf("指针变量 a 的内存地址:%p, a 的值:%v \n", &a, a) b := 100 fmt.Printf("变量 b 的内存地址:%p, b 的值:%v \n", &b, b) a = &b fmt.Printf("指针变量 a 的内存地址:%p, a 的值:%v \n", &a, a) } func test3() { b := 100 fmt.Printf("变量 b 的内存地址:%p, b 的值:%v \n", &b, b) a := &b fmt.Printf("指针变量 a 的内存地址:%p, a 的值:%v \n", &a, a) *a = 200 fmt.Printf("修改指针变量 a 后, 内存地址:%p, a 的值:%v, *a:%d \n", &a, a, *a) fmt.Printf("修改指针变量 a 后, 变量 b 的内存地址:%p, b 的值:%v \n", &b, b) } func test4() { a := 100 fmt.Println("变量a的地址:", &a) } func pointArg(a *int) { *a = 100 } func testPointArg() { a := 1 fmt.Println("变量a:", a) pointArg(&a) fmt.Println("传参后变量a:", a) } func Test() { // test1() // test2() // test3() // test4() testPointArg() }
package main import ( "go-mlp/nn" "math/rand" ) func main() { rand.Seed(1) inputs := [][]float64{ []float64{1, 1}, []float64{1, 0}, []float64{0, 1}, []float64{0, 0}, } outputs := [][]float64{ []float64{0}, []float64{1}, []float64{1}, []float64{0}, } mlp := nn.NewNN([]int{2, 1}, 2) mlp.Print() for i := 0; i < 100; i++ { mlp.Train(inputs, outputs, 2.0) } mlp.Print() }
package main import ( "encoding/json" "io" "net/http" "os" "time" "github.com/gorilla/mux" "github.com/sirupsen/logrus" ) // APIContext - provides access to request parameters and other information for the API handler type APIContext interface { Vars() map[string]string WriteJSON(result interface{}) error } // APIHandler - handler which handles request and returns serializable interface or an error type APIHandler func(ctx APIContext) error // RawAPIHandler - handler which directly works with request and response type RawAPIHandler func(w http.ResponseWriter, r *http.Request) error // DefaultAPIContext - provides default JSON-based RESTful API context type DefaultAPIContext struct { request *http.Request writer http.ResponseWriter } // ParseArgs - parses arguments from JSON (for POST/PUT/DELETE) or from URL (for GET) func (c *DefaultAPIContext) Vars() map[string]string { return mux.Vars(c.request) } func (c *DefaultAPIContext) WriteJSON(result interface{}) error { bytes, err := json.Marshal(result) if err != nil { return err } c.writer.Header().Set("Content-Type", "application/json; charset=UTF-8") _, err = io.WriteString(c.writer, string(bytes)) if err != nil { return err } return nil } func openFileLogger() *os.File { logrus.SetFormatter(&logrus.JSONFormatter{}) file, err := os.OpenFile("video_frontend.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666) if err != nil { panic(err) } logrus.SetOutput(file) return file } func newRouter() *mux.Router { router := mux.NewRouter() subrouter := router.PathPrefix("/api/v1").Subrouter() start := time.Now() decorateWithLog := func(inner http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { inner.ServeHTTP(w, r) fields := logrus.Fields{ "time": time.Since(start), "method": r.Method, "url": r.RequestURI, } logrus.WithFields(fields).Info("done") }) } decorateWithJSON := func(inner APIHandler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { wrapper := DefaultAPIContext{ request: r, writer: w, } err := inner(&wrapper) if err != nil { fields := logrus.Fields{ "err": err, "time": time.Since(start), "method": r.Method, "url": r.RequestURI, } logrus.WithFields(fields).Error("request failure") io.WriteString(w, err.Error()) w.WriteHeader(http.StatusInternalServerError) } else { w.WriteHeader(http.StatusOK) } }) } decorateWithError := func(inner RawAPIHandler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { err := inner(w, r) if err != nil { fields := logrus.Fields{ "err": err, "time": time.Since(start), "method": r.Method, "url": r.RequestURI, // "remote": r.RemoteAddr, // "userAgent": r.UserAgent(), } logrus.WithFields(fields).Error("request failure") io.WriteString(w, err.Error()) w.WriteHeader(http.StatusInternalServerError) } else { w.WriteHeader(http.StatusOK) } }) } for _, route := range jsonRoutes { handler := decorateWithLog(decorateWithJSON(route.HandlerFunc)) subrouter. Methods(route.Method). Path(route.Pattern). Handler(handler) } for _, route := range rawRoutes { handler := decorateWithLog(decorateWithError(route.HandlerFunc)) subrouter. Methods(route.Method). Path(route.Pattern). Handler(handler) } return router }
package aoc2015 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func TestDay03(t *testing.T) { assert := assert.New(t) testCases := []aoc.TestCase{ {Input: "^v", Result1: "2", Result2: "3"}, {Input: "^>v<", Result1: "4", Result2: "3"}, {Input: "^v^v^v^v^v", Result1: "2", Result2: "11"}, {Details: "Y2015D03 my input", Input: day03myInput, Result1: "2081", Result2: "2341"}, } for _, tt := range testCases { tt.Test(Day03, assert) } } func BenchmarkDay03(b *testing.B) { aoc.Benchmark(Day03, b, day01myInput) }
package sphinx import ( "github.com/btcsuite/btcd/btcec/v2" "golang.org/x/crypto/ripemd160" ) // TODO(roasbeef): Might need to change? due to the PRG* requirements? const fSLength = 48 // Hmm appears that they use k = 128 throughout the paper? // HMAC -> SHA-256 // * or could use Poly1035: https://godoc.org/golang.org/x/crypto/poly1305 // * but, the paper specs: {0, 1}^k x {0, 1}* -> {0, 1}^k // * Poly1035 is actually: {0, 1}^k x {0, 1}* -> {0, 1}^(2/k) // * Also with Poly, I guess the key is treated as a nonce, tagging two messages // with the same key allows an attacker to forge message or something like that // Size of a forwarding segment is 32 bytes, the MAC is 16 bytes, so c = 48 bytes // * NOTE: this doesn't include adding R to the forwarding segment, and w/e esle // Hmmm since each uses diff key, just use AES-CTR with blank nonce, given key, // encrypt plaintext of all zeros, this'll give us our len(plaintext) rand bytes. // PRG0 -> {0, 1}^k -> {0, 1}^r(c+k) or {0, 1}^1280 (assuming 20 hops, like rusty, but, is that too large? maybe, idk) // PRG1 -> {0, 1}^k -> {0, 1}^r(c+k) or {0, 1}^1280 (assuming 20 hops) // PRG2 -> {0, 1}^k -> {0, 1}^rc or {0, 1}^960 (assuming 20 hops, c=48) // * NOTE: in second version of paper (accepted to CCS'15), all the PRG*'s are like PRG2 // * so makes it simpler // PRP -> AES? or // * {0, 1}^k x {0, 1}^a -> {0, 1}^a // Do we need AEAD for the below? Or are is the per-hop MAC okay? // ENC: AES-CTR or CHACHA20? // DEC: AES-CTR or CHACHA20? // h_op: G^* -> {0, 1}^k // * op (elem of) {MAC, PRGO, PRG!, PRP, ENC, DEC} // * key gen for the above essentially // RoutingSegment... // NOTE: Length of routing segment in the paper is 8 bytes (enough for their // imaginary network, I guess). But, looking like they'll be (20 + 33 bytes) // 53 bytes. Or 52 if we use curve25519 type routingSegment struct { nextHop *btcec.PublicKey // NOTE: or, is this a LN addr? w/e that is? // nextHop [32]byte rCommitment [ripemd160.Size]byte // stuff perhaps? } // SphinxPayload... type sphinxPayload struct { } // ForwardingSegment.... type forwardingSegment struct { // Here's hash(R), attempt to make an HTLC with the next hop. If // successful, then pass along the onion so we can finish getting the // payment circuit set up. // TODO(roasbeef): Do we create HTLC's with the minimum amount // possible? 1 satoshi or is it 1 mili-satoshi? rs routingSegment // To defend against replay attacks. Intermediate nodes will drop the // FS if it deems it's expired. expiration uint64 // Key shared by intermediate node with the source, used to peel a layer // off the onion for the next hop. sharedSymmetricKey [32]byte // TODO(roasbeef): or, 16? } // AnonymousHeader... type anonymousHeader struct { // Forwarding info for the current hop. When serialized, it'll be // encrypted with SV, the secret key for this node known to no-one but // the node. It also contains a secret key shared with this node and the // source, so it can peel off a layer of the onion for the next hop. fs forwardingSegment mac [32]byte // TODO(roasbeef): or, 16? } // CommonHeader... type commonHeader struct { // TODO(roasbeef): maybe can use this to extend HORNET with additiona control signals // for LN nodes? controlType uint8 hops uint8 nonce [8]byte // either interpreted as EXP or nonce, little-endian? idk } // DataPacket... type dataPacket struct { chdr commonHeader ahdr anonymousHeader // TODO(roasbeef): MAC in ahdr includes the chdr? onion [fSLength * NumMaxHops]byte // TODO(roasbeef): or, is it NumMaxHops - 1? } type sphinxHeader struct { } // SessionSetupPacket... type sessionSetupPacket struct { chdr commonHeader shdr sphinxHeader sp sphinxPayload fsPayload [fSLength * NumMaxHops]byte // ? r*c // TODO(roabeef): hmm does this implcitly mean messages are a max of 48 bytes? }
package machinery import ( "fmt" "math" ) type ConflictResolver interface { Rename(kind string, oldName string, validator func(string) error) string } type autoResolver struct{} func (r *autoResolver) Rename( kind string, oldName string, validator func(string) error, ) string { for i := 1; i < math.MaxInt; i++ { newName := fmt.Sprintf("%s-%d", oldName, i) if err := validator(newName); err == nil { return newName } } panic(fmt.Sprintf("failed to rename %s %s", kind, oldName)) } var AutoResolver = &autoResolver{}
package migrate import ( "strings" "github.com/neuronlabs/errors" "github.com/neuronlabs/neuron-core/class" "github.com/neuronlabs/neuron-postgres/internal" "github.com/neuronlabs/neuron-postgres/log" ) // KeyWordType is the postgres default key word type. type KeyWordType int // IsReserved checks if the current keyword is reserved. func (k KeyWordType) IsReserved() bool { switch k { case KWUnreservedC, KWReservedR, KWReservedT: return true default: return false } } const ( // KWUnknown is the unknown keyword type. KWUnknown KeyWordType = iota // KWUnreservedU is the unreserved key word type. KWUnreservedU // KWUnreservedC is the unreserved key word type that cannot be a function or type name. KWUnreservedC // KWReservedR is the reserved keyword type. KWReservedR // KWReservedT is the reserved keyword that can be a function or type name. KWReservedT ) var keyWords = map[int]map[string]KeyWordType{} // GetQuotedWord gets the quoted 'word' if it is on the lists of the keywords. // The postgres version 'pgVersion' is the numeric version of the postgres server. func GetQuotedWord(word string, pgVersion int) string { nameType := getKeyWordType(word, pgVersion) switch nameType { case KWUnreservedC, KWReservedR, KWReservedT: return "\"" + word + "\"" default: return word } } // GetKeyWordType gets the keyword type for given 'word' and postgres version 'pgVersion'. // If field is not found returns 'KWUnknown'. func GetKeyWordType(word string, pgVersion int) KeyWordType { return getKeyWordType(word, pgVersion) } // GetKeyWords gets and stores the keywords for the provided postgres 'version' from the current database // 'db' connection. func GetKeyWords(conn internal.Connection, version int) error { if keyWords[version] != nil { return nil } rows, err := conn.Query("SELECT word, catcode FROM pg_get_keywords()") if err != nil { return errors.NewDetf(class.InternalRepository, "can't get query postgres key words: %v", err.Error()) } defer rows.Close() keywords := map[string]KeyWordType{} var ( word string catcode rune kwt KeyWordType ) for rows.Next() { if err = rows.Scan(&word, &catcode); err != nil { log.Errorf("Scanning key words query failed: %v", err) return err } switch catcode { case 'T': kwt = KWReservedT case 'R': kwt = KWReservedR case 'U': kwt = KWUnreservedU case 'C': kwt = KWUnreservedC default: log.Errorf("Unknown keyword type: '%s'. Setting keyword: '%s' as reservedR", catcode, word) kwt = KWReservedR } keywords[word] = kwt } keyWords[version] = keywords return nil } // WriteQuotedWord surrounds the 'word' with quotations '"' signs if it is one of reserved keywords. // The postgres version 'pgVersion' is the numeric version of the postgres server. // The result is being written into provided 'b' strings.Builder. func WriteQuotedWord(b *strings.Builder, word string, pgVersion int) { nameType := getKeyWordType(word, pgVersion) switch nameType { case KWUnreservedC, KWReservedR, KWReservedT: b.WriteRune('"') b.WriteString(word) b.WriteRune('"') default: b.WriteString(word) } } func getKeyWordType(word string, pgVersion int) KeyWordType { kw, ok := keyWords[pgVersion] if !ok { log.Debugf("No keywords set for the postgres version: '%d'", pgVersion) return KWUnknown } tp, ok := kw[word] if !ok { tp = KWUnknown } return tp } func quoteIdentifier(name string) string { endRune := strings.IndexRune(name, 0) if endRune > -1 { name = name[:endRune] } return `"` + strings.Replace(name, `"`, `""`, -1) + `"` }
package main import ( "fmt" "github.com/samuel/go-zookeeper/zk" client2 "zookeeper/client" ) func callback(event zk.Event) { } func main() { // 先安转zookeeper // 服务器地址列表 servers := []string{"192.168.5.216:2181"} client, err := client2.NewClient(servers, "/api", 10, func(event zk.Event) { // zk.EventNodeCreated // zk.EventNodeDeleted fmt.Println("path: ", event.Path) fmt.Println("type: ", event.Type.String()) fmt.Println("state: ", event.State.String()) fmt.Println("---------------------------") }) if err != nil { panic(err) } defer client.Close() node1 := &client2.ServiceNode{Name: "db", Host: "127.0.0.1", Port: 4000} node2 := &client2.ServiceNode{Name: "img", Host: "127.0.0.1", Port: 4001} if err := client.Register(node1); err != nil { panic(err) } if err := client.Register(node2); err != nil { panic(err) } // db dbNodes, err := client.GetNodes("db") if err != nil { panic(err) } for _, node := range dbNodes { fmt.Println("dbNode=", node.Host, node.Port) } // img imgNodes, err := client.GetNodes("img") if err != nil { panic(err) } for _, node := range imgNodes { fmt.Println("mqNode=", node.Host, node.Port) } }
package main /* Use built-in synchronization features to achieve the same result as using mutexes. (go routines and channels) The channel-based approach aligns with Go's ideas of sharing memory by communicating and having each piece of data owned by exactly one goroutine */ import ( "fmt" "math/rand" "sync/atomic" "time" ) /* In example - state will be owned by a single go routine. To read or write that state, other goroutines will send messages to the owning goroutine and receive corresponding replies. These readOp and writeOp structs encapsulate those requests and a way for goroutines to respond */ type readOp struct { key int resp chan int } type writeOp struct { key int val int resp chan bool } func main() { // count operations var readOps uint64 var writeOps uint64 reads := make(chan readOp) writes := make(chan writeOp) // go routine that owns the state go func() { var state = make(map[int]int) for { select { case read := <-reads: // selects on the reads and writes channel, responding as they arrive read.resp <- state[read.key] case write := <-writes: state[write.key] = write.val write.resp <- true } } }() // start 100 goroutines to issue reads to the state-owning goroutine via the reads channel for r := 0; r < 100; r++ { go func() { for { read := readOp{ key: rand.Intn(5), resp: make(chan int), } reads <- read <-read.resp atomic.AddUint64(&readOps, 1) time.Sleep(time.Millisecond) } }() } // Start 10 writes as well for w := 0; w < 10; w++ { go func() { for { write := writeOp{ key: rand.Intn(5), val: rand.Intn(100), resp: make(chan bool), } writes <- write <-write.resp atomic.AddUint64(&writeOps, 1) time.Sleep(time.Millisecond) } }() } time.Sleep(time.Second) // Take and report final operation counts readOpsFinal := atomic.LoadUint64(&readOps) fmt.Println("readOps:", readOpsFinal) writeOpsFinal := atomic.LoadUint64(&writeOps) fmt.Println("writeOps:", writeOpsFinal) }
// Package api implements of API/Controller layer of application // Consisting of some API endpoints which are covered with Swagger annotations package api import ( "errors" "net/http" "strconv" "time" "github.com/gin-gonic/gin" "../models" "../service" ) // ReadCandidate godoc // @Summary Read candidate // @Description Reads a specific candidate by id // @Accept json // @Produce json // @Param id query string false "Candidate ID" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /readCandidate [get] func ReadCandidate(ctx *gin.Context) { result, error := service.ReadCandidate(ctx.Query("id")) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, result) } } // CreateCandidate godoc // @Summary Create candidate // @Description Creates a new candidate // @Accept json // @Produce json // @Param first_name query string true "First Name" // @Param last_name query string true "Last Name" // @Param email query string false "E-Mail" // @Param department query string false "Department" // @Param university query string false "University" // @Param experience query boolean false "Experience" // @Param assignee query string true "Assignee" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /createCandidate [post] func CreateCandidate(ctx *gin.Context) { experience, experienceError := strconv.ParseBool(ctx.Query("experience")) if experienceError != nil { ctx.JSON(http.StatusNotFound, errors.New("Could not convert experience")) } result, error := service.CreateCandidate(&models.Candidate{ FirstName: ctx.Query("first_name"), LastName: ctx.Query("last_name"), Email: ctx.Query("email"), Department: ctx.Query("department"), University: ctx.Query("university"), Experience: experience, Assignee: ctx.Query("assignee"), }) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, result) } } // DeleteCandidate godoc // @Summary Delete candidate // @Description Removes a candidate by id // @Accept json // @Produce json // @Param id query string false "Candidate ID" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /deleteCandidate [delete] func DeleteCandidate(ctx *gin.Context) { error := service.DeleteCandidate(ctx.Query("id")) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, true) } } // DenyCandidate godoc // @Summary Deny candidate // @Description Denies a candidate by id // @Accept json // @Produce json // @Param id query string false "Candidate ID" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /denyCandidate [put] func DenyCandidate(ctx *gin.Context) { error := service.DenyCandidate(ctx.Query("id")) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, true) } } // AcceptCandidate godoc // @Summary Accept candidate // @Description Accepts a candidate // @Accept json // @Produce json // @Param id query string false "Candidate ID" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /acceptCandidate [put] func AcceptCandidate(ctx *gin.Context) { error := service.AcceptCandidate(ctx.Query("id")) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, true) } } // FindAssigneeIDByName godoc // @Summary Find assignee ID by name // @Description Finds ID of an assignee by name // @Accept json // @Produce json // @Param name query string false "Assignee Name" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /findAssigneeIDByName [get] func FindAssigneeIDByName(ctx *gin.Context) { result, error := service.FindAssigneeIDByName(ctx.Query("name")) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, result) } } // FindAssigneesCandidates godoc // @Summary Find asignees candidates // @Description Finds candidates of an assignee by ID of assignee // @Accept json // @Produce json // @Param id query string false "Assignee ID" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /findAssigneesCandidates [get] func FindAssigneesCandidates(ctx *gin.Context) { result, error := service.FindAssigneesCandidates(ctx.Query("id")) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, result) } } // ArrangeMeeting godoc // @Summary Arrange meeting // @Description Aranges a meeting with an available candidate // @Accept json // @Produce json // @Param id query string false "Candidate ID" // @Param nextMeetingTime query string false "Next Meeting Time (Ex. 2020-11-11T20:59:48.133+03:00)" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /arrangeMeeting [put] func ArrangeMeeting(ctx *gin.Context) { time, _ := time.Parse(time.RFC3339, ctx.Query("nextMeetingTime")) error := service.ArrangeMeeting(ctx.Query("_id"), &time) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, true) } } // CompleteMeeting godoc // @Summary Complete meeting // @Description Completes a meeting of specified candidate // @Accept json // @Produce json // @Param id query string false "Candidate ID" // @Success 200 {object} object model.Account // @Header 200 {string} Token "qwerty" // @Failure default {object} object httputil.DefaultError // @Router /completeMeeting [put] func CompleteMeeting(ctx *gin.Context) { error := service.CompleteMeeting(ctx.Query("id")) if error != nil { ctx.JSON(http.StatusNotFound, error.Error()) } else { ctx.JSON(http.StatusOK, true) } }
// Package rotate is a port of File-Rotate from Perl // (https://metacpan.org/release/File-Rotate), and it allows // you to automatically rotate output files when you write to them // according to the filename pattern that you can specify. package rotate import ( "fmt" "io" "os" "path/filepath" "time" "github.com/bingoohuang/golog/pkg/lock" "github.com/bingoohuang/golog/pkg/compress" "github.com/bingoohuang/golog/pkg/homedir" "github.com/bingoohuang/golog/pkg/iox" "github.com/bingoohuang/golog/pkg/timex" "github.com/pkg/errors" ) // New creates a new Rotate object. A logfile filename // must be passed. Optional `Option` parameters may be passed. func New(logfile string, options ...OptionFn) (*Rotate, error) { logfile, err := homedir.Expand(logfile) if err != nil { return nil, err } r := &Rotate{ logfile: logfile, clock: Local, rotatePostfixLayout: ".2006-01-02", maxAge: timex.Week, maintainLock: lock.NewTry(), } OptionFns(options).Apply(r) // make sure the dir is existed, eg: // ./foo/bar/baz/hello.log must make sure ./foo/bar/baz is existed dirname := filepath.Dir(logfile) if err := os.MkdirAll(dirname, 0755); err != nil { return nil, errors.Wrapf(err, "failed to create directory %s", dirname) } return r, nil } func (rl *Rotate) GenBaseFilename() (string, time.Time) { now := rl.clock.Now() return rl.logfile + now.Format(rl.rotatePostfixLayout), now } // Write satisfies the io.Writer interface. It writes to the // appropriate file handle that is currently being used. // If we have reached rotation time, the target file gets // automatically rotated, and also purged if necessary. func (rl *Rotate) Write(p []byte) (n int, err error) { defer rl.lock.Lock()() forRotate := rl.rotateMaxSize > 0 && rl.outFhSize >= rl.rotateMaxSize out, err := rl.getWriter(forRotate) if err != nil { iox.ErrorReport("Write getWriter error %+v\n", err) return 0, errors.Wrap(err, `failed to acquire target io.Writer`) } n, err = out.Write(p) if err != nil { iox.ErrorReport("Write error %+v\n", err) } rl.outFhSize += int64(n) return n, err } func (rl *Rotate) getWriter(forceRotate bool) (io.Writer, error) { fnBase, now := rl.GenBaseFilename() generation := rl.generation if fnBase != rl.curFnBase { generation = 0 } else { if !forceRotate { // nothing to do return rl.outFh, nil } generation++ } generation, fn := rl.tryGenerational(generation, fnBase) if err := rl.rotateFile(fn); err != nil { return nil, err } if (rl.maxAge > 0 || rl.gzipAge > 0) && rl.maintainLock.TryLock() { go rl.maintain(now) } rl.notifyFileRotateEvent(rl.curFn, fn) rl.curFnBase = fnBase rl.generation = generation rl.curFn = fn return rl.outFh, nil } func (rl *Rotate) tryGenerational(generation int, filename string) (int, string) { if rl.outFh == nil { return generation, filename } // A new file has been requested. Instead of just using the // regular go time format pattern, we create a new file name using // generational names such as "foo.1", "foo.2", "foo.3", etc name := filename for ; ; generation++ { if generation > 0 { name = fmt.Sprintf("%s.%d", filename, generation) } if name == rl.curFn { continue } if _, err := os.Stat(name); err == nil { continue } return generation, name } } func (rl *Rotate) rotateFile(filename string) error { if rl.outFh != nil { if err := rl.outFh.Close(); err != nil { return err } rl.outFh = nil if err := os.Rename(rl.logfile, filename); err != nil { iox.ErrorReport("Rename %s to %s error %+v\n", rl.logfile, filename, err) return err } iox.InfoReport("log file renamed to", filename) } // if we got here, then we need to create a file fh, err := os.OpenFile(rl.logfile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { iox.ErrorReport("OpenFile %s error %+v\n", rl.logfile, err) return errors.Errorf("failed to open file %s: %s", rl.logfile, err) } rl.outFh = fh stat, err := fh.Stat() if err == nil { rl.outFhSize = stat.Size() } else { rl.outFhSize = 0 iox.ErrorReport("Stat %s error %+v\n", rl.logfile, err) } return nil } func (rl *Rotate) notifyFileRotateEvent(previousFn, filename string) { if h := rl.handler; h != nil { go h.Handle(&FileRotatedEvent{PreviousFile: previousFn, CurrentFile: filename}) } } // CurrentFileName returns the current file name that the Rotate object is writing to. func (rl *Rotate) CurrentFileName() string { defer rl.lock.RLock()() return rl.curFn } // LogFile returns the current file name that the Rotate object is writing to. func (rl *Rotate) LogFile() string { return rl.logfile } // Rotate forcefully rotates the log files. If the generated file name // clash because file already exists, a numeric suffix of the form // ".1", ".2", ".3" and so forth are appended to the end of the log file // // This method can be used in conjunction with a signal handler so to // emulate servers that generate new log files when they receive a SIGHUP. func (rl *Rotate) Rotate() error { defer rl.lock.Lock()() _, err := rl.getWriter(true) if err != nil { iox.ErrorReport("Rotate getWriter error %+v\n", err) } return err } func (rl *Rotate) maintain(now time.Time) { defer rl.maintainLock.Unlock() matches, err := filepath.Glob(rl.logfile + "*") if err != nil { iox.ErrorReport("fail to glob %v error %+v\n", rl.logfile+"*", err) return } maxAgeCutoff := now.Add(-rl.maxAge) gzipAgeCutoff := now.Add(-rl.gzipAge) for _, path := range matches { if rl.needToUnlink(path, maxAgeCutoff) { rl.removeFile(path) } else if rl.needToGzip(path, gzipAgeCutoff) { rl.gzipFile(path) } } } func (rl *Rotate) gzipFile(path string) { iox.InfoReport("gzipped by", rl.gzipAge, path) if err := compress.Gzip(path); err != nil { iox.ErrorReport("Gzip error %+v\n", err) } } func (rl *Rotate) removeFile(path string) { iox.InfoReport("removed by", rl.maxAge, path) if err := os.Remove(path); err != nil { iox.ErrorReport("Remove error %+v\n", err) } } // Close satisfies the io.Closer interface. You must // call this method if you performed any writes to the object. func (rl *Rotate) Close() error { defer rl.lock.Lock()() if rl.outFh == nil { return nil } err := rl.outFh.Close() if err != nil { iox.ErrorReport("Close outFh error %+v\n", err) } rl.outFh = nil iox.InfoReport("outFh closed") return err }
/* Package log implements a simple logging package. package main import ( "github.com/ije/gox/log" ) func main() { l, err := log.New("file:/var/log/error.log?buffer=32kb") if err != nil { return } l.Info("Hello World!") } */ package log import ( "fmt" "io" "os" "runtime" "strings" "sync" "syscall" "time" "github.com/ije/gox/utils" ) type Logger struct { lock sync.Mutex level Level prefix string output io.Writer quite bool buffer []byte bufcap int buflen int flushTimer *time.Timer } func New(url string) (*Logger, error) { l := &Logger{} return l, l.parseURL(url) } func (l *Logger) parseURL(url string) (err error) { url = strings.ReplaceAll(url, " ", "") if url == "" { return nil } fsn, path := utils.SplitByFirstByte(url, ':') fs, ok := registeredFileSystems[strings.ToLower(fsn)] if !ok { return fmt.Errorf("unknown fs protocol '%s'", fsn) } // handle format like file:///var/log/error.log if strings.HasPrefix(path, "//") { path = strings.TrimPrefix(path, "//") } if !strings.HasPrefix(path, "/") { path = "./" + path } args := map[string]string{} addr, query := utils.SplitByFirstByte(path, '?') for _, q := range strings.Split(query, "&") { key, value := utils.SplitByFirstByte(q, '=') if len(key) > 0 { switch strings.ToLower(key) { case "prefix": l.SetPrefix(value) case "level": l.SetLevelByName(value) case "quite": l.SetQuite(value == "" || value == "1" || strings.ToLower(value) == "true") case "buffer": bytes, err := utils.ParseBytes(value) if err == nil { l.SetBuffer(int(bytes)) } default: args[key] = value } } } output, err := fs.Open(addr, args) if err != nil { return } l.SetOutput(output) return } func (l *Logger) SetLevel(level Level) { if level >= L_DEBUG && level <= L_FATAL { l.level = level } } func (l *Logger) SetLevelByName(name string) { l.SetLevel(LevelByName(name)) } func (l *Logger) SetPrefix(prefix string) { l.prefix = strings.TrimSpace(prefix) } func (l *Logger) SetQuite(quite bool) { l.quite = quite } func (l *Logger) SetBuffer(cap int) { if cap < 32 { return } l.FlushBuffer() l.lock.Lock() defer l.lock.Unlock() l.buffer = make([]byte, cap) l.bufcap = cap l.buflen = 0 } func (l *Logger) SetOutput(output io.Writer) { l.lock.Lock() defer l.lock.Unlock() l.output = output } func (l *Logger) Print(v ...interface{}) { l.log(-1, fmt.Sprintln(v...), noColor) } func (l *Logger) Printf(format string, v ...interface{}) { l.log(-1, fmt.Sprintf(fmt.Sprintf(format, v...)), noColor) } func (l *Logger) Debug(v ...interface{}) { l.log(L_DEBUG, fmt.Sprintln(v...), noColor) } func (l *Logger) Debugf(format string, v ...interface{}) { l.log(L_DEBUG, fmt.Sprintf(format, v...), noColor) } func (l *Logger) Info(v ...interface{}) { l.log(L_INFO, fmt.Sprintln(v...), green) } func (l *Logger) Infof(format string, v ...interface{}) { l.log(L_INFO, fmt.Sprintf(format, v...), green) } func (l *Logger) Warn(v ...interface{}) { l.log(L_WARN, fmt.Sprintln(v...), yellow) } func (l *Logger) Warnf(format string, v ...interface{}) { l.log(L_WARN, fmt.Sprintf(format, v...), yellow) } func (l *Logger) Error(v ...interface{}) { l.log(L_ERROR, fmt.Sprintln(v...), red) } func (l *Logger) Errorf(format string, v ...interface{}) { l.log(L_ERROR, fmt.Sprintf(format, v...), red) } func (l *Logger) Fatal(v ...interface{}) { l.fatal(fmt.Sprintln(v...)) } func (l *Logger) Fatalf(format string, v ...interface{}) { l.fatal(fmt.Sprintf(format, v...)) } func (l *Logger) FlushBuffer() (err error) { l.lock.Lock() defer l.lock.Unlock() if l.buflen > 0 { if l.output != nil { _, err = l.output.Write(l.buffer[:l.buflen]) if err != nil { return } } l.buflen = 0 } return } func (l *Logger) log(level Level, msg string, color string) { if level >= L_DEBUG && level < l.level { return } prefix := "" if level >= L_DEBUG && level <= L_FATAL { prefix = fmt.Sprintf("[%s] ", level) } if _prefix := l.prefix; len(_prefix) > 0 { prefix += _prefix + " " } bl := 20 + len(prefix) + len(msg) + 1 buf := make([]byte, bl) now := time.Now() year, month, day := now.Date() hour, min, sec := now.Clock() i := pad(buf, 0, year, 4, '/') i = pad(buf, i, int(month), 2, '/') i = pad(buf, i, day, 2, ' ') i = pad(buf, i, hour, 2, ':') i = pad(buf, i, min, 2, ':') i = pad(buf, i, sec, 2, ' ') copy(buf[i:], prefix) copy(buf[i+len(prefix):], msg) if buf[bl-2] == '\n' { buf = buf[:bl-1] } else { buf[bl-1] = '\n' } if !l.quite { line := string(buf) _, ok := syscall.Getenv("NO_COLOR") if !ok && color != noColor && runtime.GOOS != "windows" { line = fmt.Sprintf("%s%s%s", color, line, noColor) } l.lock.Lock() if level < L_ERROR { os.Stdout.WriteString(line) } else { os.Stderr.WriteString(line) } l.lock.Unlock() } l.write(buf) } func (l *Logger) fatal(format string, v ...interface{}) { l.log(L_FATAL, fmt.Sprintf(format, v...), red) l.FlushBuffer() os.Exit(1) } func (l *Logger) write(p []byte) (err error) { n := len(p) if n == 0 { return } l.lock.Lock() defer l.lock.Unlock() if l.output == nil { return } if l.bufcap > 0 { // flush buffer if l.buflen > 0 && l.buflen+n > l.bufcap { _, err = l.output.Write(l.buffer[:l.buflen]) if err != nil { return } l.buflen = 0 } if l.flushTimer != nil { l.flushTimer.Stop() } if n > l.bufcap { n, err = l.output.Write(p) } else { copy(l.buffer[l.buflen:], p) l.buflen += n l.flushTimer = time.AfterFunc(time.Minute, func() { l.flushTimer = nil l.FlushBuffer() }) } } else { n, err = l.output.Write(p) } return } func pad(p []byte, i int, u int, w int, suffix byte) int { i += w for j := 1; w > 0; j++ { p[i-j] = byte(u%10) + '0' u /= 10 w-- } p[i] = suffix return i + 1 }
package main import ( "flag" "fmt" "github.com/rs/zerolog/log" "os" "toutiao/admin" "toutiao/downloader" "toutiao/tools" "toutiao/translator" ) type A struct { year int } func (a A) Greet() { fmt.Println("Hello GolangUK", a.year) } type B struct { A } func (b B) Greet() { fmt.Println("Welcome to GolangUK", b.year) } var dao = &translator.YouDao{ AppKey: "6a0f0aec8e860c65", SecKey: "vTrsGcDDmD0X6RIUUpCi0oEGazF30BOz", } var id = flag.String("url", "BV1K741137fi", "请输入一个 youtube 地址") func main() { flag.Parse() if *id == "" { log.Fatal().Msg("请输入要下载的 url, --url=Szw_1B-IBcs") } ok, video := downloader.Download(*id) if !ok { log.Error().Msg("下载源文件出错") os.Exit(1) } // 分析标题和内容 // todo 可以扩展string 自由调用吗 fmt.Println(video.Title) video.Title = translator.Translate(dao, video.Title) video.Desc = translator.Translate(dao, video.Desc) video.Title = tools.CutByUtf8(video.Title, 30) video.Desc = tools.CutByUtf8(video.Desc, 300) // 文件准备完成 admin.LoadUserInfo() md5Resp := admin.Md5Check(video.Md5) if !md5Resp.IsUniq { log.Warn().Msgf("Video Already use in [%s]", md5Resp.Data) return } videoapi := admin.VideoApi() log.Warn().Msgf("video/api: %v", videoapi) admin.VideoLogStart(&video, videoapi) uploadResponse := admin.VideoUpload(&video, videoapi) log.Warn().Msgf("uploadResponse: %v", uploadResponse) admin.VideoLogSueecss(uploadResponse, videoapi, &video) admin.ArticlePost(video, videoapi, uploadResponse) }
package dal import ( "errors" ) // QueryProvider 提供数据库查询接口 type QueryProvider interface { // 查询单条数据 Single(entity QueryEntity) (map[string]string, error) // 查询单条数据 SingleWithSQL(sql string, values ...interface{}) (map[string]string, error) // 将查询结果解析到对应的指针地址 // (数据类型包括:map[string]string,map[string]interface{},struct) AssignSingle(entity QueryEntity, output interface{}) error // 将查询结果解析到对应的指针地址 // (数据类型包括:map[string]string,map[string]interface{},struct) AssignSingleWithSQL(sql string, values []interface{}, output interface{}) error // 查询列表数据 List(entity QueryEntity) ([]map[string]string, error) // 使用sql查询数据列表 ListWithSQL(sql string, values ...interface{}) ([]map[string]string, error) // 将查询结果解析到对应的指针地址 // (数据类型包括:[]map[string]string,[]map[string]interface{},[]struct) AssignList(entity QueryEntity, output interface{}) error // 使用sql查询数据列表 AssignListWithSQL(sql string, values []interface{}, output interface{}) error // 查询分页数据 Pager(entity QueryEntity) (QueryPagerResult, error) // 查询数据(根据QueryResultType返回数据结果类型) Query(entity QueryEntity) (interface{}, error) } // TranProvider 提供数据库事务操作 type TranProvider interface { // Exec 执行单条事务性操作 Exec(TranEntity) TranResult // ExecTrans 执行多条事务性操作 ExecTrans([]TranEntity) TranResult } // Provider 提供统一的数据库操作 type Provider interface { QueryProvider TranProvider } // DBProvider 提供DB初始化 type DBProvider interface { Provider // InitDB 数据库初始化 // config 为配置信息(以json字符串的方式提供) InitDB(config string) error } // ProvideEngine 数据库操作引擎 type ProvideEngine string const ( // MYSQL mysql数据库 MYSQL ProvideEngine = "mysql" ) var ( // GDAL 提供全局的Provider GDAL Provider providers map[ProvideEngine]DBProvider ) func init() { providers = make(map[ProvideEngine]DBProvider) } // RegisterDBProvider 注册DBProvider func RegisterDBProvider(provideName ProvideEngine, provider DBProvider) { if provider == nil { panic("go-dal:DBProvider is nil!") } if _, ok := providers[provideName]; ok { panic("go-dal:DBProvider has been registered!") } providers[provideName] = provider } // RegisterProvider 提供全局的provider func RegisterProvider(provideName ProvideEngine, config string) error { if GDAL != nil { return errors.New("Provider has been registered!") } provide, ok := providers[provideName] if !ok { return errors.New("Unknown provider!") } if err := provide.InitDB(config); err != nil { return err } GDAL = provide return nil } // Single 查询单条数据 func Single(entity QueryEntity) (map[string]string, error) { return GDAL.Single(entity) } // SingleWithSQL 查询单条数据 func SingleWithSQL(sql string, values ...interface{}) (map[string]string, error) { return GDAL.SingleWithSQL(sql, values...) } // AssignSingle 将查询结果解析到对应的指针地址 // (数据类型包括:map[string]string,map[string]interface{},struct) func AssignSingle(entity QueryEntity, output interface{}) error { return GDAL.AssignSingle(entity, output) } // AssignSingleWithSQL 将查询结果解析到对应的指针地址 // (数据类型包括:map[string]string,map[string]interface{},struct) func AssignSingleWithSQL(sql string, values []interface{}, output interface{}) error { return GDAL.AssignSingleWithSQL(sql, values, output) } // List 查询列表数据 func List(entity QueryEntity) ([]map[string]string, error) { return GDAL.List(entity) } // ListWithSQL 查询列表数据 func ListWithSQL(sql string, values ...interface{}) ([]map[string]string, error) { return GDAL.ListWithSQL(sql, values...) } // AssignList 将查询结果解析到对应的指针地址 // (数据类型包括:[]map[string]string,[]map[string]interface{},[]struct) func AssignList(entity QueryEntity, output interface{}) error { return GDAL.AssignList(entity, output) } // AssignListWithSQL 将查询结果解析到对应的指针地址 // (数据类型包括:[]map[string]string,[]map[string]interface{},[]struct) func AssignListWithSQL(sql string, values []interface{}, output interface{}) error { return GDAL.AssignListWithSQL(sql, values, output) } // Pager 查询分页数据 func Pager(entity QueryEntity) (QueryPagerResult, error) { return GDAL.Pager(entity) } // Query 查询数据 //(根据QueryResultType返回数据结果类型) func Query(entity QueryEntity) (interface{}, error) { return GDAL.Query(entity) } // Exec 执行单条事务性操作 func Exec(entity TranEntity) TranResult { return GDAL.Exec(entity) } // ExecTrans 执行多条事务性操作 func ExecTrans(entities []TranEntity) TranResult { return GDAL.ExecTrans(entities) }
// lexer.go package main import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "regexp" "strings" ) func assemble(asm ASM, source, executable string) (err error) { var srcFile *os.File var e error if source == "" { srcFile, e = ioutil.TempFile("", "") if e != nil { err = fmt.Errorf("Creating temporary srcFile failed - %w", e) return } defer os.Remove(srcFile.Name()) } else { srcFile, e = os.Create(source) if e != nil { err = fmt.Errorf("Creating srcFile failed - %w", e) return } } objectFile, e := ioutil.TempFile("", "") if e != nil { err = fmt.Errorf("Creating temporary objectFile failed - %w", e) return } objectFile.Close() // Write assembly into tmp source file defer os.Remove(objectFile.Name()) for _, v := range asm.header { fmt.Fprintf(srcFile, "%v\n", v) } for k, v := range asm.constants { fmt.Fprintf(srcFile, "%-12v%-10v%-15v\n", v, "equ", k) } for k, v := range asm.sysConstants { fmt.Fprintf(srcFile, "%-12v%-10v%-15v\n", v, "equ", k) } for _, v := range asm.variables { fmt.Fprintf(srcFile, "%-12v%-10v%-15v\n", v[0], v[1], v[2]) } for _, v := range asm.sectionText { fmt.Fprintf(srcFile, "%v\n", v) } for k, f := range asm.functions { if !f.inline && f.used { fmt.Fprintf(srcFile, "global %v\n", k) fmt.Fprintf(srcFile, "%v:\n", k) for _, v := range f.code { fmt.Fprintf(srcFile, "%v%-10v%-10v\n", v[0], v[1], v[2]) } } } for _, v := range asm.program { fmt.Fprintf(srcFile, "%v%-10v%-10v\n", v[0], v[1], v[2]) } srcFile.Close() // Find yasm yasm, e := exec.LookPath("yasm") if e != nil { err = fmt.Errorf("'yasm' not found. Please install - %w", e) return } // Assemble yasmCmd := &exec.Cmd{ Path: yasm, Args: []string{yasm, "-f", "elf64", srcFile.Name(), "-o", objectFile.Name()}, Stdout: os.Stdout, Stderr: os.Stderr, } if e := yasmCmd.Run(); e != nil { err = fmt.Errorf("Error while assembling the source code - %w", e) return } // Find ld ld, e := exec.LookPath("ld") if e != nil { err = fmt.Errorf("'ld' not found. Please install - %w", e) return } // Link ldCmd := &exec.Cmd{ Path: ld, Args: []string{ld, "-o", executable, objectFile.Name()}, Stdout: os.Stdout, Stderr: os.Stderr, } if e := ldCmd.Run(); e != nil { err = fmt.Errorf("Error while linking object file - %w", e) return } return } func getConvenienceFunctions() []byte { // the print and println functions for strings can be written in code instead of assembly return []byte(` fun print(s string) { for i, c : s { print(c) } } fun println(s string) { print(s) print(char(10)) } fun print(b bool) { if b { print("true") } else { print("false") } } fun println(b bool) { print(b) print(char(10)) } `) } func preprocess(program []byte) (out []byte) { out = append(getConvenienceFunctions(), program...) out = bytes.ReplaceAll(out, []byte("string"), []byte("[]char")) re := regexp.MustCompile(`(\".*\")`) out = re.ReplaceAllFunc(out, func(s []byte) []byte { tmpS := string(s) if tmpS == "\"\"" { return []byte("[](char, 0)") } return []byte("['" + strings.Join(strings.Split(tmpS[1:][:len(tmpS)-2], ""), "','") + "']") }) return } func compile(program []byte, sourceFile, binFile string) bool { tokenChan := make(chan Token, 1) lexerErr := make(chan error, 1) program = preprocess(program) go tokenize(program, tokenChan, lexerErr) ast, parseErr := parse(tokenChan) // check error channel on incoming errors // As we lex and parse simultaneously, there is most likely a parser error as well. But that should be ignored // as long as we have token errors before! select { case e := <-lexerErr: fmt.Println(e) return false default: } if parseErr != nil { fmt.Println(parseErr) return false } ast, semanticErr := semanticAnalysis(ast) if semanticErr != nil { fmt.Println(semanticErr) return false } asm := ast.generateCode() if asmErr := assemble(asm, sourceFile, binFile); asmErr != nil { fmt.Println(asmErr) return false } return true } func main() { var program []byte = []byte(` fun test () int { for ;; { break return 0 } return 1 } fun test (x int) int { switch x { case 1: return 1 case 3: return 32 default: return 3 } } `) if len(os.Args) > 1 { var err error program, err = ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) os.Exit(1) } } if !compile(program, "source.asm", "executable") { os.Exit(1) } }
package main // for printing data out import "fmt" // for reading the cli import "os" // for logging errors and actions import "log" // for dumping data from the file to somewhere else - eg, Copy import "io" func main() { arguments := os.Args if (len(arguments) != 2 ) { fmt.Println("The Program requires a file path string as an argument."); os.Exit(-1); } fmt.Println("Hello"); // totally safe, no way this could be a bad idea, right? filename := arguments[1] // Using func Open(name string) (*File, error) file, err := os.Open(filename) if err != nil { log.Println(err) } // Dump the file contents to the screen, woohoo. log.Println("####Contents of file %s", filename) // Copy(dest, src) io.Copy(os.Stdout, file) }
package config import ( "fmt" "log" _ "github.com/lib/pq" "xorm.io/xorm" ) const ( host = "localhost" port = 5432 user = "postgres" password = "password" dbName = "golang" ) func GetDBEngine() *xorm.Engine { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbName) //format engine, err := xorm.NewEngine("postgres", psqlInfo) if err != nil { log.Fatal(err) return nil } engine.ShowSQL() //It's necessary for Rookies err = engine.Ping() if err != nil { log.Fatal(err) return nil } fmt.Println("connect postgresql success") return engine }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package operations import ( "fmt" "testing" "time" . "github.com/onsi/gomega" "github.com/pkg/errors" log "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/Azure/aks-engine/pkg/api/common" "github.com/Azure/aks-engine/pkg/armhelpers" ) func TestGetNodes_ShouldReturnAResultSetWithNodes(t *testing.T) { t.Parallel() mockClient := armhelpers.MockAKSEngineClient{MockKubernetesClient: &armhelpers.MockKubernetesClient{}} logger := log.NewEntry(log.New()) apiserverURL := "https://apiserver" kubeconfig := "kubeconfig" timeout := time.Minute * 1 result := listNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout) g := NewGomegaWithT(t) g.Expect(result.err).To(BeNil()) g.Expect(result.nodes).To(HaveLen(2)) g.Expect(result.nodes[0].Name).To(Equal(fmt.Sprintf("%s-1234", common.LegacyControlPlaneVMPrefix))) g.Expect(result.nodes[0].Status.Conditions[0].Type).To(Equal(v1.NodeReady)) g.Expect(result.nodes[0].Status.Conditions[0].Status).To(Equal(v1.ConditionTrue)) g.Expect(result.nodes[0].Status.NodeInfo.KubeletVersion).To(Equal("1.9.10")) g.Expect(result.nodes[1].Name).To(Equal("k8s-agentpool3-1234")) g.Expect(result.nodes[1].Status.Conditions[0].Type).To(Equal(v1.NodeMemoryPressure)) g.Expect(result.nodes[1].Status.Conditions[0].Status).To(Equal(v1.ConditionTrue)) g.Expect(result.nodes[1].Status.NodeInfo.KubeletVersion).To(Equal("1.9.9")) } func TestGetNodes_ShouldErrorWhenK8sClientGetterFails(t *testing.T) { t.Parallel() mockClient := armhelpers.MockAKSEngineClient{ FailGetKubernetesClient: true, MockKubernetesClient: &armhelpers.MockKubernetesClient{}} logger := log.NewEntry(log.New()) apiserverURL := "https://apiserver" kubeconfig := "kubeconfig" timeout := time.Minute * 1 result := listNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout) g := NewGomegaWithT(t) g.Expect(result.err).NotTo(BeNil()) g.Expect(result.err.Error()).To(Equal("GetKubernetesClient failed")) g.Expect(result.nodes).To(HaveLen(0)) } func TestGetNodes_ShouldErrorWhenTheK8sAPIFailsToListNodes(t *testing.T) { t.Parallel() mockClient := armhelpers.MockAKSEngineClient{MockKubernetesClient: &armhelpers.MockKubernetesClient{ FailListNodes: true, }} logger := log.NewEntry(log.New()) apiserverURL := "https://apiserver" kubeconfig := "kubeconfig" timeout := time.Minute * 1 result := listNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout) g := NewGomegaWithT(t) g.Expect(result.err).NotTo(BeNil()) g.Expect(result.err.Error()).To(Equal("ListNodes failed")) g.Expect(result.nodes).To(HaveLen(0)) } func TestGetNodes_ShouldReturnNodes(t *testing.T) { t.Parallel() mockClient := armhelpers.MockAKSEngineClient{MockKubernetesClient: &armhelpers.MockKubernetesClient{}} logger := log.NewEntry(log.New()) apiserverURL := "https://apiserver" kubeconfig := "kubeconfig" timeout := time.Minute * 1 nodes, err := GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "", -1) g := NewGomegaWithT(t) g.Expect(err).To(BeNil()) g.Expect(nodes).To(HaveLen(2)) g.Expect(nodes[0].Name).To(Equal(fmt.Sprintf("%s-1234", common.LegacyControlPlaneVMPrefix))) g.Expect(nodes[0].Status.Conditions[0].Type).To(Equal(v1.NodeReady)) g.Expect(nodes[0].Status.Conditions[0].Status).To(Equal(v1.ConditionTrue)) g.Expect(nodes[0].Status.NodeInfo.KubeletVersion).To(Equal("1.9.10")) g.Expect(nodes[1].Name).To(Equal("k8s-agentpool3-1234")) g.Expect(nodes[1].Status.Conditions[0].Type).To(Equal(v1.NodeMemoryPressure)) g.Expect(nodes[1].Status.Conditions[0].Status).To(Equal(v1.ConditionTrue)) g.Expect(nodes[1].Status.NodeInfo.KubeletVersion).To(Equal("1.9.9")) } func TestGetNodes_ShouldReturnNodesInAPoolWhenAPoolStringIsSpecified(t *testing.T) { t.Parallel() mockClient := armhelpers.MockAKSEngineClient{MockKubernetesClient: &armhelpers.MockKubernetesClient{}} logger := log.NewEntry(log.New()) apiserverURL := "https://apiserver" kubeconfig := "kubeconfig" timeout := time.Minute * 1 nodes, err := GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "agentpool3", -1) g := NewGomegaWithT(t) g.Expect(err).To(BeNil()) g.Expect(nodes).To(HaveLen(1)) g.Expect(nodes[0].Name).To(Equal("k8s-agentpool3-1234")) g.Expect(nodes[0].Status.Conditions[0].Type).To(Equal(v1.NodeMemoryPressure)) g.Expect(nodes[0].Status.Conditions[0].Status).To(Equal(v1.ConditionTrue)) g.Expect(nodes[0].Status.NodeInfo.KubeletVersion).To(Equal("1.9.9")) nodes, err = GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "nonexistent", -1) g.Expect(err).To(BeNil()) g.Expect(nodes).To(HaveLen(0)) } func TestGetNodes_ShouldRespectTheWaitForNumNodesArg(t *testing.T) { t.Parallel() mockClient := armhelpers.MockAKSEngineClient{MockKubernetesClient: &armhelpers.MockKubernetesClient{}} logger := log.NewEntry(log.New()) apiserverURL := "https://apiserver" kubeconfig := "kubeconfig" timeout := time.Second * 1 nodes, err := GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "", 2) g := NewGomegaWithT(t) g.Expect(err).To(BeNil()) g.Expect(nodes).To(HaveLen(2)) g.Expect(nodes[0].Name).To(Equal(fmt.Sprintf("%s-1234", common.LegacyControlPlaneVMPrefix))) g.Expect(nodes[0].Status.Conditions[0].Type).To(Equal(v1.NodeReady)) g.Expect(nodes[0].Status.Conditions[0].Status).To(Equal(v1.ConditionTrue)) g.Expect(nodes[0].Status.NodeInfo.KubeletVersion).To(Equal("1.9.10")) g.Expect(nodes[1].Name).To(Equal("k8s-agentpool3-1234")) g.Expect(nodes[1].Status.Conditions[0].Type).To(Equal(v1.NodeMemoryPressure)) g.Expect(nodes[1].Status.Conditions[0].Status).To(Equal(v1.ConditionTrue)) g.Expect(nodes[1].Status.NodeInfo.KubeletVersion).To(Equal("1.9.9")) // waiting for more nodes than the API returns should timeout nodes, err = GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "", 3) var mostRecentGetNodesErr error g.Expect(err).NotTo(BeNil()) g.Expect(err.Error()).To(Equal(fmt.Sprintf("call to GetNodes timed out: %s", mostRecentGetNodesErr))) g.Expect(nodes).To(BeNil()) // waiting for fewer nodes than the API returns should timeout nodes, err = GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "", 1) g.Expect(err).NotTo(BeNil()) g.Expect(err.Error()).To(Equal(fmt.Sprintf("call to GetNodes timed out: %s", mostRecentGetNodesErr))) g.Expect(nodes).To(BeNil()) // filtering by pool name and and the waiting for the expected node count nodes, err = GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "agentpool3", 1) g.Expect(err).To(BeNil()) g.Expect(nodes).To(HaveLen(1)) g.Expect(nodes[0].Name).To(Equal("k8s-agentpool3-1234")) g.Expect(nodes[0].Status.Conditions[0].Type).To(Equal(v1.NodeMemoryPressure)) g.Expect(nodes[0].Status.Conditions[0].Status).To(Equal(v1.ConditionTrue)) g.Expect(nodes[0].Status.NodeInfo.KubeletVersion).To(Equal("1.9.9")) } func TestGetNodes_ShouldReturnAMeaningfulTimeoutErrorWhenK8sAPIFailsToListNodes(t *testing.T) { t.Parallel() mockClient := armhelpers.MockAKSEngineClient{MockKubernetesClient: &armhelpers.MockKubernetesClient{ FailListNodes: true, }} logger := log.NewEntry(log.New()) apiserverURL := "https://apiserver" kubeconfig := "kubeconfig" timeout := time.Second * 1 // set the timeout value high enough to allow for a single attempt nodes, err := GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "", -1) mostRecentGetNodesErr := errors.New("ListNodes failed") g := NewGomegaWithT(t) g.Expect(err).NotTo(BeNil()) g.Expect(err.Error()).To(Equal(fmt.Sprintf("call to GetNodes timed out: %s", mostRecentGetNodesErr))) g.Expect(nodes).To(BeNil()) } func TestGetNodes_ShouldReturnAVanillaTimeoutErrorIfOccursBeforeASingleRequest(t *testing.T) { t.Parallel() mockClient := armhelpers.MockAKSEngineClient{MockKubernetesClient: &armhelpers.MockKubernetesClient{}} logger := log.NewEntry(log.New()) apiserverURL := "https://apiserver" kubeconfig := "kubeconfig" timeout := time.Second * 0 // by setting the timeout to 0 we time out immediately nodes, err := GetNodes(&mockClient, logger, apiserverURL, kubeconfig, timeout, "", -1) var mostRecentGetNodesErr error g := NewGomegaWithT(t) g.Expect(err).NotTo(BeNil()) g.Expect(err.Error()).To(Equal(fmt.Sprintf("call to GetNodes timed out: %s", mostRecentGetNodesErr))) g.Expect(nodes).To(BeNil()) } func ExamplePrintNodes() { var nodes []v1.Node node := v1.Node{} node.Name = fmt.Sprintf("%s-1234", common.LegacyControlPlaneVMPrefix) node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{Type: v1.NodeReady, Status: v1.ConditionTrue}) node.Status.NodeInfo.KubeletVersion = "1.10.0" node.Status.NodeInfo.OSImage = "my-os" node.Status.NodeInfo.KernelVersion = "3.1.4" nodes = append(nodes, node) PrintNodes(nodes) // Output: NODE STATUS VERSION OS KERNEL // k8s-master-1234 Ready 1.10.0 my-os 3.1.4 }
package api_test import ( "context" "net/http" "reflect" "strings" "testing" "github.com/chanioxaris/go-datagovgr/datagovgrtest" "github.com/jarcoal/httpmock" ) func TestTelcos_IndicatorsAndStatistics_Success(t *testing.T) { ctx := context.Background() fixture := datagovgrtest.NewFixture(t) httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder( http.MethodGet, fixture.URLPaths.IndicatorsAndStatistics, httpmock.NewJsonResponderOrPanic(http.StatusOK, fixture.MockData.IndicatorsAndStatistics), ) got, err := fixture.API.Telcos.IndicatorsAndStatistics(ctx) if err != nil { t.Fatalf("Unexpected error %v", err) } if !reflect.DeepEqual(got, fixture.MockData.IndicatorsAndStatistics) { t.Fatalf("Expected data %+v, but got %+v", fixture.MockData.IndicatorsAndStatistics, got) } } func TestTelcos_IndicatorsAndStatistics_Error(t *testing.T) { ctx := context.Background() fixture := datagovgrtest.NewFixture(t) expectedError := "unexpected status code" httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder( http.MethodGet, fixture.URLPaths.IndicatorsAndStatistics, httpmock.NewJsonResponderOrPanic(http.StatusInternalServerError, nil), ) _, err := fixture.API.Telcos.IndicatorsAndStatistics(ctx) if err == nil { t.Fatal("Expected error, but got nil") } if !strings.Contains(err.Error(), expectedError) { t.Fatalf(`Expected error to contain "%v", but got "%v"`, expectedError, err) } }
package testdata import ( "bytes" "io" "os" "path/filepath" "runtime" ) // UCDReader returns reader for the given ucd file for testing. func UCDReader(file string) (io.Reader, error) { data, err := os.ReadFile(UCDPath(file)) if err != nil { return nil, err } return bytes.NewReader(data), nil } // UCDPath returns path for the given ucd file. func UCDPath(file string) string { _, pkgdir, _, ok := runtime.Caller(0) if !ok { panic("no debug info") } return filepath.Join(filepath.Dir(pkgdir), "ucd", file) }
package odder import "net/rpc" func (odderClient *OdderClient) IsOdd(n int) (even bool, err error) { reply := &OdderIsOddReply{} err = odderClient.client.Call("OdderServer.IsOdd", &OdderIsOddArgs{N: n}, reply) if err != nil { reply.Err = err } return reply.Even, reply.Err } func (odderClient *OdderClient) CreateAsync(n int) (call *rpc.Call) { return odderClient.client.Go("OdderServer.IsOdd", &OdderIsOddArgs{N: n}, &OdderIsOddReply{}, nil) }
package chessboard import "fmt" type squareCoordinates struct { x uint8 y uint8 } func (s squareCoordinates) getX() uint8 { return s.x } func (s squareCoordinates) getY() uint8 { return s.y } func (s squareCoordinates) getXAsIndex() int { return int(s.x - 'A') } func (s squareCoordinates) getYAsIndex() int { return int(s.y - '1') } func (s squareCoordinates) String() string { return fmt.Sprintf("%s%s", string(s.x), string(s.y)) } func newSquareCoordinates(x, y uint8) squareCoordinates { return squareCoordinates{ x: x, y: y, } } func newSquareCoordinatesFromIndex(x, y int) squareCoordinates { return squareCoordinates{ x: uint8(x + 'A'), y: uint8(y + '1'), } }
package main import ( "crypto/sha1" "fmt" "io" "log" "os" ) func main() { files := []string{"file1.txt", "file2.txt"} for _, file := range files { f, err := os.Open(file) if err != nil { log.Fatal(err) } defer f.Close() h := sha1.New() if _, err := io.Copy(h, f); err != nil { log.Fatal(err) } fmt.Printf("'%s' sha1: '% x'\n", file, h.Sum(nil)) } }
package cli import ( "flag" "testing" ) func TestIsFlagSetStd(t *testing.T) { fs := flag.NewFlagSet("foo", flag.PanicOnError) fs.Int("width", 10, "width of rect") fs.String("name", "", "name hint here") fs.Parse([]string{""}) if IsFlagSet(fs, "width") { t.Error("width did not set yet") } if IsFlagSet(fs, "name") { t.Error("name did not set yet") } fs.Parse([]string{"--width", "42"}) if !IsFlagSet(fs, "width") { t.Error("width must be set") } if IsFlagSet(fs, "name") { t.Error("name did not set yet") } if IsFlagSet(fs, "bad") { t.Error("unknown flag cannot be set") } } // func TestIsFlagSetGetopt(t *testing.T) { // fs := getopt.NewFlagSet("foo", flag.PanicOnError) // fs.Int("width", 10, "width of rect") // fs.String("name", "", "name hint here") // fs.Alias("w", "width") // fs.Alias("n", "name") // // //fs.Parse([]string{""}) // if IsFlagSet(fs, "width") || IsFlagSet(fs, "w") { // t.Error("width did not set yet") // } // if IsFlagSet(fs, "name") || IsFlagSet(fs, "n") { // t.Error("name did not set yet") // } // // e := fs.Parse([]string{"--width", "tt", "rest", "args"}) // if e != nil { // t.Errorf("Parse failed: %v", e) // } // if !IsFlagSet(fs, "width") { // t.Errorf("width must be set, %v, %v", fs, fs.FlagSet) // } // if !IsFlagSet(fs, "w") { // t.Error("w must be set") // } // if IsFlagSet(fs, "name") { // t.Error("name did not set yet") // } // if IsFlagSet(fs, "n") { // t.Error("name did not set yet") // } // // if IsFlagSet(fs, "bad") { // t.Error("unknown flag cannot be set") // } // }
package handlers import ( "net/http" "net/http/httptest" "net/url" "testing" "github.com/stretchr/testify/assert" ) func TestWellKnownPomeriumHandler(t *testing.T) { t.Parallel() t.Run("cors", func(t *testing.T) { authenticateURL, _ := url.Parse("https://authenticate.example.com") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodOptions, "/", nil) r.Header.Set("Origin", authenticateURL.String()) r.Header.Set("Access-Control-Request-Method", http.MethodGet) WellKnownPomerium(authenticateURL).ServeHTTP(w, r) assert.Equal(t, http.StatusNoContent, w.Result().StatusCode) }) t.Run("links", func(t *testing.T) { authenticateURL, _ := url.Parse("https://authenticate.example.com") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "https://route.example.com", nil) WellKnownPomerium(authenticateURL).ServeHTTP(w, r) assert.JSONEq(t, `{ "authentication_callback_endpoint": "https://authenticate.example.com/oauth2/callback", "frontchannel_logout_uri": "https://route.example.com/.pomerium/sign_out", "jwks_uri": "https://route.example.com/.well-known/pomerium/jwks.json" }`, w.Body.String()) }) }
package queue import ( "errors" ) const ( ErrPop = "error pop" ) type Queue []interface{} func (q *Queue) Push(item interface{}) { *q = append(*q, item) } func (q *Queue) Pop() (interface{}, error) { if len(*q) <= 0 { return nil, errors.New(ErrPop) } res := (*q)[0] *q = (*q)[1:] return res, nil } func (q *Queue) Empty() bool { if len(*q) == 0 { return true } return false }
package godoc_test import ( "fmt" "github.com/lovexiaoe/golangpros/basics/godoc" ) // 以"包名_test"作为包名, // 该go文件的名称必须以"_test"作为后缀,不然编译会报错。 //以Example作为方法名,在godoc中作为包的例子。 func Example() { oa := godoc.ObjectA{ Name: "john", } fmt.Println("oa.Name", oa.GetOAName()) } // Example+类型,可以作为类型的例子。 func ExampleObjectA() { fmt.Println("ObjectA 的例子命名为ExampleObjectA") } // Example+类型+_+方法名,可以作为方法的例子。 func ExampleObjectA_GetOAName() { fmt.Println("ObjectA.GetOAName 的例子命名为ExampleObjectA_GetOAName") }
package shared import ( "errors" "fmt" "github.com/gorilla/websocket" "github.com/songgao/water" "log" "strings" "sync" "sync/atomic" "time" ) var lastCommandId uint64 = 0 var defaultMac = [6]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} var learnMac bool = false var allowClientToClient bool = false var macTable map[MacAddr]*Socket = make(map[MacAddr]*Socket) var macLock sync.RWMutex var allSockets = make(map[*Socket]*Socket) var allSocketsLock sync.RWMutex func FindSocketByMAC(mac MacAddr) *Socket { macLock.RLock() defer macLock.RUnlock() return macTable[mac] } func BroadcastMessage(msgType int, data []byte, skip *Socket) { allSocketsLock.RLock() targetList := make([]*Socket, 0) for _, v := range allSockets { if v == skip { continue } targetList = append(targetList, v) } allSocketsLock.RUnlock() for _, v := range targetList { v.WriteMessage(msgType, data) } } type CommandHandler func(args []string) error type Socket struct { connId string conn *websocket.Conn iface *water.Interface noIfaceReader bool writeLock *sync.Mutex wg *sync.WaitGroup handlers map[string]CommandHandler closechan chan bool closechanopen bool mac MacAddr } func SetMACLearning(enable bool) { learnMac = enable } func SetClientToClient(enable bool) { allowClientToClient = enable } func MakeSocket(connId string, conn *websocket.Conn, iface *water.Interface, noIfaceReader bool) *Socket { return &Socket{ connId: connId, conn: conn, iface: iface, noIfaceReader: noIfaceReader, writeLock: &sync.Mutex{}, wg: &sync.WaitGroup{}, handlers: make(map[string]CommandHandler), closechan: make(chan bool), closechanopen: true, mac: defaultMac, } } func (s *Socket) AddCommandHandler(command string, handler CommandHandler) { s.handlers[command] = handler } func (s *Socket) Wait() { s.wg.Wait() } func (s *Socket) rawSendCommand(commandId string, command string, args ...string) error { return s.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("%s|%s|%s", commandId, command, strings.Join(args, "|")))) } func (s *Socket) SendCommand(command string, args ...string) error { return s.rawSendCommand(fmt.Sprintf("%d", atomic.AddUint64(&lastCommandId, 1)), command, args...) } func (s *Socket) WriteMessage(msgType int, data []byte) error { s.writeLock.Lock() err := s.conn.WriteMessage(msgType, data) s.writeLock.Unlock() if err != nil { log.Printf("[%s] Error writing packet to WS: %v", s.connId, err) s.Close() } return err } func (s *Socket) closeDone() { s.wg.Done() s.Close() } func (s *Socket) SetInterface(iface *water.Interface) error { s.writeLock.Lock() defer s.writeLock.Unlock() if s.iface != nil { return errors.New("Cannot re-define interface. Already set.") } s.iface = iface s.tryServeIfaceRead() return nil } func (s *Socket) setMACFrom(msg []byte) { srcMac := GetSrcMAC(msg) if !MACIsUnicast(srcMac) || srcMac == s.mac { return } macLock.Lock() defer macLock.Unlock() if s.mac != defaultMac { delete(macTable, s.mac) } if macTable[srcMac] != nil { s.mac = defaultMac log.Printf("[%d] MAC collision. Killing.", s.connId) s.Close() return } s.mac = srcMac macTable[srcMac] = s } func (s *Socket) Close() { s.writeLock.Lock() defer s.writeLock.Unlock() s.conn.Close() if s.iface != nil && !learnMac { s.iface.Close() } if s.closechanopen { s.closechanopen = false close(s.closechan) } if s.mac != defaultMac { macLock.Lock() delete(macTable, s.mac) s.mac = defaultMac macLock.Unlock() } allSocketsLock.Lock() delete(allSockets, s) allSocketsLock.Unlock() } func (s *Socket) tryServeIfaceRead() { if s.iface == nil || s.noIfaceReader { return } s.wg.Add(1) go func() { defer s.closeDone() packet := make([]byte, 2000) for { n, err := s.iface.Read(packet) if err != nil { log.Printf("[%s] Error reading packet from tun: %v", s.connId, err) return } err = s.WriteMessage(websocket.BinaryMessage, packet[:n]) if err != nil { return } } }() } func (s *Socket) Serve() { s.writeLock.Lock() defer s.writeLock.Unlock() s.tryServeIfaceRead() allSocketsLock.Lock() allSockets[s] = s allSocketsLock.Unlock() s.wg.Add(1) go func() { defer s.closeDone() for { msgType, msg, err := s.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { log.Printf("[%s] Error reading packet from WS: %v", s.connId, err) } return } if msgType == websocket.BinaryMessage { if learnMac && len(msg) >= 14 { s.setMACFrom(msg) if allowClientToClient { dest := GetDestMAC(msg) isUnicast := MACIsUnicast(dest) var sd *Socket if isUnicast { sd = FindSocketByMAC(dest) if sd != nil { sd.WriteMessage(websocket.BinaryMessage, msg) continue } } else { BroadcastMessage(websocket.BinaryMessage, msg, s) } } } if s.iface == nil { continue } s.iface.Write(msg) } else if msgType == websocket.TextMessage { str := strings.Split(string(msg), "|") if len(str) < 2 { log.Printf("[%s] Invalid in-band command structure", s.connId) continue } commandId := str[0] commandName := str[1] if commandName == "reply" { commandResult := "N/A" if len(str) > 2 { commandResult = str[2] } log.Printf("[%s] Got command reply ID %s: %s", s.connId, commandId, commandResult) continue } handler := s.handlers[commandName] if handler == nil { err = errors.New("Unknown command") } else { err = handler(str[2:]) } if err != nil { log.Printf("[%s] Error in in-band command %s: %v", s.connId, commandName, err) } s.rawSendCommand(commandId, "reply", fmt.Sprintf("%v", err == nil)) } } }() timeout := time.Duration(30) * time.Second lastResponse := time.Now() s.conn.SetPongHandler(func(msg string) error { lastResponse = time.Now() return nil }) s.wg.Add(1) go func() { defer s.closeDone() for { select { case <-time.After(timeout / 2): if time.Now().Sub(lastResponse) > timeout { log.Printf("[%s] Ping timeout", s.connId) return } err := s.WriteMessage(websocket.PingMessage, []byte{}) if err != nil { return } case <-s.closechan: return } } }() }
package saetoauthv2 import ( ) //结构体 type AuthV2 struct { ClientID string ClientSecret string AccessToken string RefreshToken string URL string Host string TimeOut int ConnectTimeOut int SslVerifyPeer bool Format string DecodeJson bool HttpInfo string UserAgent string Debug bool Boundary string }