blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
108
path
stringlengths
2
210
src_encoding
stringclasses
12 values
length_bytes
int64
13
5.82M
score
float64
2.52
5.22
int_score
int64
3
5
detected_licenses
listlengths
0
161
license_type
stringclasses
2 values
detected_licenses_right
listlengths
0
161
license_type_right
stringclasses
2 values
text
stringlengths
13
6.48M
download_success
bool
1 class
102828c449327d82cfe27d04ec2883e7960a8d69
Go
godoctor/godoctor
/analysis/names/testdata/src/foo/vendor/bar/bar.go
UTF-8
272
2.96875
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package bar func Exported() string { return "bar" } type I interface { Method() int } type t int func (t) Method() float64 { return 1.234 } func callInterface(i I) { i.Method() } type i struct { Method func() float64 // Not actually a method -- this is a field! }
true
6805f40ec61be585ca32ed8a1cc8471cc64c8c6b
Go
shelleyvip/golang
/new巩固/31_io.copy.go
UTF-8
371
2.78125
3
[]
no_license
[]
no_license
package main import ( "github.com/labstack/gommon/log" "os" ) func v1() { var f *os.File var err error if len(os.Args) >1{ f,err = os.Open(os.Args[1]) if err != nil{ log.Fatal(err) } }else { f = os.Stdin } buf := make([]byte,1024) for{ n,err := f.Read(buf) if err != nil{ return } os.Stdout.Write(buf[:n]) } } func main() { v1() }
true
96f676069850a4f0070c74a9c008e03fbc067c59
Go
chenqinghe/nacos-go-sdk
/discovery/lb/random.go
UTF-8
428
2.90625
3
[]
no_license
[]
no_license
package lb import ( "math/rand" "reflect" "time" ) type Random struct { r *rand.Rand } func NewRandom(seed ...int64) *Random { if len(seed) == 0 { return &Random{r: rand.New(rand.NewSource(time.Now().UnixNano()))} } return &Random{r: rand.New(rand.NewSource(seed[0]))} } func (r *Random) Select(instances interface{}) interface{} { v := reflect.ValueOf(instances) return v.Index(r.r.Intn(v.Len())).Interface() }
true
9837bf4832adbc85ab549615b77b8b6ed35d29aa
Go
Rallstad/Heis
/go/src/network/network.go
UTF-8
1,967
3.03125
3
[]
no_license
[]
no_license
package network import ( "net" "os" "strings" "fmt" ) func ClientConnectUDP(port string)*net.UDPConn{ adress,err :=net.ResolveUDPAddr("udp","129.241.187.255"+port) if (err != nil){ fmt.Println(adress,err) } connection,err := net.DialUDP("udp",nil,adress) if err == nil{ fmt.Println("Connection achieved at : ",adress) } return connection } func ServerConnectUDP(port string)*net.UDPConn{ adress,err := net.ResolveUDPAddr("udp",port) if err != nil { fmt.Println("Error: " , err) os.Exit(0) } connection, err := net.ListenUDP("udp",adress) if err != nil { fmt.Println("Error: " , err) os.Exit(0) } return connection } func ClientSend(conn *net.UDPConn,msg []byte ){ _,_= conn.Write(msg) } func ServerListenUDP(conn *net.UDPConn,buf []byte)int{ n,_,_ := conn.ReadFromUDP(buf) return n } func CheckNetworkConnection(networkAccessChannel chan bool){ for{ ip := GetNetworkIP() if(ip == "::1"){ networkAccessChannel<-false } } } func GetNetworkIP()string{ ipAdd,_ := net.InterfaceAddrs() ip:=strings.Split(ipAdd[1].String(),"/")[0] return ip } //Main function for testing /// // func main(){ // ListenPort := ":54321" // SendPort := ":12345" // connectionChanListen := make(chan *net.UDPConn,10) // connectionChanSend := make(chan *net.UDPConn) // waitChan := make(chan int) // recvChan := make(chan UDPmsg,5) // fmt.Println("Starting server...") // time.Sleep(time.Second *1) // go ServerConnectUDP(ListenPort,connectionChanListen) // go ServerListenUDP(connectionChanListen, recvChan) // go serverPrint(recvChan) // go ClientConnectUDP(SendPort,connectionChanSend) // go ClientSend(connectionChanSend) // //fmt.Println("Goroutines initialized") // <-waitChan // } // func serverPrint(recvChan chan UDPmsg){ // for { // fmt.Println("waiting ..") // printmsg := <-recvChan // fmt.Println("MSG: ",printmsg.msg) // } // }
true
5e7e6efb6be7807d0d547130124d514be58aa64f
Go
bhupathi-skyflow/skyflow-go
/errors/error_codes.go
UTF-8
352
2.8125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package errors // ErrorCodesEnum - Enum defines the list of error codes/categorization of errors in Skyflow. type ErrorCodesEnum string // Defining the values of Error code Enum const ( // Server - Represents server side error Server ErrorCodesEnum = "Server" // InvalidInput - Input passed was not invalid format InvalidInput = "InvalidInput" )
true
5e810c415bde65a46e172415207e76de820db172
Go
bingzhao0719/diary
/config/Config.go
UTF-8
1,150
3.015625
3
[]
no_license
[]
no_license
package config import ( "bufio" "encoding/json" "fmt" "os" ) type Config struct { AppName string `json:"app_name"` AppMode string `json:"app_mode"` AppHost string `json:"app_host"` AppPort string `json:"app_port"` Database DatabaseConfig `database` } type DatabaseConfig struct { Driver string `json:"driver"` User string `json:"user"` Password string `json:"password"` Host string `json:"host"` Port string `json:"port"` DbName string `json:"db_name"` Charset string `json:"charset"` ShowSql bool `json:"show_sql"` } func init() { fmt.Println("config init") cfg,err := ParseConfig("./config/app.json") if err != nil{ fmt.Println(err) return } fmt.Println(cfg.AppName,cfg.AppHost) fmt.Println(cfg.Database) } var _cfg *Config func GetConfig() *Config { return _cfg } func ParseConfig(path string) (*Config,error) { file ,err := os.Open(path) if err != nil{ panic(err) } defer file.Close() reader := bufio.NewReader(file) decoder := json.NewDecoder(reader) if err :=decoder.Decode(&_cfg);err != nil{ return _cfg,err } fmt.Printf("ParseConfig:%p\n",_cfg) return _cfg,nil }
true
fdbea888cc4a1ccfdde3ea70f2c7a1cc0a69d202
Go
relloyd/halfpipe
/transform/consumer.go
UTF-8
770
2.8125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package transform import ( "sync" "github.com/relloyd/halfpipe/stream" ) // Consumers of components' channels. type consumers struct { sync.RWMutex internal map[string]consumer } type consumer map[string]*consumerData // use ptr to consumerData since we can't do assignments like: m["key"].structVar = 1 type consumerData struct { callbackChan chan chan stream.Record // the inputChan that the requester want to be notified on. lastSentChan chan stream.Record // the last outputChan we sent to requestingStepName's callbackChan. } func (c *consumers) Load(key string) (retval consumer) { c.RLock() retval = c.internal[key] c.RUnlock() return } func (c *consumers) Store(key string, value consumer) { c.Lock() c.internal[key] = value c.Unlock() }
true
236597fc36b9869170078cc0582238b80f7f0357
Go
nju04zq/algorithm_code
/medium/152_Maximum_Product_Subarray/max.go
UTF-8
1,451
3.265625
3
[]
no_license
[]
no_license
package main import "fmt" import ( "math/rand" "time" ) func max(a, b int) int { if a > b { return a } else { return b } } func min(a, b int) int { if a < b { return a } else { return b } } func maxProduct(nums []int) int { if len(nums) == 0 { return 0 } maxSub, maxProduct, minProduct := nums[0], nums[0], nums[0] for i, num := range nums { if i == 0 { continue } if num == 0 { maxProduct, minProduct = 0, 0 } else if num > 0 { maxProduct = max(maxProduct*num, num) minProduct = min(minProduct*num, num) } else { tmp1 := max(minProduct*num, num) tmp2 := min(maxProduct*num, num) maxProduct, minProduct = tmp1, tmp2 } maxSub = max(maxSub, maxProduct) } return maxSub } func MakeRandArray() []int { maxLen, maxElement := 10, 20 r := rand.New(rand.NewSource(time.Now().UnixNano())) len := r.Int()%maxLen + 1 a := make([]int, len) for i := 0; i < len; i++ { a[i] = r.Int()%maxElement - 8 } return a } func maxProductBF(nums []int) int { maxSub := nums[0] for i := 0; i < len(nums); i++ { product := 1 for j := i; j < len(nums); j++ { product *= nums[j] maxSub = max(maxSub, product) } } return maxSub } func testMaxProduct(nums []int) { res := maxProduct(nums) ans := maxProductBF(nums) if res != ans { panic(fmt.Errorf("nums %v, get %d, expect %d", nums, res, ans)) } } func main() { for i := 0; i < 100000; i++ { testMaxProduct(MakeRandArray()) } }
true
a01cf21ce3af0f3a98837d8d9cd54ab6af11d024
Go
elvin-du/algorithm-lab
/code-interviews/quick-sort.go
UTF-8
516
3.28125
3
[]
no_license
[]
no_license
package code_interviews func QuickSort(data []int) { quickSort(data, 0, len(data)-1) } func quickSort(data []int, l, h int) { if h <= l { return } p := data[l] left, right := l, h for ; l < h; { for ; l < h; { if data[h] < p { data[h], data[l] = data[l], data[h] l++ break } else { h-- } } for ; l < h; { if data[l] > p { data[h], data[l] = data[l], data[h] h-- break } else { l++ } } } quickSort(data, left, h) quickSort(data, h+1, right) }
true
847100ebc0603ff370797a4083ea89d7da9a762a
Go
leolinf/golang-demo
/crawler/zhenai/parser/citylist.go
UTF-8
576
2.796875
3
[]
no_license
[]
no_license
package parser import ( "golang-demo/crawler/engine" "regexp" ) const cityListRe = `<a href="(http://www.zhenai.com/zhenghun/[a-z0-9]+)"[^>]*>([^<]+)</a>` func ParseCityList(contents []byte) engine.ParserResult { re := regexp.MustCompile(cityListRe) matchs := re.FindAllSubmatch(contents, -1) result := engine.ParserResult{} for _, m := range matchs { result.Item = append(result.Item, "City "+string(m[2])) result.Requests = append(result.Requests, engine.Request{ Url: string(m[1]), ParserFunc: ParseCity, }) break } return result }
true
ba0b865f7ebaee243cf7626ada2c391db486dd82
Go
Reg1nleifr/go-tour
/09 routines and channels/rac.go
UTF-8
1,488
4.125
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" "time" ) func say(msg string) { for i := 0; i < 2; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(msg) } } func sum(toSum []int, c chan int) { sum := 0 for _, i := range toSum { sum += i } c <- sum // send sum to c } func fibonacci(n int, c chan int) { x, y := 0, 1 for i := 0; i < n; i++ { c <- x time.Sleep(100 * time.Millisecond) x, y = y, x+y } close(c) } func fibonacciSelect(c, quit chan int) { x, y := 0, 1 for { select { case c <- x: x, y = y, x+y case <-quit: return } } } func main() { // Basic routine go say("Hello") say("世界") // Channel Routine fmt.Println() fmt.Println("## Channel synchronized routine") s := []int{7, 2, 8, -9, 4, 0} // Channel creation c := make(chan int) go sum(s[:len(s)/2], c) go sum(s[len(s)/2:], c) // By default, sends and receives block until the other side is ready x, y := <-c, <-c //recive from c into two variables fmt.Println(x, y, x+y) // Range / Close with channels fmt.Println() fmt.Println("## Channels and close <- fibonacci") c = make(chan int, 10) go fibonacci(cap(c), c) for i := range c { fmt.Println(i) } fmt.Println() fmt.Println("## Select with channels") c1 := make(chan int) quit := make(chan int) go func() { for i := 0; i < 10; i++ { fmt.Println(<-c1) } quit <- -1 << 12 // Ganz egal was quit zugeordnet wird es geht nur darum ob im quit was reinkommt (siehe switch) }() fibonacciSelect(c1, quit) }
true
e352da14477e2a360a753914de41a080711930c8
Go
Bexultan2323/finalproject
/cmd/web/handlers.go
UTF-8
2,041
2.671875
3
[]
no_license
[]
no_license
package main import ( "aitu.com/snippetbox/pkg/forms" "aitu.com/snippetbox/pkg/models" "errors" "fmt" "net/http" "strconv" ) func (app *application) home(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { app.notFound(w) return } snippet, err := app.snippets.Latest() if err != nil { app.serverError(w, err) return } app.render(w, r, "home.page.tmpl.html", &templateData{ Snippets: snippet, }) } func (app *application) showSnippet(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(r.URL.Query().Get(":id")) if err != nil || id < 1 { app.notFound(w) return } snippet, err := app.snippets.Get(id) if err != nil { if errors.Is(err, models.ErrNoRecord) { app.notFound(w) } else { app.serverError(w, err) } return } flash := app.session.PopString(r, "flash") app.render(w, r, "show.page.tmpl.html", &templateData{ Flash:flash, Snippet: snippet, }) } func (app *application) createSnippetForm(w http.ResponseWriter, r *http.Request) { app.render(w, r, "create.page.tmpl.html", &templateData{ Form: forms.New(nil), }) } func (app *application) createSnippet(w http.ResponseWriter, r *http.Request) { err := r.ParseForm() if err != nil { app.clientError(w, http.StatusBadRequest) return } //form := forms.New(r.PostForm) //form.Required("title", "content", "expires") //form.MaxLength("title", 100) //form.PermittedValues("expires", "2021-12-15", "2020-11-16", "2020-11-11") form := forms.New(r.PostForm) form.Required("title", "content", "expires","created","profits") form.MaxLength("title", 100) if !form.Valid() { app.render(w, r, "create.page.tmpl.html", &templateData{Form: form}) return } id, err := app.snippets.Insert(form.Get("title"), form.Get("content"),form.Get("created"), form.Get("expires"),form.Get("profits")) if err != nil { app.serverError(w, err) return } app.session.Put(r, "flash", "Company successfully added!") http.Redirect(w, r, fmt.Sprintf("/snippet/%d", id), http.StatusSeeOther) }
true
a45b2cbe6b382f3d4de20990930b9efe39f461e9
Go
akellbl4/remark42
/backend/app/notify/slack_test.go
UTF-8
4,224
2.578125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package notify import ( "context" "log" "net/http" "net/http/httptest" "testing" "github.com/go-chi/chi/v5" "github.com/slack-go/slack" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/umputun/remark42/backend/app/store" ) func TestSlack_New(t *testing.T) { ts := newMockSlackServer() defer ts.Close() tb, err := ts.newClient("general") assert.NoError(t, err) assert.NotNil(t, tb) assert.Equal(t, "C12345678", tb.channelID) _, err = ts.newClient("unknown-channel") require.Error(t, err) assert.Contains(t, err.Error(), "no such channel") } func TestSlack_Send(t *testing.T) { ts := newMockSlackServer() defer ts.Close() tb, err := ts.newClient("general") assert.NoError(t, err) assert.NotNil(t, tb) c := store.Comment{Text: "some text", ParentID: "1", ID: "999"} c.User.Name = "from" cp := store.Comment{Text: "some parent text"} cp.User.Name = "to" err = tb.Send(context.TODO(), Request{Comment: c, parent: cp}) assert.NoError(t, err) c.PostTitle = "test title" err = tb.Send(context.TODO(), Request{Comment: c, parent: cp}) assert.NoError(t, err) err = tb.Send(context.TODO(), Request{Comment: c, parent: cp}) assert.NoError(t, err) c.PostTitle = "[test title]" err = tb.Send(context.TODO(), Request{Comment: c, parent: cp}) assert.NoError(t, err) tb, err = ts.newClient("general") assert.NoError(t, err) ts.isServerDown = true err = tb.Send(context.TODO(), Request{Comment: c, parent: cp}) require.Error(t, err) assert.Contains(t, err.Error(), "slack server error", "send on broken client") } func TestSlack_Name(t *testing.T) { ts := newMockSlackServer() defer ts.Close() tb, err := ts.newClient("general") assert.NoError(t, err) assert.NotNil(t, tb) assert.Equal(t, "slack: general (C12345678)", tb.String()) } func TestSlack_SendVerification(t *testing.T) { ts := newMockSlackServer() defer ts.Close() tb, err := ts.newClient("general") assert.NoError(t, err) assert.NotNil(t, tb) err = tb.SendVerification(context.TODO(), VerificationRequest{}) assert.NoError(t, err) } type mockSlackServer struct { *httptest.Server isServerDown bool } func (ts *mockSlackServer) newClient(channelName string) (*Slack, error) { return NewSlack("any-token", channelName, slack.OptionAPIURL(ts.URL+"/")) } func newMockSlackServer() *mockSlackServer { mockServer := mockSlackServer{} router := chi.NewRouter() router.Post("/conversations.list", func(w http.ResponseWriter, r *http.Request) { s := `{ "ok": true, "channels": [ { "id": "C12345678", "name": "general", "is_channel": true, "is_group": false, "is_im": false, "created": 1503888888, "is_archived": false, "is_general": false, "unlinked": 0, "name_normalized": "random", "is_shared": false, "parent_conversation": null, "creator": "U12345678", "is_ext_shared": false, "is_org_shared": false, "pending_shared": [], "pending_connected_team_ids": [], "is_pending_ext_shared": false, "is_member": false, "is_private": false, "is_mpim": false, "previous_names": [], "num_members": 1 } ], "response_metadata": { "next_cursor": "" } }` _, _ = w.Write([]byte(s)) }) router.Post("/chat.postMessage", func(w http.ResponseWriter, r *http.Request) { if mockServer.isServerDown { w.WriteHeader(500) } else { s := `{ "ok": true, "channel": "C12345678", "ts": "1617008342.000100", "message": { "type": "message", "subtype": "bot_message", "text": "wowo", "ts": "1617008342.000100", "username": "slackbot", "bot_id": "B12345678" } }` _, _ = w.Write([]byte(s)) } }) router.NotFound(func(w http.ResponseWriter, r *http.Request) { log.Printf("..... 404 for %s .....\n", r.URL) }) mockServer.Server = httptest.NewServer(router) return &mockServer }
true
7454d05c4bb9d62ed0c5e19d8639d6f3598a0b3c
Go
enricodangelo/exercises-in-style
/go/src/misc/div_by_0.go
UTF-8
90
2.609375
3
[]
no_license
[]
no_license
package main import ( "fmt" ) func main() { var i float64 = 1 fmt.Println(i / 0.0) }
true
df9b362b5accb37726376d87d65fc3d4061e1f7c
Go
ZhangLi1995/learnGin
/_ginlearn/router/router.go
UTF-8
4,039
3.171875
3
[]
no_license
[]
no_license
package main import ( "fmt" "log" "net/http" "time" "github.com/gin-gonic/gin" ) /** * @Description: 默认服务器 */ func serve1() { router := gin.Default() router.GET("/", func(ctx *gin.Context) { ctx.String(http.StatusOK, "Hello World") }) router.Run(":8000") } /** * @Description: http 服务器 */ func serve2() { router := gin.Default() http.ListenAndServe(":8080", router) } /** * @Description: 自定义 http 服务配置 */ func serve3() { router := gin.Default() s := &http.Server{ Addr: ":8080", Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() } /** * @Description: 路由参数: API 参数 + URL 参数 */ func router1() { router := gin.Default() // 注意: /user/:name/ 会被重定向到 /user/:name router.GET("/user/:name", func(ctx *gin.Context) { name := ctx.Param("name") ctx.String(http.StatusOK, name) }) router.GET("/user/:name/*action", func(ctx *gin.Context) { name := ctx.Param("name") action := ctx.Param("action") message := name + " is " + action ctx.String(http.StatusOK, message) }) router.GET("/welcome", func(ctx *gin.Context) { name := ctx.DefaultQuery("name", "Guest") ctx.String(http.StatusOK, fmt.Sprintf("Hello %s ", name)) }) router.Run(":8000") } /** * @Description: 表单参数 */ func router2() { router := gin.Default() router.POST("/form", func(ctx *gin.Context) { type1 := ctx.DefaultPostForm("type", "alert") username := ctx.PostForm("username") password := ctx.PostForm("password") hobbys := ctx.PostFormArray("hobby") ctx.String(http.StatusOK, fmt.Sprintf("type is %v, username is %v, password is %v, hobby is %v", type1, username, password, hobbys)) }) router.Run(":9527") } /** * @Description: 单个文件上传 */ func router3() { router := gin.Default() // 设置最大内存限制为 8MB,默认为 32MB router.MaxMultipartMemory = 8 << 20 // 8MB router.POST("/upload", func(ctx *gin.Context) { file, _ := ctx.FormFile("file") // 单文件 log.Println(file.Filename) ctx.SaveUploadedFile(file, file.Filename) // 上传文件到具体的位置 /* 也可以直接使用 io 操作,拷贝文件数据 out, err := os.Create(filename) defer out.Close() _, err := io.Copy(out, file) */ ctx.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) }) router.Run(":8080") } /** * @Description: 多个文件上传 */ func router4() { router := gin.Default() // 设置最大内存限制为 8MB,默认为 32MB router.MaxMultipartMemory = 8 << 20 // 8MB router.POST("/upload", func(ctx *gin.Context) { form, err := ctx.MultipartForm() // 多文件 if err != nil { ctx.String(http.StatusBadRequest, fmt.Sprintf("get form err: %v", err)) return } files := form.File["files"] for _, file := range files { if err := ctx.SaveUploadedFile(file, file.Filename); err != nil { ctx.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %v", err)) return } } ctx.String(http.StatusOK, fmt.Sprintf("Uploaded successfully %v files ", len(files))) }) router.Run(":8080") } /** * @Description: 分组路由 */ func router5() { router := gin.Default() // group: v1 v1 := router.Group("/v1") { v1.GET("/login", loginEndpoint) v1.GET("/submit", submitEndpoint) v1.POST("/read", readEndpoint) } // group: v2 v2 := router.Group("/v2") { v2.GET("/login", loginEndpoint) v2.GET("/submit", submitEndpoint) v2.POST("/read", readEndpoint) } router.Run(":8080") } func loginEndpoint(ctx *gin.Context) { name := ctx.DefaultQuery("name", "Guest") ctx.String(http.StatusOK, fmt.Sprintf("Hello %v \n", name)) } func submitEndpoint(ctx *gin.Context) { name := ctx.DefaultQuery("name", "Guest") ctx.String(http.StatusOK, fmt.Sprintf("Hello %v \n", name)) } func readEndpoint(ctx *gin.Context) { name := ctx.DefaultQuery("name", "Guest") ctx.String(http.StatusOK, fmt.Sprintf("Hello %v \n", name)) }
true
187f08f8b6ae3db3a76f8bdc998540d240b547eb
Go
samonzeweb/godb
/transaction.go
UTF-8
2,002
2.875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package godb import ( "database/sql" "fmt" "time" ) // preparableAndQueryable represents either a Tx or DB. type preparableAndQueryable interface { Exec(query string, args ...interface{}) (sql.Result, error) Query(query string, args ...interface{}) (*sql.Rows, error) QueryRow(query string, args ...interface{}) *sql.Row Prepare(query string) (*sql.Stmt, error) } // Begin starts a new transaction, fails if there is already one. func (db *DB) Begin() error { if db.sqlTx != nil { return fmt.Errorf("Begin was called multiple times, sql transaction already exists") } startTime := time.Now() tx, err := db.sqlDB.Begin() consumedTime := timeElapsedSince(startTime) db.addConsumedTime(consumedTime) db.logExecution(consumedTime, "BEGIN") if err != nil { db.logExecutionErr(err, "BEGIN") return err } db.sqlTx = tx return nil } // Commit commits an existing transaction, fails if none exists. func (db *DB) Commit() error { if db.sqlTx == nil { return fmt.Errorf("Commit was called without existing sql transaction") } db.stmtCacheTx.clearWithoutClosingStmt() startTime := time.Now() err := db.sqlTx.Commit() consumedTime := timeElapsedSince(startTime) db.addConsumedTime(consumedTime) db.logExecution(consumedTime, "COMMIT") db.sqlTx = nil if err!=nil { db.logExecutionErr(err, "COMMIT") } return err } // Rollback rollbacks an existing transaction, fails if none exists. func (db *DB) Rollback() error { if db.sqlTx == nil { return fmt.Errorf("Rollback was called without existing sql transaction") } db.stmtCacheTx.clearWithoutClosingStmt() startTime := time.Now() err := db.sqlTx.Rollback() consumedTime := timeElapsedSince(startTime) db.addConsumedTime(consumedTime) db.logExecution(consumedTime, "ROLLBACK") if err!=nil { db.logExecutionErr(err, "ROLLBACK") } db.sqlTx = nil return err } // CurrentTx returns the current Tx (or nil). Don't commit or rollback it // directly ! func (db *DB) CurrentTx() *sql.Tx { return db.sqlTx }
true
5d7261a8d26c60b1aad04cc37f1946f162ab3467
Go
dmportella/golang-tutorial
/chapter3/methods.go
UTF-8
351
4.09375
4
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
package chapter3 import "fmt" type rectangle struct { width, height int } func (r *rectangle) area() int { return r.width * r.height } func (r *rectangle) perim() int { return 2*r.width + 2*r.height } func Methods() { rect := rectangle{width: 10, height: 5} fmt.Println(rect) fmt.Println("area: ", rect.area(), "perim: ", rect.perim()) }
true
f6752ed8da77d1ac2d7ecfb8ea732dc4baf73de6
Go
jhoscar1/golang-exercises
/composites/08/map.go
UTF-8
447
3.328125
3
[]
no_license
[]
no_license
package main import "fmt" func main() { friends := map[string][]string{ "oscar_jason": {"friends", "movies", "chicken fingers"}, "herren_josh": {"musicals", "movies", "teaching"}, "mansfield_june": {"ceramics", "movies", "savvy"}, } friends["steinberg_henry"] = []string{"printing", "games", "movies"} delete(friends, "oscar_jason") for _, v := range friends { for ind, item := range v { fmt.Println(ind, item) } } }
true
1072af871dc6018f0966c65d4bfdc19036f66b35
Go
team-e-org/backend
/app/helpers/error.go
UTF-8
966
2.609375
3
[]
no_license
[]
no_license
package helpers type AppError interface { AppError() Error() string } type InternalServerError struct { err error } func (e *InternalServerError) Error() string { return e.err.Error() } func (e *InternalServerError) AppError() {} func NewInternalServerError(err error) AppError { return &InternalServerError{err: err} } type Unauthorized struct { err error } func (e *Unauthorized) Error() string { return e.err.Error() } func (e *Unauthorized) AppError() {} func NewUnauthorized(err error) AppError { return &Unauthorized{err: err} } type NotFound struct { err error } func (e *NotFound) Error() string { return e.err.Error() } func (e *NotFound) AppError() {} func NewNotFound(err error) AppError { return &NotFound{err: err} } type BadRequest struct { err error } func (e *BadRequest) Error() string { return e.err.Error() } func (e *BadRequest) AppError() {} func NewBadRequest(err error) AppError { return &BadRequest{err: err} }
true
03bd5b4e82f9cbd3977867d16cc0a0f214f281ea
Go
dskloet/bitcoin
/src/bitcoin/bitstamp/orderbook.go
UTF-8
1,057
2.578125
3
[]
no_license
[]
no_license
package bitstamp import ( "github.com/dskloet/bitcoin/src/bitcoin" "strconv" ) type unparsedOrderBook struct { Timestamp string Bids [][]string Asks [][]string } func (client Client) OrderBook() ( bids []bitcoin.Order, asks []bitcoin.Order, err error) { var unparsed unparsedOrderBook err = getRequest(API_ORDER_BOOK, &unparsed) if err != nil { return } for _, unparsedBid := range unparsed.Bids { var price, amount float64 price, amount, err = parseFloatPair(unparsedBid) if err != nil { return } bids = append(bids, bitcoin.BuyOrder(price, amount)) } for _, unparsedAsk := range unparsed.Asks { var price, amount float64 price, amount, err = parseFloatPair(unparsedAsk) if err != nil { return } asks = append(asks, bitcoin.SellOrder(price, amount)) } return } func parseFloatPair(pair []string) (a, b float64, err error) { a, err = strconv.ParseFloat(pair[0], 64) if err != nil { return } b, err = strconv.ParseFloat(pair[1], 64) return }
true
98c010a548d2b5de333b5bf2395b8fb696fef636
Go
go-numb/go-ftx-bff
/models/time.go
UTF-8
338
2.765625
3
[]
no_license
[]
no_license
package models import ( "encoding/json" "math" "time" ) const FM float64 = 1e9 type FTime struct { time.Time } func (p *FTime) UnmarshalJSON(data []byte) error { var f float64 if err := json.Unmarshal(data, &f); err != nil { return err } sec, dec := math.Modf(f) p.Time = time.Unix(int64(sec), int64(dec*FM)) return nil }
true
836603355278e526749d21fb025506b949227c40
Go
kiniamogh/trading-system
/services/websocket-service/cmd/server/main.go
UTF-8
1,120
2.59375
3
[]
no_license
[]
no_license
package main import ( "fmt" "log" "net/http" "github.com/caarlos0/env" _logger "github.com/muwazana/backoffice/pkg/logger" "github.com/muwazana/backoffice/services/websocket-service/pkg/api" ) type config struct { LogLevel string `env:"LOG_LEVEL" envDefault:"info"` ServiceName string `env:"SERVICE_HOSTNAME,required"` Port string `env:"SERVICE_PORT" envDefault:"4000"` } var ( cfg config logger *_logger.Log ) func init() { err := env.Parse(&cfg) if err != nil { log.Fatalf("error parsing config: %+v", err) } exitFunc := func(_ int) {} logger = _logger.NewLogger(cfg.LogLevel, cfg.ServiceName, &exitFunc) } func main() { http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { _, _ = fmt.Fprintf(w, "OK") }) // create router instance router := api.NewRouter() api.ListenToRedis(router) // handle all requests to /ws, upgrade to WebSocket via our router handler. http.Handle("/ws", router) // start server. err := http.ListenAndServe(fmt.Sprintf(":%s", cfg.Port), nil) if err != nil { logger.Log().Fatalf("error while listening %+v", err) } }
true
90657047a7756d7812f0474178ed031849361377
Go
dilei/leetcode-go
/cs-notes/10-rect_cover.go
UTF-8
414
3.546875
4
[]
no_license
[]
no_license
package csnotes // 矩形覆盖 // c // 我们可以用 2*1 的小矩形横着或者竖着去覆盖更大的矩形。请问用 n 个 2*1 的小矩形无重叠地覆盖一个 2*n 的大矩形,总共有多少种方法? func rectCover(n int) int { if n <= 2 { return n } pre1 := 1 pre2 := 2 var result int for i:=3; i<=n; i++ { result = pre1 + pre2 pre1 = pre2 pre2 = result } return result }
true
284c6c67c4de4217a3029569eb0f3936ac140193
Go
flyfilly/challenges
/digitDegree/digitDegree.go
UTF-8
280
3.140625
3
[]
no_license
[]
no_license
package main import ( "math" ) func main() { } func digitDegree(n int) int { return add(n, 0) } func add(n int, m int) int { if n >= 10 { t := 0 for n > 0 { t += n % 10 n = int(math.Floor(float64(n) / float64(10))) } return add(t, (m + 1)) } return m }
true
906c90338399b4dc9040f0e5f160e2cc8ecd45aa
Go
bleenco/abstruse
/pkg/gitscm/scm.go
UTF-8
6,369
2.828125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package gitscm import ( "context" "encoding/json" "fmt" "net/http" "github.com/drone/go-scm/scm" "github.com/drone/go-scm/scm/driver/bitbucket" "github.com/drone/go-scm/scm/driver/gitea" "github.com/drone/go-scm/scm/driver/github" "github.com/drone/go-scm/scm/driver/gitlab" "github.com/drone/go-scm/scm/driver/gogs" "github.com/drone/go-scm/scm/transport" ) // SCM represents source code management instance. type SCM struct { provider string url string token string client *scm.Client ctx context.Context } // New returns new instance of SCM. func New(ctx context.Context, provider, url, token string) (SCM, error) { var err error scm := SCM{ provider: provider, url: url, token: token, ctx: ctx, } switch provider { case "github": scm.client, err = github.New(scm.url) case "bitbucket": scm.client, err = bitbucket.New(scm.url) case "gitea": scm.client, err = gitea.New(scm.url) case "gitlab": scm.client, err = gitlab.New(scm.url) case "gogs": scm.client, err = gogs.New(scm.url) default: return scm, fmt.Errorf("unknown scm provider") } scm.client.Client = &http.Client{ Transport: &transport.BearerToken{Token: scm.token}, } return scm, err } // ListRepos returns list of repositories. func (s SCM) ListRepos(page, size int) ([]*scm.Repository, error) { repos, _, err := s.client.Repositories.List(s.ctx, scm.ListOptions{Page: page, Size: size}) return repos, err } // FindRepo finds repository. func (s SCM) FindRepo(name string) (*scm.Repository, error) { repo, _, err := s.client.Repositories.Find(s.ctx, name) return repo, err } // ListCommits returns list of commits. func (s SCM) ListCommits(repo, branch string) ([]*scm.Commit, error) { if s.provider != "gitea" { commits, _, err := s.client.Git.ListCommits(s.ctx, repo, scm.CommitListOptions{Ref: branch}) return commits, err } path := fmt.Sprintf("api/v1/repos/%s/commits?sha=%s", repo, branch) out := []*commitInfo{} res, err := s.client.Do(s.ctx, &scm.Request{Method: "GET", Path: path}) if err != nil { return nil, err } if err := json.NewDecoder(res.Body).Decode(&out); err != nil { return nil, err } var commits []*scm.Commit for _, o := range out { commits = append(commits, convertCommitInfo(o)) } return commits, nil } // LastCommit returns last commit. func (s SCM) LastCommit(repo, branch string) (*scm.Commit, error) { commits, err := s.ListCommits(repo, branch) if err != nil { return nil, err } if len(commits) > 0 { return commits[0], nil } return nil, fmt.Errorf("not found") } // FindCommit finds commit. func (s SCM) FindCommit(repo, ref string) (*scm.Commit, error) { commit, _, err := s.client.Git.FindCommit(s.ctx, repo, ref) return commit, err } // FindBranch finds a git branch by name. func (s SCM) FindBranch(repo, name string) (*scm.Reference, error) { reference, _, err := s.client.Git.FindBranch(s.ctx, repo, name) return reference, err } // FindTag finds a git tag by name. func (s SCM) FindTag(repo, name string) (*scm.Reference, error) { tag, _, err := s.client.Git.FindTag(s.ctx, repo, name) return tag, err } // FindContent finds content of a repository file. func (s SCM) FindContent(repo, ref, path string) (*scm.Content, error) { content, _, err := s.client.Contents.Find(s.ctx, repo, path, ref) return content, err } // ListContent returns a list of contents in a repo directory by path. func (s SCM) ListContent(repo, ref, path string) ([]*scm.Content, error) { contents, _, err := s.client.Contents.List(s.ctx, repo, path, ref, scm.ListOptions{}) if err != nil { return nil, err } var content []*scm.Content for _, c := range contents { if c.Kind == scm.ContentKindFile { scmcontent, err := s.FindContent(repo, ref, c.Path) if err != nil { return nil, err } content = append(content, scmcontent) } } return content, nil } // RefType returns reference type. func (s SCM) RefType(ref string) string { if scm.IsPullRequest(ref) { return "pr" } if scm.IsTag(ref) { return "tag" } if scm.IsBranch(ref) { return "branch" } return "unknown" } // ListHooks returns webhooks applied for the repository. func (s SCM) ListHooks(repo string) ([]*scm.Hook, error) { opts := scm.ListOptions{Page: 1, Size: 30} hooks, _, err := s.client.Repositories.ListHooks(s.ctx, repo, opts) return hooks, err } // CreateHook creates hook for specified repository. func (s SCM) CreateHook(repo, target, secret, provider string, data HookForm) (*scm.Hook, error) { input := &scm.HookInput{ Name: "Abstruse CI", Target: target, Secret: secret, SkipVerify: false, } if provider == "gitea" { var events []string if data.Branch || data.Tag { events = append(events, "create") } if data.PullRequest { events = append(events, "pull_request") } if data.Push { events = append(events, "push") } input.NativeEvents = events } else { input.Events = scm.HookEvents{ Branch: data.Branch, Push: data.Push, Tag: data.Tag, PullRequest: data.PullRequest, Issue: false, IssueComment: false, PullRequestComment: false, ReviewComment: false, } } hook, _, err := s.client.Repositories.CreateHook(s.ctx, repo, input) return hook, err } // DeleteHook deletes webhook by ID. func (s SCM) DeleteHook(repo string, ID string) error { _, err := s.client.Repositories.DeleteHook(s.ctx, repo, ID) return err } // CreateStatus sends build status to SCM provider. func (s SCM) CreateStatus(repo, sha, url string, state scm.State) error { var message string switch state { case scm.StateSuccess: message = "Abstruse CI build successful." case scm.StatePending: message = "Abstruse CI build is running." case scm.StateFailure: message = "Abstruse CI build failed." case scm.StateRunning: message = "Abstruse CI build running." case scm.StateError: message = "Abstruse CI build errored." case scm.StateCanceled: message = "Abstruse CI build cancelled." } input := &scm.StatusInput{ State: state, Label: "continuous-integration", Desc: message, Target: url, } _, _, err := s.client.Repositories.CreateStatus(s.ctx, repo, sha, input) return err } // Client returns underlying scm client. func (s SCM) Client() *scm.Client { return s.client }
true
276c40c5a7c455195dc5f21ce4fbb48a1595f24c
Go
jinmatt/twtrgo
/http/server.go
UTF-8
1,358
3.171875
3
[]
no_license
[]
no_license
package http import ( "context" "log" "net" "net/http" "os" "time" "github.com/jinmatt/twtrgo/config" "github.com/jinmatt/twtrgo/http/handler" ) // Server type to hold http components type Server struct { handler *handler.Handler server *http.Server listener net.Listener } // NewServer inits type Server with http handlers func NewServer(handler *handler.Handler) *Server { return &Server{ handler: handler, } } // Start sets up and starts the http server with `Config` func (s *Server) Start(config *config.Config) error { addr := ":" + config.Port ln, err := net.Listen("tcp", addr) if err != nil { return err } s.listener = ln handler, err := s.handler.MakeHandler() if err != nil { return err } // Start http server log.Printf("Listening on '%s'...\n", addr) server := &http.Server{ Addr: addr, Handler: handler, } s.server = server go func() { err = server.Serve(ln) if err != http.ErrServerClosed { log.Fatalln("Error on server.Serve:", err) os.Exit(1) } }() return nil } // Stop shuts down http server in a given grace time period func (s *Server) Stop(grace time.Duration) { ctx, cancel := context.WithTimeout(context.Background(), grace) err := s.server.Shutdown(ctx) if err != nil { log.Fatalln("Graceful shutdown expired:", err.Error()) } cancel() s.listener.Close() }
true
f1ff7c07ef941a65cbe282492388e3a8884564ff
Go
apg-pk/changeagent
/discovery/discovery.go
UTF-8
5,140
2.984375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package discovery import ( "bytes" "fmt" "github.com/golang/protobuf/proto" ) //go:generate protoc --go_out=. discovery.proto /* * This module contains a set of discovery services that make it easier to * learn which servers are configured as part of a cluster, and make it easier * to know when that configuration changes. */ /* A NodeList is a list of nodes that represents the current config state. It has a "new" and "old" list of Nodes. Under normal operation, only the "new" list is available. During a configuration change, both lists are set and we are in a mode of joint consensus. */ type NodeList struct { New []string `json:"new,omitempty"` Old []string `json:"old,omitempty"` } /* NodeConfig is the current configuration of nodes in the system. This is what we persist in the raft implementation. It includes both the current and previous node lists. We use this in case we need to backtrack in the history and restore an old set of node configuration. */ type NodeConfig struct { Current *NodeList `json:"current,omitempty"` Previous *NodeList `json:"previous,omitempty"` } /* Discovery is the interface that other modules use to get an intial node list from the discovery mechanism. */ type Discovery interface { /* * Get the current configuration from this service, which will only contain a new, "current" * config. */ GetCurrentConfig() *NodeConfig /* * If this method returns true, then the implementation only supports a single * stand-alone node. In that case, configuration changes will never be delivered. * This will only be true if the service has a single node and it will never * have anything other than a single node. */ IsStandalone() bool /* * Return a channel that will be notified whenever the configuration changes. */ Watch() <-chan bool /* * Stop any resources created by the service. */ Close() /* * For testing only: Add a new node to the config, or update an existing node. */ AddNode(a string) /* * For testing only: Delete a node. */ DeleteNode(a string) } /* EncodeConfig turns a NodeConfig into a marhshalled set of bytes for storage and distribution. */ func EncodeConfig(config *NodeConfig) ([]byte, error) { cfgPb := NodeConfigPb{} if config.Current != nil { cfgPb.Current = marshalNodeList(config.Current) } if config.Previous != nil { cfgPb.Previous = marshalNodeList(config.Previous) } return proto.Marshal(&cfgPb) } /* DecodeConfig turns the bytes from EncodeConfig into a NodeConfig object. */ func DecodeConfig(msg []byte) (*NodeConfig, error) { var cfg NodeConfigPb err := proto.Unmarshal(msg, &cfg) if err != nil { return nil, err } nc := NodeConfig{} if cfg.Previous != nil { nc.Previous = unmarshalNodeList(cfg.Previous) } if cfg.Current != nil { nc.Current = unmarshalNodeList(cfg.Current) } return &nc, nil } /* GetUniqueNodes returns a deduped list of all the nodes in the current config. This will return the latest node list if we are in joint consensus mode. */ func (c *NodeConfig) GetUniqueNodes() []string { nl := make(map[string]string) if c.Current != nil { for _, n := range c.Current.Old { nl[n] = n } for _, n := range c.Current.New { nl[n] = n } } var ret []string for _, n := range nl { ret = append(ret, n) } return ret } func marshalNodeList(nl *NodeList) *NodeListPb { listPb := NodeListPb{} if len(nl.New) > 0 { listPb.New = nl.New } if len(nl.Old) > 0 { listPb.Old = nl.Old } return &listPb } func unmarshalNodeList(nl *NodeListPb) *NodeList { ret := NodeList{} if nl.New != nil { ret.New = nl.GetNew() } if nl.Old != nil { ret.Old = nl.GetOld() } return &ret } func (n *NodeList) String() string { buf := &bytes.Buffer{} fmt.Fprintf(buf, "New: [") for _, cn := range n.New { fmt.Fprintf(buf, cn) } fmt.Fprintf(buf, "], Old: [") for _, cn := range n.Old { fmt.Fprintf(buf, cn) } fmt.Fprintf(buf, "]") return buf.String() } /* Equal returns true if the specified node lists have the same sets of keys and values. */ func (n *NodeList) Equal(o *NodeList) bool { if len(n.New) != len(o.New) { return false } if len(n.Old) != len(o.Old) { return false } for i := range n.New { if n.New[i] != o.New[i] { return false } } for i := range n.Old { if n.Old[i] != o.Old[i] { return false } } return true } func (c *NodeConfig) String() string { buf := &bytes.Buffer{} if c.Current != nil { fmt.Fprintf(buf, "Current: %s ", c.Current.String()) } if c.Previous != nil { fmt.Fprintf(buf, "Previous: %s", c.Previous.String()) } return buf.String() } /* Equal returns true if the specified NodeConfig objects have the same sets of keys and values. */ func (c *NodeConfig) Equal(o *NodeConfig) bool { if c.Current == nil { if o.Current != nil { return false } } else { if o.Current == nil { return false } if !c.Current.Equal(o.Current) { return false } } if c.Previous == nil { if o.Previous != nil { return false } } else { if o.Previous == nil { return false } if !c.Previous.Equal(o.Previous) { return false } } return true }
true
edaac330f579c3ca312e9147eb09b68883e2898f
Go
tathagatnawadia/GolangTcpService
/Entities/Client.go
UTF-8
990
3.015625
3
[]
no_license
[]
no_license
package Entities import ( "net" "relay_solution/Utils" ) type IClient interface { GetUserId() int GetActive() bool SetActive(bool) SendMessage(myMessage RelayMessage) AddToHistory(command string) ReceiveMessages() } //@todo: not a good to expose properties as public, should be private with getters and setters if needed - following SOLID type Client struct { User_id int Handler net.Conn Incoming chan RelayMessage Timestamp string Active bool History []string } func (r *Client) GetUserId() int { return r.User_id } func (r *Client) GetActive() bool { return r.Active } func (r *Client) SetActive(v bool) { r.Active = v } func (r *Client) SendMessage(myMessage RelayMessage) { r.Incoming <- myMessage } func (r *Client) AddToHistory(command string) { r.History = append(r.History, command) } func (r *Client) ReceiveMessages() { for { messagePacket := <-r.Incoming Utils.SendBroadcast(messagePacket.Message, messagePacket.From, r.Handler) } }
true
7199c0eae0495115a501f7b628d39ff5e37ecafa
Go
alfalfaw/bookstore
/main.go
UTF-8
2,926
3.234375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "encoding/json" "log" "math/rand" "net/http" "strconv" "github.com/gorilla/mux" ) // Book Struct (Model) type Book struct { ID string `json:"id"` Isbn string `json:"isbn"` Title string `json:"title"` Author *Author `json:"author"` } // Author Struct (Model) type Author struct { Firstname string `json:"firstname"` Lastname string `json:"lastname"` } // Init books var as slice Book struct var books []Book // Get All Books func getBooks(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(books) } // Get Single Book func getBook(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") params := mux.Vars(r) for _, item := range books { if item.ID == params["id"] { json.NewEncoder(w).Encode(item) return } } // return a empty book when not found json.NewEncoder(w).Encode(&Book{}) } // Create a New Book func createBook(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var book Book _ = json.NewDecoder(r.Body).Decode(&book) // 生成id book.ID = strconv.Itoa(rand.Intn(100000000)) books = append(books, book) // return the book created json.NewEncoder(w).Encode(book) } // Update a Book func updateBook(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") params := mux.Vars(r) for index, item := range books { if item.ID == params["id"] { books = append(books[:index], books[index+1:]...) var book Book _ = json.NewDecoder(r.Body).Decode(&book) book.ID = params["id"] books = append(books, book) // return the book created json.NewEncoder(w).Encode(book) return } } json.NewEncoder(w).Encode(books) } // Delete a Book func deleteBook(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") params := mux.Vars(r) for index, item := range books { if item.ID == params["id"] { books = append(books[:index], books[index+1:]...) break } } json.NewEncoder(w).Encode(books) } func main() { r := mux.NewRouter() books = append(books, Book{ID: "1", Isbn: "13824", Title: "Book1", Author: &Author{Firstname: "abc", Lastname: "edf"}}) books = append(books, Book{ID: "2", Isbn: "13824", Title: "Book2", Author: &Author{Firstname: "abc", Lastname: "edf"}}) books = append(books, Book{ID: "3", Isbn: "13824", Title: "Book3", Author: &Author{Firstname: "abc", Lastname: "edf"}}) // Route Handlers / Endpoints r.HandleFunc("/api/books", getBooks).Methods("GET") r.HandleFunc("/api/books/{id}", getBook).Methods("GET") r.HandleFunc("/api/books", createBook).Methods("POST") r.HandleFunc("/api/books/{id}", updateBook).Methods("PUT") r.HandleFunc("/api/books/{id}", deleteBook).Methods("DELETE") // 打印严重错误 log.Fatal(http.ListenAndServe(":8000", r)) }
true
23641857b774569cab1d27c1674fcd82b73a15bb
Go
shimakaru/GoLang
/golang_udemy-master/4.basetype/4.main.go
UTF-8
108
2.53125
3
[]
no_license
[]
no_license
package main import "fmt" func main() { var bt bool = true var bf bool = false fmt.Println(bt, bf) }
true
81091deb46d6ce7c809365760602e292d1e2149b
Go
iesreza/foundation
/lib/request/users.go
UTF-8
1,327
2.765625
3
[]
no_license
[]
no_license
package request import ( "fmt" "github.com/iesreza/foundation/lib" "time" ) type User struct { Id int64 Name string Username string LastActivity int64 LastSeen int64 Guest bool Password string `xorm:"varchar(200)"` Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` OTP string LastOTP int64 } func Login(username, password string) (*User, error) { if username == "test" && password == "test" { u := User{ Username: username, Name: username, Guest: false, } return &u, nil } return &User{Guest: true}, fmt.Errorf("invalid username and password") } func GetUser(req Request) *User { user, exist := req.Session.Get("user") if exist { user.(*User).LastActivity = time.Now().Unix() return user.(*User) } res := &User{ Guest: true, } req.Session.Set("user", res) return res } func (user *User) EstablishSession(req Request) { req.Session.Set("user", user) } func (user *User) IsGuest() bool { return user.Guest } func (user *User) SetPassword(password string) { user.Password = lib.GeneratePassword(password) //user.Save() } func CheckAuthentication(username, password string) bool { /* Database.Find()*/ return false } /*func (user *User) Save() { Database.Update(user) }*/
true
6a4e372148ff4103f074d5fb89f6b480c6aa6bb4
Go
fnanez001/FrankNanez-CSCI20-Spr2020
/1.2.2 Lab.go
UTF-8
921
3.09375
3
[]
no_license
[]
no_license
// Frank Nanez // 2-4-20 // Lab 1.2.2 CSCI20 package main import "fmt" func main() { fmt.Println("Hello World") fmt.Println() fmt.Println("Estimated Popluation in 10 years in the US") fmt.Println("Population is;",329234331 ) fmt.Println("Death rate every; 10 seconds") fmt.Println("Birth rate every; 9 seconds") fmt.Println() fmt.Println("Deaths over the next 10 years =", ((24*60*60*365*10)/10)) fmt.Println("Births over the next 10 years =", ((24*60*60*365*10)/9)) fmt.Println("Population in 10 years =", 329234331-(10*((24*60*60*365)/10))+(10*((24*60*60*365)/9))) fmt.Println() fmt.Println("My name is Frank!") fmt.Println() fmt.Println("FFFFF RR A N N K K") fmt.Println("F R R A A NN N K K") fmt.Println("FFF RR A A A N N N KK") fmt.Println("F R R A A N NN K K") fmt.Println("F R R A A N N K K") fmt.Println() fmt.Println("Thank You!") }
true
94829a171980170791e5570cd49cf1e4660bbb53
Go
slham/basketball
/app/api.go
UTF-8
1,537
2.53125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package app import ( "basketball/env" "basketball/handlers" "basketball/storage" "github.com/gorilla/mux" "github.com/rs/cors" "github.com/slham/toolbelt/l" "net/http" "os" ) type App struct { Config env.Config Router *mux.Router } func (a *App) Initialize() bool { l.Info(nil, "application initializing") a.Config.Env = os.Getenv("ENVIRONMENT") a.Config.L.Level = l.Level(os.Getenv("LOG_LEVEL")) a.Config.Runtime.Port = os.Getenv("RUNTIME_PORT") a.Config.Storage.Bucket = os.Getenv("STORAGE_BUCKET") a.Config.Storage.Prefix = os.Getenv("STORAGE_PREFIX") a.Config.Storage.FileName = os.Getenv("STORAGE_FILENAME") l.Debug(nil, "application configuration: %v", a.Config) ok := l.Initialize(a.Config.L.Level) if !ok { l.Error(nil, "failed to initialize logging middleware") return false } ok = storage.Initialize(a.Config) if !ok { l.Error(nil, "failed to initialize storage") return false } a.Router = mux.NewRouter() a.initializeRoutes() l.Info(nil, "Up and Running!") return true } func (a *App) Run() bool { if err := http.ListenAndServe(":"+a.Config.Runtime.Port, cors.Default().Handler(a.Router)); err != nil { l.Error(nil, "failed to boot server: %v", err) return false } return true } func (a *App) initializeRoutes() { a.Router.Use(l.Logging) a.Router.Methods("GET").Path("/health").HandlerFunc(handlers.HealthCheck) a.Router.Methods("POST").Path("/ratings").HandlerFunc(handlers.RatePlayers) a.Router.Methods("PUT").Path("/players").HandlerFunc(handlers.StorePlayers) }
true
2d116673ecfffa495d232d193ce51c80c8777612
Go
OpenIndustryCloud/fission-go-add-risk-data
/add-risk-data.go
UTF-8
9,857
2.65625
3
[]
no_license
[]
no_license
package main /* This API will update ticket payload with weather risk and fruad risk data */ import ( "encoding/json" "net/http" "strconv" "strings" "time" ) const ( //FORMS STORM_FORM_ID = 114093996871 TV_FORM_ID = 114093998312 //FIELDS WIND_SPEED_FIELD_ID = 114100596852 TV_MODEL_FIELD_ID = 114099896612 CLAIM_TYPE_FIELD_ID = 114099964311 // TV , Storm Surge WEATHER_RISK_FIELD_ID = 114100712171 FRAUD_RISK_FIELD_ID = 114100657672 FRAUD_CHECK_REQ_FIELD_ID = 114101778331 PHONE_FIELD_ID = 114100658992 EMAIL_FIELD_ID = 114100659172 DAMAGE_IMAGE_URL_1 = 114101729171 DAMAGE_IMAGE_URL_2 = 114101729171 RECEIPT_OR_EST_IMG_URL = 114101729331 DAMAGE_VIDEO_URL = 114101655952 SETTLEMENT_AMOUNT = 114101736271 ) func Handler(w http.ResponseWriter, r *http.Request) { mediaFields := [4]int64{114101729171, 114101729331, 114101655952, 114101729171} var composedResult = ComposedResult{} err := json.NewDecoder(r.Body).Decode(&composedResult) if err != nil { createErrorResponse(w, err.Error(), http.StatusBadRequest) return } // populate ticket payload with custom field ticketDetails := TicketDetails{} var claimType, riskDesc, windSpeed string if composedResult.TranformedData.Status == 200 { ticketDetails = composedResult.TranformedData.TicketDetails if strings.Contains(ticketDetails.Ticket.Subject, "Storm") { claimType = "Storm Surge" ticketDetails.Ticket.TicketFormID = STORM_FORM_ID } else { claimType = "TV" ticketDetails.Ticket.TicketFormID = TV_FORM_ID } println("Submission ID ---> " + ticketDetails.Ticket.EventID) } else { createErrorResponse(w, "Ticket Details not recieved", http.StatusBadRequest) } if composedResult.WeatherRisk.Status == 200 { weatherRisk := composedResult.WeatherRisk riskDesc = strconv.Itoa(weatherRisk.RiskScore) + " : " + weatherRisk.Description ticketDetails.addCustomFields(CustomFields{WEATHER_RISK_FIELD_ID, riskDesc}) println("riskDesc", riskDesc) if weatherRisk.RiskScore <= 20 { ticketDetails.addCustomFields(CustomFields{FRAUD_CHECK_REQ_FIELD_ID, "true"}) ticketDetails.addCustomFields(CustomFields{FRAUD_RISK_FIELD_ID, "HIGH"}) } else if weatherRisk.RiskScore > 20 && weatherRisk.RiskScore <= 60 { ticketDetails.addCustomFields(CustomFields{FRAUD_CHECK_REQ_FIELD_ID, "true"}) ticketDetails.addCustomFields(CustomFields{FRAUD_RISK_FIELD_ID, "MEDIUM"}) } else { ticketDetails.addCustomFields(CustomFields{FRAUD_CHECK_REQ_FIELD_ID, "false"}) ticketDetails.addCustomFields(CustomFields{FRAUD_RISK_FIELD_ID, "LOW"}) } } if composedResult.WeatherData.Status == 200 { weatherData := composedResult.WeatherData windSpeed = weatherData.History.Dailysummary[0].Maxwspdm ticketDetails.addCustomFields(CustomFields{WIND_SPEED_FIELD_ID, windSpeed}) println("windSpeed", windSpeed) } //add Custom Fields //common fields ticketDetails.addCustomFields(CustomFields{CLAIM_TYPE_FIELD_ID, claimType}) ticketDetails.addCustomFields(CustomFields{PHONE_FIELD_ID, ticketDetails.Ticket.Requester.Phone}) ticketDetails.addCustomFields(CustomFields{EMAIL_FIELD_ID, ticketDetails.Ticket.Requester.Email}) ticketDetails.addCustomFields(CustomFields{SETTLEMENT_AMOUNT, "0"}) //if images stored in Bucket mediaBucket := composedResult.MediaBucket if mediaBucket.Status == 200 { for i, media := range mediaBucket.Media { ticketDetails.addCustomFields(CustomFields{mediaFields[i], media.MediaLink}) } } if (TVClaimData{}) != composedResult.TranformedData.TVClaimData { tvClaimData := composedResult.TranformedData.TVClaimData mediaBucket := composedResult.MediaBucket //TV Field ticketDetails.addCustomFields(CustomFields{TV_MODEL_FIELD_ID, tvClaimData.TVModelNo}) if mediaBucket.Status != 200 { //typeform media files ticketDetails.addCustomFields(CustomFields{DAMAGE_IMAGE_URL_1, tvClaimData.DamageImageURL1}) ticketDetails.addCustomFields(CustomFields{DAMAGE_IMAGE_URL_2, tvClaimData.DamageImageURL2}) ticketDetails.addCustomFields(CustomFields{RECEIPT_OR_EST_IMG_URL, tvClaimData.TVReceiptImage}) ticketDetails.addCustomFields(CustomFields{DAMAGE_VIDEO_URL, tvClaimData.DamageVideoURL}) } } if (StromClaimData{}) != composedResult.TranformedData.StromClaimData { stormClaimData := composedResult.TranformedData.StromClaimData //Storm Fields if mediaBucket.Status != 200 { ticketDetails.addCustomFields(CustomFields{DAMAGE_IMAGE_URL_1, stormClaimData.DamageImageURL1}) ticketDetails.addCustomFields(CustomFields{DAMAGE_IMAGE_URL_2, stormClaimData.DamageImageURL2}) ticketDetails.addCustomFields(CustomFields{RECEIPT_OR_EST_IMG_URL, stormClaimData.RepairEstimateImage}) ticketDetails.addCustomFields(CustomFields{DAMAGE_VIDEO_URL, stormClaimData.DamageVideoURL}) } } //add status 200 if no error ticketDetails.Status = 200 //marshal to JSON ticketDetailsJSON, err := json.Marshal(ticketDetails) if err != nil { createErrorResponse(w, err.Error(), http.StatusBadRequest) return } println("After updating Risk data, Image dats etc. to ticket -----> ", string(ticketDetailsJSON)) w.Header().Set("content-type", "application/json") w.Write([]byte(string(ticketDetailsJSON))) } func (ticketDetails *TicketDetails) addCustomFields(customField CustomFields) { ticketDetails.Ticket.CustomFields = append(ticketDetails.Ticket.CustomFields, customField) } type MediaBucket struct { Status int `json:"status,omitempty"` Media []Media `json:"media,omitempty"` } type Media struct { Bucket string `json:"bucket,omitempty"` Name string `json:"name,omitempty"` Size int64 `json:"size,omitempty"` MediaLink string `json:"media-link,omitempty"` OriginalLink string `json:"original-link,omitempty"` } func main() { println("staritng app..") http.HandleFunc("/", Handler) http.ListenAndServe(":8084", nil) } // createErrorResponse - this function forms a error reposne with // error message and http code func createErrorResponse(w http.ResponseWriter, message string, status int) { errorJSON, _ := json.Marshal(&Error{ Status: status, Message: message}) //Send custom error message to caller w.WriteHeader(status) w.Header().Set("content-type", "application/json") w.Write([]byte(errorJSON)) } // Error - error object type Error struct { Status int `json:"status"` Message string `json:"message"` } type ComposedResult struct { MediaBucket MediaBucket `json:"media-bucket"` TranformedData TranformedData `json:"tranformed-data"` WeatherData WeatherData `json:"weather-data"` WeatherRisk struct { Status int `json:"status"` Description string `json:"description"` RiskScore int `json:"riskScore"` } `json:"weather-risk"` } type WeatherData struct { Status int `json:"status"` History struct { Dailysummary []struct { Fog string `json:"fog"` Maxpressurem string `json:"maxpressurem"` Maxtempm string `json:"maxtempm"` Maxwspdm string `json:"maxwspdm"` Minpressurem string `json:"minpressurem"` Mintempm string `json:"mintempm"` Minwspdm string `json:"minwspdm"` Rain string `json:"rain"` Tornado string `json:"tornado"` } `json:"dailysummary"` } `json:"history"` Response struct { Version string `json:"version"` } `json:"response"` } type CustomFields struct { ID int64 `json:"id"` Value string `json:"value"` } type TranformedData struct { Status int `json:"status,omitempty"` TicketDetails TicketDetails `json:"ticket_details,omitempty"` WeatherAPIInput WeatherAPIInput `json:"weather_api_input,omitempty"` TVClaimData TVClaimData `json:"tv_claim_data,omitempty"` StromClaimData StromClaimData `json:"storm_claim_data,omitempty"` } type TVClaimData struct { TVPrice string `json:"tv_price,omitempty"` CrimeRef string `json:"crime_ref,omitempty"` IncidentDate string `json:"incident_date,omitempty"` TVModelNo string `json:"tv_model_no,omitempty"` TVMake string `json:"tv_make,omitempty"` TVSerialNo string `json:"tv_serial_no,omitempty"` DamageImageURL1 string `json:"damage_image_url_1,omitempty"` DamageImageURL2 string `json:"damage_image_url_2,omitempty"` TVReceiptImage string `json:"tv_reciept_image_url,omitempty"` DamageVideoURL string `json:"damage_video_url,omitempty"` } type StromClaimData struct { IncidentPlace string `json:"incident_place,omitempty"` IncidentDate string `json:"incident_date,omitempty"` DamageImageURL1 string `json:"damage_image_url_1,omitempty"` DamageImageURL2 string `json:"damage_image_url_2,omitempty"` RepairEstimateImage string `json:"estimate_image_url,omitempty"` DamageVideoURL string `json:"damage_video_url,omitempty"` } type TicketDetails struct { Status int `json:"status"` Ticket struct { Type string `json:"type"` Subject string `json:"subject"` Priority string `json:"priority"` Status string `json:"status"` Comment struct { HTMLBody string `json:"html_body"` Uploads []string `json:"uploads,omitempty"` } `json:"comment"` CustomFields []CustomFields `json:"custom_fields,omitempty"` Requester struct { LocaleID int `json:"locale_id"` Name string `json:"name"` Email string `json:"email"` Phone string `json:"phone"` PolicyNumber string `json:"policy_number"` } `json:"requester"` TicketFormID int64 `json:"ticket_form_id"` EventID string `json:"event_id"` Token string `json:"token"` SubmittedAt time.Time `json:"submitted_at"` } `json:"ticket"` } type WeatherAPIInput struct { City string `json:"city,omitempty"` Country string `json:"country,omitempty"` Date string `json:"date,omitempty"` //YYYYMMDD }
true
cdd77f39c983e8c5149ae0200e6fe18b37ea03f9
Go
joelmaat/Project-Euler
/src/fibonacci.go
UTF-8
3,402
3.296875
3
[]
no_license
[]
no_license
package main import ( "fmt" "math/big" "reflect" "runtime" "time" ) type SquareRooted struct { // Meaning: coefficient * sqrt(rooted) + constant coefficient, rooted, constant *big.Rat } func (rooted *SquareRooted) Set(template *SquareRooted) *SquareRooted { if template == rooted { return rooted } if rooted.coefficient == nil || rooted.rooted == nil || rooted.constant == nil { rooted.coefficient, rooted.rooted, rooted.constant = new(big.Rat), new(big.Rat), new(big.Rat) } rooted.coefficient.Set(template.coefficient) rooted.rooted.Set(template.rooted) rooted.constant.Set(template.constant) return rooted } func (rooted *SquareRooted) Multiply(coefficient, constant *big.Rat) *SquareRooted { coefficient, constant = new(big.Rat).Set(coefficient), new(big.Rat).Set(constant) scratch, rcoefficient := big.NewRat(1, 1), new(big.Rat).Set(rooted.coefficient) rooted.coefficient.Mul(rcoefficient, constant) rooted.coefficient.Add(rooted.coefficient, scratch.Mul(rooted.constant, coefficient)) rooted.constant.Mul(rooted.constant, constant) rooted.constant.Add(rooted.constant, scratch.Mul(rcoefficient, rooted.rooted).Mul(scratch, coefficient)) return rooted } func (rooted *SquareRooted) Square() *SquareRooted { return rooted.Multiply(rooted.coefficient, rooted.constant) } func (rooted *SquareRooted) Exponentiate(power uint64) *SquareRooted { base := new(SquareRooted).Set(rooted) rooted.coefficient.SetInt64(0) rooted.constant.SetInt64(1) for remaining := power; remaining > 0; remaining >>= 1 { if remaining&1 != 0 { rooted.Multiply(base.coefficient, base.constant) } if remaining > 1 { base.Square() } } return rooted } func Fibonacci(n uint64) *big.Int { phi := SquareRooted{big.NewRat(1, 2), big.NewRat(5, 1), big.NewRat(1, 2)} return phi.Exponentiate(n).coefficient.Mul(phi.coefficient, big.NewRat(2, 1)).Num() } func FibonacciSum(n uint64) *big.Int { first, second := big.NewInt(1), big.NewInt(0) for i := n; i > 0; i-- { second.Add(first, second) first.Sub(second, first) } return second } func Multiply(result, base []*big.Int) []*big.Int { result[1].Mul(result[1], base[1]) result[0].Mul(result[0], base[0]).Add(result[0], result[1]) result[2].Mul(result[2], base[2]).Add(result[2], result[1]) result[1].Sub(result[2], result[0]) return result } func Square(base []*big.Int) []*big.Int { two := big.NewInt(2) base[1].Exp(base[1], two, nil) base[0].Exp(base[0], two, nil).Add(base[0], base[1]) base[2].Exp(base[2], two, nil).Add(base[2], base[1]) base[1].Sub(base[2], base[0]) return base } func FibonacciMatrix(power uint64) *big.Int { base := []*big.Int{big.NewInt(0), big.NewInt(1), big.NewInt(1)} result := []*big.Int{big.NewInt(0), big.NewInt(1), big.NewInt(1)} if power < 3 { return result[power] } for remaining := power - 2; remaining > 0; remaining >>= 1 { if remaining&1 != 0 { Multiply(result, base) } if remaining > 1 { Square(base) } } return result[2] } func main() { runtime.GOMAXPROCS(runtime.NumCPU() * 2) // fmt.Printf("%d\n", FibonacciMatrix(uint64(17))); return for _, fn := range []func(uint64) *big.Int{FibonacciMatrix} { delay, count := time.Now(), int64(0) for j := 100; j > 0; j-- { fn(uint64((1 << 17) - 1)) } count = time.Since(delay).Nanoseconds() fmt.Printf("%30s: %15d\n", runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name(), count) } }
true
5d105d5660194c41cbe2e5ffdbf3c9769fc4078a
Go
TshSophie/SomeAlgorithm
/00Sort/04_InsertSort/InsertSort.go
UTF-8
370
3.578125
4
[]
no_license
[]
no_license
package main import "fmt" func InsertSort(arr []int) { length := len(arr) for i := 1; i < length; i++ { if arr[i] < arr[i-1] { temp := arr[i] var j int for j = i - 1; j >= 0 && arr[j] > temp; j-- { arr[j+1] = arr[j] } arr[j+1] = temp } } } func main() { arr := []int{5, 3, 6, 7, 2} fmt.Println(arr) InsertSort(arr) fmt.Println(arr) }
true
fd64c59e7373ce5eebe9c6a0a8048ea206b8901a
Go
ichiban/not35
/user.go
UTF-8
631
2.90625
3
[]
no_license
[]
no_license
package main import ( "context" "time" "golang.org/x/crypto/bcrypt" ) type User struct { ID int `db:"id"` Email string `db:"email"` PasswordHash []byte `db:"password_hash"` CreatedAt time.Time `db:"created_at"` UpdatedAt time.Time `db:"updated_at"` } func authenticate(ctx context.Context, u *User, email, password string) error { var c User if err := db.GetContext(ctx, &c, "SELECT * FROM users WHERE email = $1", email); err != nil { return err } if err := bcrypt.CompareHashAndPassword(c.PasswordHash, []byte(password)); err != nil { return err } *u = c return nil }
true
b5acfbff489c0ea832d01926a6d9102d1b613eb4
Go
Serrous/OTUS
/lesson_6/lesson_6.go
UTF-8
2,410
3.953125
4
[]
no_license
[]
no_license
package main import ( "errors" "fmt" "runtime" ) type myType = func() error func aaa() error { sl := []int{1, 2, 3, 4, 5} for _, i := range sl { if i == 3 { return errors.New("Произошла ошибка в функции aaa") } fmt.Println("aaa", i) } return nil } func bbb() error { sl := []int{6, 7, 8, 9, 10} for _, i := range sl { if i == 8 { return errors.New("Произошла ошибка в функции bbb") } fmt.Println("bbb", i) } return nil } //Run is our function func Run(task []myType, n int, m int) error { var countGorutines = make(chan bool, n) //канал для ограничения конкрурентного запуска горутин var errs = make(chan error) //канал для получения ошибок из горутин var quit = make(chan bool) //канал для сигнала завершения errCount := 0 //счетчик ошибок defer fmt.Println("Сейчас запущено горутин:", runtime.NumGoroutine()) // для проверки оставшихся горутин defer func() { //обрабатываем панику, которая будет вызвана попыткой записать в закрытый канал. if err := recover(); err != nil { fmt.Println("panic!", err) } }() go func() { //запускаем WatchDog, который остлеживает прилетающие ошибки из канала errs for { msg := <-errs fmt.Println(msg) errCount++ if errCount >= m { fmt.Println("Произошло", errCount, "ошибок, посылаю сигнал завершения") close(quit) //посылаем сигнал завершения путем закрытия канала quit close(countGorutines) //закрываем канал return } } }() for _, i := range task { countGorutines <- true go func(n myType) { for { select { case <-quit: fmt.Println("Получен сигнал завершения") return default: result := n() if result != nil { errs <- result } <-countGorutines return } } }(i) } return nil } func main() { myTasks := []myType{aaa, bbb, aaa, bbb, aaa, bbb, aaa, bbb, aaa, bbb} fmt.Println(Run(myTasks, 2, 4)) }
true
1249af2757c96804c255c0dd43e951ccab3aa63e
Go
ankurrai1/getting_started_GO
/concepts_code/method.go
UTF-8
1,044
4.25
4
[]
no_license
[]
no_license
// Go supports methods defined on struct as methods defined in any object orianded language package main import( "fmt" ) type rect struct { width int height int } // This area method has referance of rect struct. func (r *rect) area() int { // pass by referance return r.width * r.height } // Methods can be defined for either pointer or value receiver types. // following an example of a value receiver. func (r rect) perim() int { // pass by value return 2*r.width + 2*r.height } func main() { r := rect{width: 10, height: 5} // here we are creating the stucture // Here we call the 2 methods defined for our struct. fmt.Println("area: ", r.area()) fmt.Println("perimiter:", r.perim()) // Go automatically handles conversion between values and pointers for method calls. // You may want to use a pointer receiver type to avoid copying on method calls or // to allow the method to mutate the receiving struct. rp := &r fmt.Println("area: ", rp.area()) fmt.Println("perimiter:", rp.perim()) }
true
3be6c52238a3bdbc5bf690fa7088606a51e13bf7
Go
d3zd3z/gosure
/store/store_test.go
UTF-8
2,313
3.109375
3
[]
no_license
[]
no_license
package store import ( "bytes" "fmt" "io/ioutil" "math/rand" "os" "path" "testing" "davidb.org/x/gosure/sure" ) func TestTmpFile(t *testing.T) { tdir, err := ioutil.TempDir("", "store-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tdir) var st Store st.Path = tdir // Make sure we can create a large number of these for i := 0; i < 100; i++ { f, err := st.tmpFile() if err != nil { t.Fatal(err) } f.Close() // Verify that the name is correct. name := path.Join(tdir, fmt.Sprintf("2sure.%d.gz", i)) if f.Name() != name { t.Fatalf("Tmp name mismatch, expect %q, got %q", f.Name(), name) } } // Verify that we can't write to an invalid name. st.Path = path.Join(tdir, "notdir") f, err := st.tmpFile() if err == nil { name := f.Name() f.Close() t.Fatalf("Should not have been able to create file %q", name) } // Try with a file instead of a name. st.Path = path.Join(tdir, "2sure.0.gz") f, err = st.tmpFile() if err == nil { name := f.Name() f.Close() t.Fatalf("Should not have been able to create file %q", name) } } func TestWrite(t *testing.T) { r := rand.New(rand.NewSource(1)) tdir, err := ioutil.TempDir("", "store-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tdir) // Write 3 times, and then make sure the files we get back are // right. var trees []*sure.Tree var st Store st.Path = tdir for i := 0; i < 3; i++ { tr := sure.GenerateTree(r, 10, 2) trees = append(trees, tr) err := st.Write(tr) if err != nil { t.Fatal(err) } } // Check that we only have the two names. files, err := ioutil.ReadDir(tdir) if err != nil { t.Fatal(err) } if len(files) != 2 { t.Fatalf("Wrong number of files: %d, expect %d", len(files), 2) } for _, fi := range files { if fi.Name() == "2sure.dat.gz" || fi.Name() == "2sure.bak.gz" { continue } t.Fatalf("File: %q unexpected", fi.Name()) } t2, err := st.ReadDat() if err != nil { t.Fatal(err) } treesSame(t, trees[2], t2) t1, err := st.ReadBak() if err != nil { t.Fatal(err) } treesSame(t, trees[1], t1) } func treesSame(t *testing.T, a, b *sure.Tree) { var buf bytes.Buffer sure.NewComparer(&buf).CompareTrees(a, b) if buf.Len() > 0 { t.Logf("delta output: %q", buf.String()) t.Fatal("Trees differ") } }
true
9859c6a8c7134f1d20e8bd311d81352d85cfe120
Go
rkbodenner/parallel_universe
/game/setup_rule.go
UTF-8
1,667
3.140625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package game import ( "fmt" ) type SetupRule struct { Id int Description string Details string Arity string Dependencies []*SetupRule } func NewSetupRule(desc string, arity string, deps ...*SetupRule) *SetupRule { return &SetupRule{0, desc, "", arity, deps} } func (a *SetupRule) Equal(b *SetupRule) bool { return a.Id == b.Id && a.Description == b.Description && a.Details == b.Details && a.Arity == b.Arity } type SetupStep struct { Rule *SetupRule Owner *Player Done bool } func NewGlobalSetupStep(rule *SetupRule) (*SetupStep, error) { if "Once" != rule.Arity { return nil, fmt.Errorf("Global setup step cannot be created from a rule with different arity") } return &SetupStep{rule, nil, false}, nil } func NewPerPlayerSetupStep(rule *SetupRule, owner *Player) (*SetupStep, error) { if "Each player" != rule.Arity { return nil, fmt.Errorf("Per-player setup step cannot be created from a rule with different arity") } return &SetupStep{rule, owner, false}, nil } func (step *SetupStep) CanBeOwnedBy(player *Player) bool { return step.Owner == nil || player.Id == step.Owner.Id } func (step *SetupStep) Finish() { step.Done = true } func (a *SetupStep) Equal(b *SetupStep) bool { if a.Rule.Equal(b.Rule) { if a.Owner == nil && b.Owner == nil { return true } if a.Owner != nil && b.Owner != nil { if a.Owner.Id == b.Owner.Id { return true } } } return false } func (step *SetupStep) String() string { ownerName := "" if nil != step.Owner { ownerName = step.Owner.Name } return fmt.Sprintf("%s (%s)", step.Rule.Description, ownerName) }
true
7368616f7750e6b9121cee475db2fa8acf1d8305
Go
tcolgate/grafana-simple-json-go
/simplejson.go
UTF-8
20,817
2.6875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// Copyright 2016 Qubit Digital Ltd. // 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 logspray is a collection of tools for streaming and indexing // large volumes of dynamic logs. // Package simplejson eases the creation of HTTP endpoints to support Grafana's // simplejson data source plugin. package simplejson import ( "context" "encoding/json" "errors" "net/http" "sort" "time" ) // Handler Is an opaque type that supports the required HTTP handlers for the // Simple JSON plugin type Handler struct { query Querier tableQuery TableQuerier annotations Annotator search Searcher tags TagSearcher mux *http.ServeMux } // New creates a new http.Handler that will answer to the required endpoint for // a SimpleJSON source. You should use WithQuerier, WithTableQuerier, // WithAnnotator and WithSearch to set handlers for each of the endpionts. func New(opts ...Opt) *Handler { mux := http.NewServeMux() Handler := &Handler{ mux: mux, } mux.HandleFunc("/", Handler.HandleRoot) mux.HandleFunc("/query", Handler.HandleQuery) mux.HandleFunc("/annotations", Handler.HandleAnnotations) mux.HandleFunc("/search", Handler.HandleSearch) mux.HandleFunc("/tag-keys", Handler.HandleTagKeys) mux.HandleFunc("/tag-values", Handler.HandleTagValues) for _, o := range opts { if err := o(Handler); err != nil { panic(err) } } return Handler } // WithSource will attempt to use the datasource provided as // a Querier, TableQuerier, Annotator, Searcher and TagSearch // if it supports the required interface. func WithSource(src interface{}) Opt { return func(sjc *Handler) error { if q, ok := src.(Querier); ok { sjc.query = q } if tq, ok := src.(TableQuerier); ok { sjc.tableQuery = tq } if a, ok := src.(Annotator); ok { sjc.annotations = a } if s, ok := src.(Searcher); ok { sjc.search = s } if ts, ok := src.(TagSearcher); ok { sjc.tags = ts } return nil } } // WithQuerier adds a timeserie query handler. func WithQuerier(q Querier) Opt { return func(sjc *Handler) error { sjc.query = q return nil } } // WithTableQuerier adds a table query handler. func WithTableQuerier(q TableQuerier) Opt { return func(sjc *Handler) error { sjc.tableQuery = q return nil } } // WithAnnotator adds an annoations handler. func WithAnnotator(a Annotator) Opt { return func(sjc *Handler) error { sjc.annotations = a return nil } } // WithSearcher adds a search handlers. func WithSearcher(s Searcher) Opt { return func(sjc *Handler) error { sjc.search = s return nil } } // WithTagSearcher adds adhoc filter tag search handlers. func WithTagSearcher(s TagSearcher) Opt { return func(sjc *Handler) error { sjc.tags = s return nil } } // Opt provides configurable options for the Handler type Opt func(*Handler) error // QueryCommonArguments describes the arguments common to timeserie and // table queries. type QueryCommonArguments struct { From, To time.Time Filters []QueryAdhocFilter } // QueryArguments defines the options to a timeserie query. type QueryArguments struct { QueryCommonArguments Interval time.Duration MaxDPs int } // TableQueryArguments defines the options to a table query. type TableQueryArguments struct { QueryCommonArguments } // A Querier responds to timeseri queries from Grafana type Querier interface { GrafanaQuery(ctx context.Context, target string, args QueryArguments) ([]DataPoint, error) } // TagInfoer is an internal interface to describe difference types of tag. type TagInfoer interface { tagName() string tagType() string } // TagStringKey represent an adhoc query string key. type TagStringKey string func (k TagStringKey) tagName() string { return string(k) } func (k TagStringKey) tagType() string { return "string" } // TagValuer is in an internal interface used to describe tag // Values. type TagValuer interface { tagValue() json.RawMessage } // TagStringValue represent an adhoc query string key. type TagStringValue string func (k TagStringValue) tagValue() json.RawMessage { // We igore the error here because the following should // always be marshable. bs, _ := json.Marshal(struct { Text string `json:"text"` }{ Text: string(k), }) return json.RawMessage(bs) } // A TagSearcher allows the querying of tag keys and values for adhoc filters. type TagSearcher interface { GrafanaAdhocFilterTags(ctx context.Context) ([]TagInfoer, error) GrafanaAdhocFilterTagValues(ctx context.Context, key string) ([]TagValuer, error) } // A TableQuerier responds to table queries from Grafana type TableQuerier interface { GrafanaQueryTable(ctx context.Context, target string, args TableQueryArguments) ([]TableColumn, error) } // AnnotationsArguments defines the options to a annotations query. type AnnotationsArguments struct { QueryCommonArguments } // An Annotator responds to queries for annotations from Grafana type Annotator interface { GrafanaAnnotations(ctx context.Context, query string, args AnnotationsArguments) ([]Annotation, error) } // A Searcher responds to search queries from Grafana type Searcher interface { GrafanaSearch(ctx context.Context, target string) ([]string, error) } // QueryAdhocFilter describes a user supplied filter to be added to // each query target. type QueryAdhocFilter struct { Key string `json:"key"` Operator string `json:"operator"` Value string `json:"value"` } // DataPoint represents a single datapoint at a given point in time. type DataPoint struct { Time time.Time Value float64 } // A TableNumberColumn holds values for a "number" column in a table. type TableNumberColumn []float64 func (TableNumberColumn) simpleJSONColumn() { } // A TableTimeColumn holds values for a "time" column in a table. type TableTimeColumn []time.Time func (TableTimeColumn) simpleJSONColumn() { } // A TableStringColumn holds values for a "string" column in a table. type TableStringColumn []string func (TableStringColumn) simpleJSONColumn() { } // TableColumnData is a private interface to this package, you should // use one of TableStringColumn, TableNumberColumn, or TableTimeColumn type TableColumnData interface { simpleJSONColumn() } // TableColumn represents a single table column. Data should // be one the TableNumberColumn, TableStringColumn or TableTimeColumn types. type TableColumn struct { Text string Data TableColumnData } // Annotation represents an annotation that can be displayed on a graph, or // in a table. type Annotation struct { Time time.Time `json:"time"` TimeEnd time.Time `json:"timeEnd,omitempty"` Title string `json:"title"` Text string `json:"text"` Tags []string `json:"tags"` } // HandleRoot serves a plain 200 OK for /, required by Grafana func (h *Handler) HandleRoot(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "File not found", http.StatusNotFound) } w.Write([]byte("OK")) } // simpleJSONTime is a wrapper for time.Time that reformats for type simpleJSONTime time.Time // MarshalJSON implements JSON marshalling func (sjt *simpleJSONTime) MarshalJSON() ([]byte, error) { out := time.Time(*sjt).Format(time.RFC3339Nano) return json.Marshal(out) } // UnmarshalJSON implements JSON unmarshalling func (sjt *simpleJSONTime) UnmarshalJSON(injs []byte) error { in := "" err := json.Unmarshal(injs, &in) if err != nil { return err } t, err := time.Parse(time.RFC3339Nano, in) if err != nil { return err } *sjt = simpleJSONTime(t) return nil } type simpleJSONDuration time.Duration func (sjd *simpleJSONDuration) MarshalJSON() ([]byte, error) { out := time.Duration(*sjd).String() return json.Marshal(out) } func (sjd *simpleJSONDuration) UnmarshalJSON(injs []byte) error { in := "" err := json.Unmarshal(injs, &in) if err != nil { return err } d, err := time.ParseDuration(in) if err != nil { return err } *sjd = simpleJSONDuration(d) return nil } type simpleJSONRawRange struct { From string `json:"from"` To string `json:"to"` } type simpleJSONRange struct { From simpleJSONTime `json:"from"` To simpleJSONTime `json:"to"` Raw simpleJSONRawRange `json:"raw"` } type simpleJSONTarget struct { Target string `json:"target"` RefID string `json:"refId"` Hide bool `json:"hide"` Type string `json:"type"` } /* { "panelId": 1, "range": { "from": "2016-10-31T06:33:44.866Z", "to": "2016-10-31T12:33:44.866Z", "raw": { "from": "now-6h", "to": "now" } }, "rangeRaw": { "from": "now-6h", "to": "now" }, "interval": "30s", "intervalMs": 30000, "targets": [ { "target": "upper_50", refId: "A" , "hide": false. "type"; "timeserie"}, { "target": "upper_75", refId: "B" } ], "format": "json", "maxDataPoints": 550 } */ type simpleJSONQuery struct { PanelID int `json:"panelId"` Range simpleJSONRange `json:"range"` RangeRaw simpleJSONRawRange `json:"rangeRaw"` Interval simpleJSONDuration `json:"interval"` IntervalMS int `json:"intervalMs"` Targets []simpleJSONTarget `json:"targets"` Format string `json:"format"` MaxDataPoints int `json:"maxDataPoints"` AdhocFilters []QueryAdhocFilter `json:"adhocFilters"` } /* [ { "target":"upper_75", // The field being queried for "datapoints":[ [622,1450754160000], // Metric value as a float , unixtimestamp in milliseconds [365,1450754220000] ] }, { "target":"upper_90", "datapoints":[ [861,1450754160000], [767,1450754220000] ] } ] */ type simpleJSONPTime time.Time func (sjdpt *simpleJSONPTime) MarshalJSON() ([]byte, error) { out := time.Time(*sjdpt).UnixNano() / 1000000 return json.Marshal(out) } func (sjdpt *simpleJSONPTime) UnmarshalJSON(injs []byte) error { in := int64(0) err := json.Unmarshal(injs, &in) if err != nil { return err } t := time.Unix(0, in*1000000) *sjdpt = simpleJSONPTime(t) return nil } type simpleJSONDataPoint struct { Value float64 `json:"value"` Time simpleJSONPTime `json:"time"` } func (sjdp *simpleJSONDataPoint) MarshalJSON() ([]byte, error) { out := [2]float64{sjdp.Value, float64(time.Time(sjdp.Time).UnixNano() / 1000000)} return json.Marshal(out) } func (sjdp *simpleJSONDataPoint) UnmarshalJSON(injs []byte) error { in := [2]float64{} err := json.Unmarshal(injs, &in) if err != nil { return err } *sjdp = simpleJSONDataPoint{} sjdp.Value = in[0] sjdp.Time = simpleJSONPTime(time.Unix(0, int64(in[1])*1000000)) return nil } type simpleJSONData struct { Target string `json:"target"` DataPoints []simpleJSONDataPoint `json:"datapoints"` } type simpleJSONTableColumn struct { Text string `json:"text"` Type string `json:"type"` } type simpleJSONTableRow []interface{} type simpleJSONTableData struct { Type string `json:"type"` Columns []simpleJSONTableColumn `json:"columns"` Rows []simpleJSONTableRow `json:"rows"` } func (h *Handler) jsonTableQuery(ctx context.Context, req simpleJSONQuery, target simpleJSONTarget) (interface{}, error) { resp, err := h.tableQuery.GrafanaQueryTable( ctx, target.Target, TableQueryArguments{ QueryCommonArguments: QueryCommonArguments{ From: time.Time(req.Range.From), To: time.Time(req.Range.To), Filters: req.AdhocFilters, }, }, ) if err != nil { return nil, err } rowCount := 0 var cols []simpleJSONTableColumn for _, cv := range resp { var colType string var dataLen int switch data := cv.Data.(type) { case TableNumberColumn: colType = "number" dataLen = len(data) case TableStringColumn: colType = "string" dataLen = len(data) case TableTimeColumn: colType = "time" dataLen = len(data) default: return nil, errors.New("invlalid column type") } if rowCount == 0 { rowCount = dataLen } if dataLen != rowCount { return nil, errors.New("all columns must be of equal length") } cols = append(cols, simpleJSONTableColumn{Text: cv.Text, Type: colType}) } rows := make([]simpleJSONTableRow, rowCount) for i := 0; i < rowCount; i++ { rows[i] = make([]interface{}, len(resp)) } for j := range resp { switch data := resp[j].Data.(type) { case TableNumberColumn: for i := 0; i < rowCount; i++ { rows[i][j] = data[i] } case TableStringColumn: for i := 0; i < rowCount; i++ { rows[i][j] = data[i] } case TableTimeColumn: for i := 0; i < rowCount; i++ { rows[i][j] = data[i] } } } return simpleJSONTableData{ Type: "table", Columns: cols, Rows: rows, }, nil } func (h *Handler) jsonQuery(ctx context.Context, req simpleJSONQuery, target simpleJSONTarget) (interface{}, error) { resp, err := h.query.GrafanaQuery( ctx, target.Target, QueryArguments{ QueryCommonArguments: QueryCommonArguments{ From: time.Time(req.Range.From), To: time.Time(req.Range.To), Filters: req.AdhocFilters, }, Interval: time.Duration(req.Interval), MaxDPs: req.MaxDataPoints, }) if err != nil { return nil, err } sort.Slice(resp, func(i, j int) bool { return resp[i].Time.Before(resp[j].Time) }) out := simpleJSONData{Target: target.Target} for _, v := range resp { out.DataPoints = append(out.DataPoints, simpleJSONDataPoint{ Time: simpleJSONPTime(v.Time), Value: v.Value, }) } return out, nil } // HandleQuery hands the /query endpoint, calling the appropriate timeserie // or table handler. func (h *Handler) HandleQuery(w http.ResponseWriter, r *http.Request) { if h.query == nil && h.tableQuery == nil { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } ctx := r.Context() req := simpleJSONQuery{} dec := json.NewDecoder(r.Body) if err := dec.Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } var err error var out []interface{} for _, target := range req.Targets { var res interface{} switch target.Type { case "", "timeserie": if h.query == nil { http.Error(w, "timeserie query not implemented", http.StatusBadRequest) return } res, err = h.jsonQuery(ctx, req, target) case "table": if h.tableQuery == nil { http.Error(w, "table query not implemented", http.StatusBadRequest) return } res, err = h.jsonTableQuery(ctx, req, target) default: http.Error(w, "unknown query type, timeserie or table", 400) return } if err != nil { http.Error(w, err.Error(), 500) return } out = append(out, res) } bs, err := json.Marshal(out) if err != nil { http.Error(w, err.Error(), 500) return } w.Header().Set("Content-Type", "application/json") w.Write(bs) } /* { "range": { "from": "2016-04-15T13:44:39.070Z", "to": "2016-04-15T14:44:39.070Z" }, "rangeRaw": { "from": "now-1h", "to": "now" }, "annotation": { "name": "deploy", "datasource": "Simple JSON Datasource", "iconColor": "rgba(255, 96, 96, 1)", "enable": true, "query": "#deploy" } } */ type simpleJSONAnnotation struct { Name string `json:"name"` Query string `json:"query"` Enable bool `json:"enable"` IconColor string `json:"iconColor"` } type simpleJSONAnnotationResponse struct { ReqAnnotation simpleJSONAnnotation `json:"annotation"` Time simpleJSONPTime `json:"time"` RegionID int `json:"regionId,omitempty"` Title string `json:"title"` Text string `json:"text"` Tags []string `json:"tags"` } type simpleJSONAnnotationsQuery struct { Range simpleJSONRange `json:"range"` RangeRaw simpleJSONRawRange `json:"rangeRaw"` Annotation simpleJSONAnnotation `json:"annotation"` } // HandleAnnotations responds to the /annotation requests. func (h *Handler) HandleAnnotations(w http.ResponseWriter, r *http.Request) { if h.annotations == nil { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusBadRequest) return } ctx := r.Context() if r.Method == http.MethodOptions { w.Write([]byte("Allow: POST,OPTIONS")) return } req := simpleJSONAnnotationsQuery{} dec := json.NewDecoder(r.Body) if err := dec.Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } resp := []simpleJSONAnnotationResponse{} anns, err := h.annotations.GrafanaAnnotations( ctx, req.Annotation.Query, AnnotationsArguments{ QueryCommonArguments{ From: time.Time(req.Range.From), To: time.Time(req.Range.To), }, }) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } regionID := 1 for i := range anns { startAnn := simpleJSONAnnotationResponse{ ReqAnnotation: req.Annotation, Time: simpleJSONPTime(anns[i].Time), Title: anns[i].Title, Text: anns[i].Text, Tags: anns[i].Tags, } if !anns[i].TimeEnd.IsZero() { startAnn.RegionID = regionID } resp = append(resp, startAnn) if !anns[i].TimeEnd.IsZero() { endAnn := simpleJSONAnnotationResponse{ ReqAnnotation: req.Annotation, Time: simpleJSONPTime(anns[i].TimeEnd), Title: anns[i].Title, Text: anns[i].Text, Tags: anns[i].Tags, RegionID: regionID, } resp = append(resp, endAnn) regionID++ } } bs, err := json.Marshal(resp) if err != nil { http.Error(w, err.Error(), 500) return } w.Header().Set("Content-Type", "application/json") w.Write(bs) } type simpleJSONSearchQuery struct { Target string } // HandleSearch implements the /search endpoint. func (h *Handler) HandleSearch(w http.ResponseWriter, r *http.Request) { if h.search == nil { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusBadRequest) return } ctx := r.Context() req := simpleJSONSearchQuery{} dec := json.NewDecoder(r.Body) if err := dec.Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } resp, err := h.search.GrafanaSearch(ctx, req.Target) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } bs, err := json.Marshal(resp) if err != nil { http.Error(w, err.Error(), 500) return } w.Header().Set("Content-Type", "application/json") w.Write(bs) } type simpleJSONQueryAdhocKey struct { Type string `json:"type"` Text string `json:"text"` } // HandleTagKeys implements the /tag-keys endpoint. func (h *Handler) HandleTagKeys(w http.ResponseWriter, r *http.Request) { if h.tags == nil { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } ctx := r.Context() tags, err := h.tags.GrafanaAdhocFilterTags(ctx) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } var allTags []simpleJSONQueryAdhocKey for _, tag := range tags { allTags = append(allTags, simpleJSONQueryAdhocKey{ Type: tag.tagType(), Text: tag.tagName(), }) } bs, err := json.Marshal(allTags) if err != nil { http.Error(w, err.Error(), 500) return } w.Header().Set("Content-Type", "application/json") w.Write(bs) } type simpleJSONTagValuesQuery struct { Key string `json:"key"` } // HandleTagValues implements the /tag-values endpoint. func (h *Handler) HandleTagValues(w http.ResponseWriter, r *http.Request) { if h.tags == nil { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusBadRequest) return } ctx := r.Context() req := simpleJSONTagValuesQuery{} dec := json.NewDecoder(r.Body) if err := dec.Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } vals, err := h.tags.GrafanaAdhocFilterTagValues(ctx, req.Key) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } var allVals []json.RawMessage for _, val := range vals { allVals = append(allVals, val.tagValue()) } bs, err := json.Marshal(allVals) if err != nil { http.Error(w, err.Error(), 500) return } w.Header().Set("Content-Type", "application/json") w.Write(bs) } // ServeHTTP supports the http.Handler interface for a simplejson // handler. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }
true
f72098c75d273f48f02e11ce11b8a1660079972f
Go
i-redbyte/golang-benchmarks
/bench_int_insert_slice_test.go
UTF-8
755
2.578125
3
[]
no_license
[]
no_license
package go_benchmark import "testing" func insertXIntSlice(x int, b *testing.B) { testSlice := make([]int, 0) b.ResetTimer() for i := 0; i < x; i++ { testSlice = append(testSlice, i) } } func BenchmarkInsertIntSlice1000000(b *testing.B) { for i := 0; i < b.N; i++ { insertXIntSlice(1000000, b) } } func BenchmarkInsertIntSlice100000(b *testing.B) { for i := 0; i < b.N; i++ { insertXIntSlice(100000, b) } } func BenchmarkInsertIntSlice10000(b *testing.B) { for i := 0; i < b.N; i++ { insertXIntSlice(10000, b) } } func BenchmarkInsertIntSlice1000(b *testing.B) { for i := 0; i < b.N; i++ { insertXIntSlice(1000, b) } } func BenchmarkInsertIntSlice100(b *testing.B) { for i := 0; i < b.N; i++ { insertXIntSlice(100, b) } }
true
720aee8d0ef382ddb84016a7aa72ba88fee1b30f
Go
zenledger-io/go-psql
/client_test.go
UTF-8
38,185
2.765625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package psql import ( "context" "errors" "fmt" "testing" "time" "github.com/stretchr/testify/require" ) func TestClient_Test(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() m := &MockModel{ StringField: "test", NullStringField: NewNullString("test"), IntField: 5, FloatField: 4.5, BoolField: true, TimeField: time.Now(), } ctx := context.Background() // Insert if err := c.Insert(ctx, m); err != nil { t.Fatalf("error inserting %v", err) } if m.ID < 1 { t.Fatalf("insert did not set id") } var results []*MockModel if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } result := results[0] if result.ID != m.ID { t.Fatalf("ids do not match (%v and %v)", result.ID, m.ID) } if result.StringField != m.StringField || result.IntField != m.IntField || result.FloatField != m.FloatField || result.BoolField != m.BoolField || !result.NullStringField.Valid { t.Fatalf("result does not match expect (%v and %v)", result, m) } // Update m.BoolField = false m.IntField = 10 m.NullStringField = InvalidNullString() if err := c.Update(ctx, m); err != nil { t.Fatalf("Error updating %v", err) } results = nil if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } result = results[0] if result.BoolField { t.Fatalf("incorrect value for bool_field after update, expected false %v", result) } if result.IntField != 10 { t.Fatalf("incorrect value for int_field after update, expected 10 %v", result) } // Select with nullable results = nil if err := c.Select("mock_models").Where(Attrs{"null_string_field": NullString{}}).Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } // with nil results = nil if err := c.Select("mock_models").Where(Attrs{"null_string_field": nil}).Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } m.IntField = 15 m.FloatField = 18.2 // Update single column if err := c.Update(ctx, m, "float_field"); err != nil { t.Fatalf("Error updating %v", err) } results = nil if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } result = results[0] if result.FloatField != 18.2 { t.Fatalf("incorrect value for float_field after update, expected 18.2 %v", result) } if result.IntField != 10 { t.Fatalf("incorrect value for int_field after update, expected 10 %v", result) } // Delete if i, err := c.Delete(ctx, m); err != nil { t.Fatalf("Error deleting (rows affected %v) %v", i, err) } results = nil if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 0 { t.Fatalf("results returned incorrect amount, expected 0 and got %v", len(results)) } // Multi insert m.BoolField = false if err := c.Insert(ctx, m); err != nil { t.Fatalf("Error inserting %v", err) } if err := c.Insert(ctx, m); err != nil { t.Fatalf("Error inserting %v", err) } if err := c.Insert(ctx, m); err != nil { t.Fatalf("Error inserting %v", err) } results = nil if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 3 { t.Fatalf("results returned incorrect amount, expected 3 and got %v", len(results)) } // Select with clause results = nil if err := c.Select("mock_models").Where(Attrs{"id": m.ID}).Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } // RawSelect results = nil if err := c.RawSelect(ctx, &results, "SELECT * FROM mock_models WHERE id = $1", m.ID); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } // RawQuery if r, err := c.RawQuery(ctx, "SELECT count(*) FROM mock_models"); err != nil { t.Fatalf("Select failed %v", err) } else { var count int err := r.Scan(ctx, &count) if err != nil { t.Fatalf("failed to scan %v", err) } require.Equal(t, 3, count) } // UpdateAll with no constraint if r, err := c.UpdateAll(m.TableName(), Attrs{"bool_field": true}).Exec(ctx); err != nil || r.RowsAffected != 3 { t.Fatalf("update all failed with rows returned %v and error %v", r.RowsAffected, err) } // UpdateAll with constraint m.BoolField = false if err := c.Insert(ctx, m); err != nil { t.Fatalf("Error inserting %v", err) } if r, err := c.UpdateAll(m.TableName(), Attrs{"bool_field": false}).Where(Attrs{"bool_field": true}).Exec(ctx); err != nil || r.RowsAffected != 3 { t.Fatalf("update all failed with rows returned %v and error %v", r.RowsAffected, err) } // DeleteAll with constraint if result, err := c.DeleteAll(m.TableName()).Where(Attrs{"id": m.ID}).Exec(ctx); result.RowsAffected != 1 || err != nil { t.Fatalf("Error deleting with consrtaint, rows affected %v, error %v", result.RowsAffected, err) } // DeleteAll with no constraint if result, err := c.DeleteAll(m.TableName()).Exec(ctx); result.RowsAffected != 3 || err != nil { t.Fatalf("Error deleting with consrtaint, rows affected %v, error %v", result.RowsAffected, err) } // Nullable ID mn := &MockModelNullableID{ StringField: "test", NullStringField: NewNullString("test"), IntField: 5, FloatField: 4.5, BoolField: true, TimeField: time.Now(), } if mn.ID.Valid { t.Fatalf("id valid prior to insert") } // Insert if err := c.Insert(ctx, mn); err != nil { t.Fatalf("error inserting %v", err) } if !mn.ID.Valid { t.Fatalf("insert did not set id") } // Returning queries strField := "test string" m = &MockModel{StringField: strField} // InsertReturning insertCols := []string{"bool_field", "string_field", "int_field", "float_field", "time_field", "table"} if err := c.InsertReturning(ctx, m, insertCols...); err != nil { t.Fatalf("error inserting %v", err) } id := m.ID if id < 1 { t.Fatalf("insert did not set id") } if m.CreatedAt.IsZero() { t.Fatalf("created at not returned") } // UpdateReturning m = &MockModel{ID: id, BoolField: true} if err := c.UpdateReturning(ctx, m, "bool_field"); err != nil { t.Fatalf("error updating %v", err) } require.Equal(t, true, m.BoolField) require.Equal(t, strField, m.StringField) // DeleteReturning m = &MockModel{ID: id} if err := c.DeleteReturning(ctx, m); err != nil { t.Fatalf("error deleting %v", err) } require.Equal(t, true, m.BoolField) require.Equal(t, strField, m.StringField) } type QuoteNeededModel struct { ID int `sql:"id"` QuoteNeededField string `sql:"table"` // use reserved word } func (*QuoteNeededModel) TableName() string { return "table" // use reserved word } func TestClient_Quoting(t *testing.T) { var createTable = `create table "table" (id bigserial primary key, "table" text)` c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(createTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec(`drop table "table"`) _ = c.Close() }() ctx := context.Background() m := &QuoteNeededModel{QuoteNeededField: "text"} // Insert if err := c.Insert(ctx, m); err != nil { t.Fatalf("error inserting %v", err) } if m.ID < 1 { t.Fatalf("insert did not set id") } var results []*QuoteNeededModel if err := c.Select(m.TableName()).Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } result := results[0] if result.ID != m.ID { t.Fatalf("ids do not match (%v and %v)", result.ID, m.ID) } require.Equal(t, m.QuoteNeededField, result.QuoteNeededField) // Update m.QuoteNeededField = "table" results = nil if err := c.Update(ctx, m); err != nil { t.Fatalf("Error updating %v", err) } if err := c.Select(m.TableName()).Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } result = results[0] require.Equal(t, m.QuoteNeededField, result.QuoteNeededField) // Delete if i, err := c.Delete(ctx, m); err != nil { t.Fatalf("Error deleting (rows affected %v) %v", i, err) } results = nil if err := c.Select(m.TableName()).Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 0 { t.Fatalf("results returned incorrect amount, expected 0 and got %v", len(results)) } } func TestSliceModelProvider_NextModel(t *testing.T) { arr := make([]Model, 1) arr[0] = &MockModel{} p := NewSliceModelProvider(arr) if m := p.NextModel(); m == nil { t.Fatal("expected next model to not be nil") } if m := p.NextModel(); m != nil { t.Fatal("expected next model to be nil") } if m := p.NextModel(); m != nil { t.Fatal("expected next model to be nil") } } func TestChannelModelProvider_NextModel(t *testing.T) { ch := make(chan Model, 1) ch <- &MockModel{} m := &MockModel{} p := NewChannelModelProvider(m, ch) if m := p.NextModel(); m == nil { t.Fatal("expected next model to not be nil") } if m := p.NextModel(); m == nil { t.Fatal("expected next model to not be nil") } if m := p.NextModel(); m != nil { t.Fatal("expected next model to be nil") } if m := p.NextModel(); m != nil { t.Fatal("expected next model to be nil") } close(ch) if m := p.NextModel(); m != nil { t.Fatal("expected next model to be nil") } } func TestClient_BulkInsert(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() models := []Model{ &MockModel{ StringField: "test1", NullStringField: NewNullString("test"), IntField: 1, FloatField: 4.5, BoolField: true, TimeField: time.Now(), Table: "table", }, &MockModel{ StringField: "test2", NullStringField: NewNullString("test"), IntField: 2, FloatField: 5.6, BoolField: false, TimeField: time.Now(), }, &MockModel{ StringField: "test3", NullStringField: NewNullString("test"), IntField: 3, FloatField: 6.7, BoolField: true, TimeField: time.Now(), }, } ctx := context.Background() // Slice Model Provider if err := c.BulkInsert(NewSliceModelProvider(models)); err != nil { t.Fatalf("bulk insert failed, %v", err) } results := make([]*MockModel, 0) if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != len(models) { t.Fatalf("results returned incorrect amount, expected %v and got %v", len(models), len(results)) } // Clear data for next test if r, err := c.DeleteAll("mock_models").Exec(ctx); err != nil || r.RowsAffected != int64(len(models)) { t.Fatalf("error deleting %v rows affected, error: %v", r.RowsAffected, err) } // Channel Model Provider n := len(models) - 1 ch := make(chan Model, n) m := models[n] for i := 0; i < n; i++ { ch <- models[i] } if err := c.BulkInsert(NewChannelModelProvider(m, ch)); err != nil { t.Fatalf("bulk insert failed, %v", err) } results = nil if err := c.Select("mock_models").OrderBy("string_field asc").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != len(models) { t.Fatalf("results returned incorrect amount, expected %v and got %v", len(models), len(results)) } for i, result := range results { require.Equal(t, fmt.Sprintf("test%v", i+1), result.StringField) require.Equal(t, NewNullString("test"), result.NullStringField) } // Clear data for next test if r, err := c.DeleteAll("mock_models").Exec(ctx); err != nil || r.RowsAffected != int64(len(models)) { t.Fatalf("error deleting %v rows affected, error: %v", r.RowsAffected, err) } // Channel Model Provider Cap() n = len(models) - 1 ch = make(chan Model, n-1) m = models[n] go func() { for i := 0; i < n; i++ { ch <- models[i] } }() if err := c.BulkInsert(NewChannelModelProvider(m, ch)); err != nil { t.Fatalf("bulk insert failed, %v", err) } results = nil if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != len(models)-1 { t.Fatalf("results returned incorrect amount, expected %v and got %v", len(models)-1, len(results)) } } func TestClient_EmbeddedModelSlice(t *testing.T) { type EmbeddedMockModel struct { StringField string `sql:"string_field"` // will not override embedded MockModel FloatField float64 `sql:"float_field"` // will override embedded } c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() m := &MockModel{ StringField: "test", NullStringField: NewNullString("test"), IntField: 5, FloatField: 4.5, BoolField: true, TimeField: time.Now(), } ctx := context.Background() // Insert if err := c.Insert(ctx, m); err != nil { t.Fatalf("error inserting %v", err) } if m.ID < 1 { t.Fatalf("insert did not set id") } var results []*EmbeddedMockModel if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } result := results[0] if result.ID != m.ID { t.Fatalf("ids do not match (%v and %v)", result.ID, m.ID) } if result.MockModel.StringField != m.StringField || result.StringField != "" || // overridden in embedded struct result.IntField != m.IntField || result.MockModel.IntField != m.IntField || result.FloatField != m.FloatField || result.MockModel.FloatField != 0 || // overridden in main struct result.BoolField != m.BoolField || !result.NullStringField.Valid { t.Fatalf("result does not match expect (%v and %v)", result, m) } result = &EmbeddedMockModel{} if err := c.Select("mock_models").Scan(ctx, result); err != nil { t.Fatalf("Select failed %v", err) } if result.ID != m.ID { t.Fatalf("ids do not match (%v and %v)", result.ID, m.ID) } if result.MockModel.StringField != m.StringField || result.StringField != "" || // overridden in embedded struct result.IntField != m.IntField || result.MockModel.IntField != m.IntField || result.FloatField != m.FloatField || result.MockModel.FloatField != 0 || // overridden in main struct result.BoolField != m.BoolField || !result.NullStringField.Valid { t.Fatalf("result does not match expect (%v and %v)", result, m) } } func TestClient_EmbeddedModelInsert(t *testing.T) { type EmbeddedMockModel struct { StringField string `sql:"string_field"` // will not override embedded MockModel FloatField float64 `sql:"float_field"` // will override embedded } c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() m := &EmbeddedMockModel{ StringField: "will be overridden", MockModel: MockModel{ StringField: "test", NullStringField: NewNullString("test"), IntField: 5, FloatField: 4.5, BoolField: true, TimeField: time.Now(), }, FloatField: 5.5, } ctx := context.Background() // Insert if err := c.Insert(ctx, m); err != nil { t.Fatalf("error inserting %v", err) } if m.ID < 1 { t.Fatalf("insert did not set id") } var results []*MockModel if err := c.Select("mock_models").Slice(ctx, &results); err != nil { t.Fatalf("Select failed %v", err) } if len(results) != 1 { t.Fatalf("results returned incorrect amount, expected 1 and got %v", len(results)) } result := results[0] if result.ID != m.ID { t.Fatalf("ids do not match (%v and %v)", result.ID, m.ID) } if result.StringField != m.MockModel.StringField || result.IntField != m.IntField || result.FloatField != m.FloatField || result.BoolField != m.BoolField || !result.NullStringField.Valid { t.Fatalf("result does not match expect (%v and %v)", result, m) } } func TestClient_RunInTransaction(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "no error returned": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() err := c.RunInTransaction(ctx, func(ctx context.Context, tx *Tx) error { err := tx.Update(ctx, MockModel{ID: 1, IntField: 20}, "int_field") require.Nil(t, err) err = tx.Update(ctx, MockModel{ID: 1, IntField: 6}, "int_field") require.Nil(t, err) return nil }, nil) require.Nil(t, err) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{6, 10}) }, }, "panic": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() defer func() { require.NotNil(t, recover()) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err := q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4, 10}) }() c.RunInTransaction(ctx, func(ctx context.Context, tx *Tx) error { err := tx.Update(ctx, MockModel{ID: 1, IntField: 20}, "int_field") require.Nil(t, err) err = tx.Update(ctx, MockModel{ID: 1, IntField: 6}, "int_field") require.Nil(t, err) panic(errors.New("error for use in panic")) }, nil) }, }, "error returned": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() err := c.RunInTransaction(ctx, func(ctx context.Context, tx *Tx) error { err := tx.Update(ctx, MockModel{ID: 1, IntField: 20}, "int_field") require.Nil(t, err) err = tx.Update(ctx, MockModel{ID: 1, IntField: 6}, "int_field") require.Nil(t, err) return errors.New("some error returned") }, nil) require.Nil(t, err) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } // test individual methods func TestClient_Select(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "select values": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() var results []int q := c.Select(MockModel{}.TableName(), "int_field") err := q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4, 10}) }, }, "select models": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() var results []MockModel q := c.Select(MockModel{}.TableName()) err := q.OrderBy("id asc").Slice(ctx, &results) require.Nil(t, err) var ids []int var ints []int for _, r := range results { ids = append(ids, r.ID) ints = append(ints, r.IntField) } require.ElementsMatch(t, ids, []int{1, 2}) require.ElementsMatch(t, ints, []int{4, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_Insert(t *testing.T) { tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "insert 2 models": { Run: func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } var results []int q := c.Select(MockModel{}.TableName(), "int_field") err := q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_Update(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "update a model": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() err := c.Update(ctx, MockModel{ID: 1, IntField: 20}, "int_field") require.Nil(t, err) err = c.Update(ctx, MockModel{ID: 1, IntField: 6}, "int_field") require.Nil(t, err) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{6, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_Delete(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "delete a model": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() i, err := c.Delete(ctx, MockModel{ID: 2}) require.Nil(t, err) require.Equal(t, int64(1), i) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_Save(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "update a model": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() err := c.Save(ctx, MockModel{ID: 1, IntField: 20}, "int_field") require.Nil(t, err) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{10, 20}) }, }, "insert a model": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() err := c.Save(ctx, &MockModel{IntField: 20}, "int_field") require.Nil(t, err) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4, 10, 20}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_UpdateAll(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 5}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "update models": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() q := c.UpdateAll(MockModel{}.TableName(), Attrs{"int_field": -1}) r, err := q.WhereRaw("int_field < %v", 10).Exec(ctx) require.Nil(t, err) require.Equal(t, int64(2), r.RowsAffected) var results []int q = c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{-1, -1, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_DeleteAll(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 5}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "update models": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() q := c.DeleteAll(MockModel{}.TableName()) r, err := q.WhereRaw("int_field < %v", 10).Exec(ctx) require.Nil(t, err) require.Equal(t, int64(2), r.RowsAffected) var results []int q = c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_RawSelect(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "select values": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() var results []int err := c.RawSelect(ctx, &results, "select int_field from mock_models where int_field < $1", 10) require.Nil(t, err) require.ElementsMatch(t, results, []int{4}) results = nil q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4, 10}) }, }, "select models": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() err := c.RunInTransaction(ctx, func(ctx context.Context, tx *Tx) error { var results []MockModel err := tx.RawSelect(ctx, &results, "select * from mock_models where int_field < $1", 10) require.Nil(t, err) var ids []int var ints []int for _, r := range results { ids = append(ids, r.ID) ints = append(ints, r.IntField) } require.ElementsMatch(t, ids, []int{1}) require.ElementsMatch(t, ints, []int{4}) return nil }, nil) require.Nil(t, err) var results []MockModel q := c.Select(MockModel{}.TableName()) err = q.OrderBy("id asc").Slice(ctx, &results) require.Nil(t, err) var ids []int var ints []int for _, r := range results { ids = append(ids, r.ID) ints = append(ints, r.IntField) } require.ElementsMatch(t, ids, []int{1, 2}) require.ElementsMatch(t, ints, []int{4, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_RawQuery(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "update models": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() r, err := c.RawQuery(ctx, "update mock_models set int_field = $1 where int_field < $1 returning id", 10) require.Nil(t, err) var results []int err = r.Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, []int{1}, results) results = nil q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{10, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_InsertReturning(t *testing.T) { tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "insert 2 models": { Run: func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.InsertReturning(ctx, m) require.Nil(t, err) require.Greater(t, m.ID, 0) require.Greater(t, m.IntField, 0) } var results []int q := c.Select(MockModel{}.TableName(), "int_field") err := q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_UpdateReturning(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "update a model": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() m := &MockModel{ID: 1, IntField: 20} err := c.UpdateReturning(ctx, m, "int_field") require.Nil(t, err) r, err := c.UpdateAll(m.TableName(), Attrs{"float_field": 4.6}).Exec(ctx) require.Nil(t, err) require.Equal(t, int64(2), r.RowsAffected) m.IntField = 6 err = c.UpdateReturning(ctx, m, "int_field") require.Nil(t, err) require.Equal(t, 6, m.IntField) require.Equal(t, 4.6, m.FloatField) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{6, 10}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } } func TestClient_DeleteReturning(t *testing.T) { before := func(t *testing.T, c *Client) { ctx := context.Background() models := []*MockModel{ {IntField: 4}, {IntField: 10}, } for _, m := range models { err := c.Insert(ctx, m) require.Nil(t, err) } } tcs := map[string]struct { Before func(*testing.T, *Client) Run func(*testing.T, *Client) }{ "delete a model": { Before: before, Run: func(t *testing.T, c *Client) { ctx := context.Background() m := &MockModel{ID: 2} err := c.DeleteReturning(ctx, m) require.Nil(t, err) require.Equal(t, 10, m.IntField) var results []int q := c.Select(MockModel{}.TableName(), "int_field") err = q.OrderBy("int_field asc").Slice(ctx, &results) require.Nil(t, err) require.ElementsMatch(t, results, []int{4}) }, }, } for name, tc := range tcs { t.Run(name, func(t *testing.T) { c := NewClient(nil) if err := c.Start(""); err != nil { t.Fatalf("Failed to start %v", err) } if _, err := c.Exec(modelsTable); err != nil { t.Fatalf("failed to create table %v", err) } defer func() { _, _ = c.Exec("drop table mock_models") _ = c.Close() }() if tc.Before != nil { tc.Before(t, c) } tc.Run(t, c) }) } }
true
780ef181abce9bef83e795f6849e83e6b6b8854f
Go
paingha/auth-service
/utils/verifyjwt.go
UTF-8
1,419
3.171875
3
[]
no_license
[]
no_license
package utils import ( "fmt" "os" jwt "github.com/dgrijalva/jwt-go" ) //Claims struct for Jwt type Claims struct { ID uint `json:"id"` jwt.StandardClaims } //VerifyJWT takes in token as a string and returns a boolean. func VerifyJWT(jwtToken string) (bool, uint64) { var response = false var emptyString uint64 = 0 // Initialize a new instance of `Claims` //fmt.Println(jwtToken) claims := &Claims{} // Parse the JWT string and store the result in `claims`. // Note that we are passing the key in this method as well. This method will return an error // if the token is invalid (if it has expired according to the expiry time we set on sign in), // or if the signature does not match tkn, err := jwt.ParseWithClaims(jwtToken, claims, func(token *jwt.Token) (interface{}, error) { return []byte(os.Getenv("JWT_SECRET")), nil }) if err != nil { if err == jwt.ErrSignatureInvalid { //w.WriteHeader(http.StatusUnauthorized) fmt.Println("Token Error") response = false return response, emptyString } fmt.Println("Bad Request") response = false return response, emptyString } if !tkn.Valid { //w.WriteHeader(http.StatusUnauthorized) fmt.Println("Invalid Token") response = false return response, emptyString } // Finally, return the welcome message to the user, along with their // username given in the token response = true return response, uint64(claims.ID) }
true
4499f4bfe92d6a1cb29424043e4af802b37f75a4
Go
kannappanr/minio
/cmd/erasure_test.go
UTF-8
7,057
2.984375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Minio Cloud Storage, (C) 2016 Minio, 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 cmd import ( "bytes" "os" "testing" ) // mustEncodeData - encodes data slice and provides encoded 2 dimensional slice. func mustEncodeData(data []byte, dataBlocks, parityBlocks int) [][]byte { encodedData, err := encodeData(data, dataBlocks, parityBlocks) if err != nil { // Upon failure panic this function. panic(err) } return encodedData } // Generates good encoded data with one parity block and data block missing. func getGoodEncodedData(data []byte, dataBlocks, parityBlocks int) [][]byte { encodedData := mustEncodeData(data, dataBlocks, parityBlocks) encodedData[3] = nil encodedData[1] = nil return encodedData } // Generates bad encoded data with one parity block and data block with garbage data. func getBadEncodedData(data []byte, dataBlocks, parityBlocks int) [][]byte { encodedData := mustEncodeData(data, dataBlocks, parityBlocks) encodedData[3] = []byte("garbage") encodedData[1] = []byte("garbage") return encodedData } // Generates encoded data with all data blocks missing. func getMissingData(data []byte, dataBlocks, parityBlocks int) [][]byte { encodedData := mustEncodeData(data, dataBlocks, parityBlocks) for i := 0; i < dataBlocks+1; i++ { encodedData[i] = nil } return encodedData } // Generates encoded data with less number of blocks than expected data blocks. func getInsufficientData(data []byte, dataBlocks, parityBlocks int) [][]byte { encodedData := mustEncodeData(data, dataBlocks, parityBlocks) // Return half of the data. return encodedData[:dataBlocks/2] } // Represents erasure encoding matrix dataBlocks and paritBlocks. type encodingMatrix struct { dataBlocks int parityBlocks int } // List of encoding matrices the tests will run on. var encodingMatrices = []encodingMatrix{ {3, 3}, // 3 data, 3 parity blocks. {4, 4}, // 4 data, 4 parity blocks. {5, 5}, // 5 data, 5 parity blocks. {6, 6}, // 6 data, 6 parity blocks. {7, 7}, // 7 data, 7 parity blocks. {8, 8}, // 8 data, 8 parity blocks. } // Tests erasure decoding functionality for various types of inputs. func TestErasureDecode(t *testing.T) { data := []byte("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.") // List of decoding cases // - validates bad encoded data. // - validates good encoded data. // - validates insufficient data. testDecodeCases := []struct { enFn func([]byte, int, int) [][]byte shouldPass bool }{ // Generates bad encoded data. { enFn: getBadEncodedData, shouldPass: false, }, // Generates good encoded data. { enFn: getGoodEncodedData, shouldPass: true, }, // Generates missing data. { enFn: getMissingData, shouldPass: false, }, // Generates short data. { enFn: getInsufficientData, shouldPass: false, }, } // Validates all decode tests. for i, testCase := range testDecodeCases { for _, encodingMatrix := range encodingMatrices { // Encoding matrix. dataBlocks := encodingMatrix.dataBlocks parityBlocks := encodingMatrix.parityBlocks // Data block size. blockSize := len(data) // Test decoder for just the missing data blocks { // Generates encoded data based on type of testCase function. encodedData := testCase.enFn(data, dataBlocks, parityBlocks) // Decodes the data. err := decodeMissingData(encodedData, dataBlocks, parityBlocks) if err != nil && testCase.shouldPass { t.Errorf("Test %d: Expected to pass by failed instead with %s", i+1, err) } // Proceed to extract the data blocks. decodedDataWriter := new(bytes.Buffer) _, err = writeDataBlocks(decodedDataWriter, encodedData, dataBlocks, 0, int64(blockSize)) if err != nil && testCase.shouldPass { t.Errorf("Test %d: Expected to pass by failed instead with %s", i+1, err) } // Validate if decoded data is what we expected. if bytes.Equal(decodedDataWriter.Bytes(), data) != testCase.shouldPass { err := errUnexpected t.Errorf("Test %d: Expected to pass by failed instead %s", i+1, err) } } // Test decoder for all missing data and parity blocks { // Generates encoded data based on type of testCase function. encodedData := testCase.enFn(data, dataBlocks, parityBlocks) // Decodes the data. err := decodeDataAndParity(encodedData, dataBlocks, parityBlocks) if err != nil && testCase.shouldPass { t.Errorf("Test %d: Expected to pass by failed instead with %s", i+1, err) } // Proceed to extract the data blocks. decodedDataWriter := new(bytes.Buffer) _, err = writeDataBlocks(decodedDataWriter, encodedData, dataBlocks, 0, int64(blockSize)) if err != nil && testCase.shouldPass { t.Errorf("Test %d: Expected to pass by failed instead with %s", i+1, err) } // Validate if decoded data is what we expected. if bytes.Equal(decodedDataWriter.Bytes(), data) != testCase.shouldPass { err := errUnexpected t.Errorf("Test %d: Expected to pass by failed instead %s", i+1, err) } } } } } // Setup for erasureCreateFile and erasureReadFile tests. type erasureTestSetup struct { dataBlocks int parityBlocks int blockSize int64 diskPaths []string disks []StorageAPI } // Removes the temporary disk directories. func (e erasureTestSetup) Remove() { for _, path := range e.diskPaths { os.RemoveAll(path) } } // Returns an initialized setup for erasure tests. func newErasureTestSetup(dataBlocks int, parityBlocks int, blockSize int64) (*erasureTestSetup, error) { diskPaths := make([]string, dataBlocks+parityBlocks) disks := make([]StorageAPI, len(diskPaths)) var err error for i := range diskPaths { disks[i], diskPaths[i], err = newPosixTestSetup() if err != nil { return nil, err } err = disks[i].MakeVol("testbucket") if err != nil { return nil, err } } return &erasureTestSetup{dataBlocks, parityBlocks, blockSize, diskPaths, disks}, nil }
true
1c157b29fce842a6833b64cedff495a9292ef528
Go
go-hep/hep
/groot/riofs/plugin/http/span_test.go
UTF-8
4,580
3.09375
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
// Copyright ©2022 The go-hep Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http import ( "reflect" "testing" ) func TestSpanSplit(t *testing.T) { mk := func(beg, end int64) span { return span{ off: beg, len: end - beg, } } from := func(vs ...int64) []span { if len(vs) == 0 { return nil } o := make([]span, 0, len(vs)/2) for i := 0; i < len(vs); i += 2 { o = append(o, mk(vs[i], vs[i+1])) } return o } for _, tc := range []struct { spans []span sp span want []span }{ { spans: from(), sp: span{0, 2}, want: from(0, 2), }, // 1-1 intersects { spans: from(2, 4), sp: mk(0, 3), want: from(0, 2), }, { spans: from(2, 4), sp: mk(3, 5), want: from(4, 5), }, { spans: from(2, 5), sp: mk(3, 4), want: from(), }, { spans: from(2, 4), sp: mk(0, 5), want: from(0, 2, 4, 5), }, { spans: from(2, 4), sp: mk(0, 4), want: from(0, 2), }, { spans: from(2, 4), sp: mk(2, 5), want: from(4, 5), }, { spans: from(2, 4), sp: mk(0, 2), want: from(0, 2), }, { spans: from(2, 4), sp: mk(0, 1), want: from(0, 1), }, { spans: from(2, 4), sp: mk(4, 6), want: from(4, 6), }, { spans: from(2, 4), sp: mk(5, 6), want: from(5, 6), }, // { spans: from(0, 4, 5, 7), sp: mk(0, 7), want: from(4, 5), }, { spans: from(0, 4, 5, 7), sp: mk(0, 6), want: from(4, 5), }, { spans: from(0, 4, 5, 7), sp: mk(7, 9), want: from(7, 9), }, // 2-1 intersects { spans: from(1, 4, 6, 8), sp: mk(3, 7), want: from(4, 6), }, { spans: from(1, 4, 6, 8), sp: mk(3, 10), want: from(4, 6, 8, 10), }, { spans: from(1, 4, 6, 8), sp: mk(3, 5), want: from(4, 5), }, { spans: from(1, 4, 6, 8), sp: mk(1, 5), want: from(4, 5), }, { spans: from(1, 4, 6, 8), sp: mk(1, 7), want: from(4, 6), }, { spans: from(1, 4, 6, 8), sp: mk(1, 10), want: from(4, 6, 8, 10), }, { spans: from(1, 4, 6, 8), sp: mk(0, 5), want: from(0, 1, 4, 5), }, { spans: from(1, 4, 6, 8), sp: mk(0, 7), want: from(0, 1, 4, 6), }, { spans: from(1, 4, 6, 8), sp: mk(0, 10), want: from(0, 1, 4, 6, 8, 10), }, { spans: from(1, 4, 6, 8), sp: mk(4, 5), want: from(4, 5), }, { spans: from(1, 4, 6, 8), sp: mk(4, 7), want: from(4, 6), }, { spans: from(1, 4, 6, 8), sp: mk(4, 10), want: from(4, 6, 8, 10), }, { spans: from(1, 4, 6, 8), sp: mk(1, 8), want: from(4, 6), }, { spans: from(1, 4, 6, 8), sp: mk(1, 4), want: from(), }, { spans: from(1, 4, 6, 8), sp: mk(1, 6), want: from(4, 6), }, { spans: from(1, 4, 6, 8), sp: mk(4, 6), want: from(4, 6), }, { spans: from(1, 4, 6, 8), sp: mk(4, 8), want: from(4, 6), }, { spans: from(1, 4, 6, 8), sp: mk(6, 8), want: from(), }, } { t.Run("", func(t *testing.T) { got := split(tc.sp, tc.spans) if !reflect.DeepEqual(got, tc.want) { t.Fatalf("invalid split:\ngot= %+v\nwant=%+v", got, tc.want) } }) } } func TestSpanAdd(t *testing.T) { mk := func(beg, end int64) span { return span{ off: beg, len: end - beg, } } from := func(vs ...int64) []span { if len(vs) == 0 { return nil } o := make([]span, 0, len(vs)/2) for i := 0; i < len(vs); i += 2 { o = append(o, mk(vs[i], vs[i+1])) } return o } for _, tc := range []struct { spans []span sp span want []span }{ { spans: from(), sp: mk(0, 10), want: from(0, 10), }, { spans: from(), sp: mk(9, 10), want: from(9, 10), }, { spans: from(1, 3, 4, 6), sp: mk(3, 4), want: from(1, 6), }, { spans: from(1, 3, 4, 6), sp: mk(0, 1), want: from(0, 3, 4, 6), }, { spans: from(1, 3, 4, 6), sp: mk(6, 10), want: from(1, 3, 4, 10), }, { spans: from(1, 3, 4, 6), sp: mk(7, 10), want: from(1, 3, 4, 6, 7, 10), }, { spans: from(2, 3, 4, 6), sp: mk(0, 1), want: from(0, 1, 2, 3, 4, 6), }, } { t.Run("", func(t *testing.T) { got := make(spans, len(tc.spans)) copy(got, tc.spans) got.add(tc.sp) if !reflect.DeepEqual(got, spans(tc.want)) { t.Fatalf("invalid span-add:\ngot= %+v\nwant=%+v", got, tc.want) } }) } }
true
fb1a5649f1ff2c920c2b0110bffe156f795a242d
Go
vbatts/gossl
/conn.go
UTF-8
2,007
2.765625
3
[]
no_license
[]
no_license
package gossl /* #include "openssl/ssl.h" #include "openssl/err.h" #cgo pkg-config: openssl */ import "C" import "time" import "net" import "fmt" var _ = fmt.Println type Conn struct { conn net.Conn ssl *SSL bio *BIO err error handshakeCompleted bool } func (self *Conn) Conn() net.Conn { return self.conn } // basic connection, must call either NewServerConn or NewClientConn func newConn(ctx *Context, conn net.Conn) (*Conn, error) { self := &Conn{ssl: NewSSL(ctx), bio: NewBIO(BIOConn()), conn: conn} self.bio.SetAppData(self) self.ssl.SetBIO(self.bio, self.bio) return self, nil } // create a new server connection func NewServerConn(ctx *Context, conn net.Conn) (*Conn, error) { sslConn, err := newConn(ctx, conn) if err != nil { return nil, err } sslConn.ssl.SetAcceptState() return sslConn, nil } // create a new client connection func NewClientConn(ctx *Context, conn net.Conn) (*Conn, error) { sslConn, err := newConn(ctx, conn) if err != nil { return nil, err } sslConn.ssl.SetConnectState() return sslConn, nil } func (self *Conn) Close() error { return self.ssl.Shutdown() } func (self *Conn) LocalAddr() net.Addr { return self.conn.LocalAddr() } func (self *Conn) RemoteAddr() net.Addr { return self.conn.RemoteAddr() } func (self *Conn) Read(b []byte) (int, error) { if err := self.Handshake(); err != nil { fmt.Printf("handshake failed %s;\n", err) return 0, err } return self.ssl.Read(b) } func (self *Conn) Write(b []byte) (int, error) { if err := self.Handshake(); err != nil { return 0, err } return self.ssl.Write(b) } func (self *Conn) SetDeadline(t time.Time) error { return nil } func (self *Conn) SetReadDeadline(t time.Time) error { return nil } func (self *Conn) SetWriteDeadline(t time.Time) error { return nil } func (self *Conn) Handshake() (err error) { if !self.handshakeCompleted { err = self.ssl.Handshake() self.handshakeCompleted = true } return }
true
259aa59c3166b5cf470c25bdb8a67bca24729553
Go
chaokaikai1/GoProject
/daxigua.com/gostudy/day04/func2/main.go
UTF-8
383
3.921875
4
[]
no_license
[]
no_license
package main import "fmt" func sum(x, y int) int { return x + y } func f1(f func(x, y int) int) { i := f(1, 2) fmt.Println(i) } func f2(x, y int) (ret func(name string) string) { age := x + y ret = func(name string) string { return name } fmt.Println(age) //fmt.Println(ret) return } func main() { //函数作为参数 f1(sum) //函数作为返回值 f2(2, 2) }
true
c07d6ee123d6ab7f451fd93e28664c6b74d8e74d
Go
tangxusc/cqrs-db
/pkg/protocol/mysql_impl/parser/select.go
UTF-8
2,265
2.953125
3
[]
no_license
[]
no_license
package parser import ( "fmt" "github.com/xwb1989/sqlparser" ) type SelectParseResult struct { TableName string TableAsName string //名称,别名 ColumnMap map[string]string Where []string } func ParseSelect(stmt *sqlparser.Select) (result *SelectParseResult) { result = &SelectParseResult{} err := ParseTableName(stmt, result) if err != nil { return } err = ParseColumnName(stmt, result) if err != nil { return } err = ParseWhere(stmt, result) if err != nil { return } return } func ParseWhere(stmt *sqlparser.Select, result *SelectParseResult) error { if stmt.Where == nil { return nil } expr, ok := stmt.Where.Expr.(*sqlparser.ComparisonExpr) if !ok { return nil } val := expr.Right.(*sqlparser.SQLVal) result.Where = make([]string, 1) result.Where[0] = string(val.Val) return nil } func ParseColumnName(selectVar *sqlparser.Select, result *SelectParseResult) (err error) { exprs := []sqlparser.SelectExpr(selectVar.SelectExprs) result.ColumnMap = make(map[string]string, len(exprs)) for _, value := range exprs { switch value.(type) { case *sqlparser.AliasedExpr: expr := value.(*sqlparser.AliasedExpr) colName, ok := expr.Expr.(*sqlparser.ColName) if !ok { err = fmt.Errorf("不支持的列名称") return } colNameString := colName.Name.Lowered() colAsNameString := colNameString if !expr.As.IsEmpty() { colAsNameString = expr.As.Lowered() } result.ColumnMap[colNameString] = colAsNameString case *sqlparser.StarExpr: //对于*如何处理 default: err = fmt.Errorf("不支持nextval等函数") return } } return } func ParseTableName(selectVar *sqlparser.Select, result *SelectParseResult) (err error) { exprs := []sqlparser.TableExpr(selectVar.From) if len(exprs) != 1 { err = fmt.Errorf("不支持查询多个表") return } expr := exprs[0] switch expr.(type) { case *sqlparser.AliasedTableExpr: tableExpr := expr.(*sqlparser.AliasedTableExpr) result.TableAsName = tableExpr.As.String() name, ok := tableExpr.Expr.(sqlparser.TableName) if !ok { err = fmt.Errorf("不支持子查询等操作") return } result.TableName = name.Name.String() default: err = fmt.Errorf("不支持的sql查询") return } return }
true
cc8893fb4ecae57d5b30ad2a7cc05450d4141c2a
Go
gtalarico/pm
/internal/commands/commands_test.go
UTF-8
523
3.078125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package commands import ( "testing" ) func TestGetCommand(t *testing.T) { // Test Valid Commands inputs := [...]string{"go", "list", "add", "remove"} for _, input := range inputs { command, _ := GetCommand(input) if command.Name != input { t.Error("Test Failed: {} inputted, {} expected, recieved: {}", input, input, command.Name) } } // Test Invalid Command input := "invalidcmd" _, err := GetCommand(input) if err == nil { t.Error("Test Failed: {} inputted, {} expected", input, "an error") } }
true
b765476d51151a31ee7d1fa537eb169086d5d460
Go
benbjohnson/go-dblib
/integration/dsn.go
UTF-8
1,333
2.5625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// SPDX-FileCopyrightText: 2020 SAP SE // SPDX-FileCopyrightText: 2021 SAP SE // // SPDX-License-Identifier: Apache-2.0 package integration import ( "database/sql" "database/sql/driver" "github.com/SAP/go-dblib/dsn" ) // genSQLDBFn is the signature of functions stored in the genSQLDBMap. type genSQLDBFn func() (*sql.DB, error) // genSQLDBMap maps abstract names to functions, which are expected to // return unique sql.DBs. type genSQLDBMap map[string]genSQLDBFn var sqlDBMap = make(genSQLDBMap) // ConnectorCreator is the interface for function expected by InitDBs to // initialize driver.Connectors. type ConnectorCreator func(interface{}) (driver.Connector, error) // RegisterDSN registers at least one new genSQLDBFn in genSQLDBMap // based on sql.Open. // If connectorFn is non-nil a second genSQLDBFn is stored with the // suffix `connector`. func RegisterDSN(name string, info interface{}, connectorFn ConnectorCreator) error { sqlDBMap[name] = func() (*sql.DB, error) { db, err := sql.Open("ase", dsn.FormatSimple(info)) if err != nil { return nil, err } return db, nil } if connectorFn != nil { sqlDBMap[name+" connector"] = func() (*sql.DB, error) { connector, err := connectorFn(info) if err != nil { return nil, err } return sql.OpenDB(connector), nil } } return nil }
true
35bf7f7e1582b777b7ef5f6cf1a661c3d7b06d9f
Go
omkz/golang-echo-blog
/main.go
UTF-8
709
2.78125
3
[]
no_license
[]
no_license
package main import ( "github.com/labstack/echo/v4" "github.com/omkz/golang-echo-blog/controllers" "github.com/labstack/echo/v4/middleware" "net/http" ) func main() { // Echo instance e := echo.New() // Middleware // e.Use(middleware.Logger()) e.Use(middleware.Recover()) e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ Format: "method=${method}, uri=${uri}, status=${status}\n", })) e.Use(middleware.CORS()) // Routes e.GET("/", hello) e.GET("/posts", controllers.GetPosts) e.POST("/posts", controllers.CreatePost) // Start server e.Logger.Fatal(e.Start(":8080")) } // Handler func hello(c echo.Context) error { return c.String(http.StatusOK, "Hello, World!") }
true
886c122e2e04739e4b6052bb9c700662ff54e22c
Go
barnex/mjolnir
/helheim/user.go
UTF-8
1,196
2.921875
3
[]
no_license
[]
no_license
package helheim import ( "errors" "fmt" "io" "os/user" "strconv" ) // Cluster user. type User struct { name string share int // Relative group share of the user use int // Current number of jobs running que JobQueue group *Group mailbox Mailbox } // API func to add new group with share. func AddUserAPI(out io.Writer, usr *user.User, args []string) error { user := args[0] group := GetGroup(args[1]) if group == nil { return errors.New("no such group: " + args[1]) } share, err := strconv.Atoi(args[2]) if err != nil { return err } group.AddUser(user, share) return nil } func (u *User) String() string { return u.name } func (u *User) HasJobs() bool { return u.que.Len() > 0 } // Roughly the fractional use of the user. // User with largest share wins if no jobs are running yet func (u *User) FracUse() float64 { return (float64(u.use) + 1e-3) / float64(u.share) } // API func, prints user info. func Users(out io.Writer) error { for _, u := range users { fmt.Fprintln(out, u) } return nil } func GetUser(username string) *User { usr, ok := users[username] if !ok { panic(errors.New("unknown username: " + username)) } return usr }
true
c6c7dc40d225ab1ad202cdf9b3f60bd7b2354001
Go
team142/snaily
/model/user.go
UTF-8
1,133
2.984375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package model import ( "encoding/base64" uuid "github.com/satori/go.uuid" "golang.org/x/crypto/bcrypt" "log" "strings" ) type User struct { ID string `json:"id"` Email string `json:"email"` FirstName string `json:"firstname"` LastName string `json:"lastname"` Password string `json:"password"` } func (u *User) SaltAndSetPassword() { hash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.MinCost) if err != nil { log.Println(err) } u.Password = base64.StdEncoding.EncodeToString(hash) } func (u *User) CheckPassword(password string) (ok bool) { hashB, err := base64.StdEncoding.DecodeString(u.Password) if err != nil { panic(err) } hashP := []byte(password) err = bcrypt.CompareHashAndPassword(hashB, hashP) if err != nil { return false } return true } func NewUserFromEmail(email string) *User { return &User{ ID: uuid.NewV4().String(), Email: strings.ToLower(email), } } func (u *User) GetUserMessage() *MessageUserV1 { result := MessageUserV1{ ID: u.ID, FirstName: u.FirstName, LastName: u.LastName, Email: u.Email, } return &result }
true
c572181d0051304bd908eea9a16256eec323932e
Go
wantidea/api-go
/lib/response/message.go
UTF-8
4,611
2.625
3
[]
no_license
[]
no_license
package response import ( "fmt" ) const ( MsgSuccess = "成功" MsgError = "失败" ) // MsgList 消息 map var MsgList = map[int]string{ CodeSuccess: "成功", CodeError: "失败", CodeErrorInvalidParams: "参数验证失败", CodeErrorAuthCheckTokenNull: "请携带令牌 token", CodeErrorAuthCheckTokenFail: "令牌认证失败", CodeErrorAuthCheckTokenTimeout: "令牌过期", CodeErrorAuthRoute: "您无此操作权限", CodeErrorUserHasItem: "用户名已存在", CodeErrorRoleHasItem: "角色名已存在", CodeErrorRouteHasItem: "此路由已存在", CodeErrorSystem: "发生错误,请联系系统管理员", CodeErrorMongodb: "数据库操作失败,请联系管理员", CodeSuccessAdd: "添加成功", CodeSuccessDel: "删除成功", CodeSuccessUpd: "修改成功", CodeSuccessItem: "查询成功", CodeSuccessList: "列表查询成功", CodeErrorAdd: "添加失败", CodeErrorDel: "删除失败", CodeErrorUpd: "修改失败", CodeErrorItem: "查询失败", CodeErrorList: "列表查询失败", CodeSuccessUserAdd: MsgSuccessAddFormat(TypeUser), CodeSuccessUserDel: MsgSuccessDelFormat(TypeUser), CodeSuccessUserUpd: MsgSuccessUpdFormat(TypeUser), CodeSuccessUserItem: MsgSuccessItemFormat(TypeUser), CodeSuccessUserList: MsgSuccessListFormat(TypeUser), CodeSuccessRoleAdd: MsgSuccessAddFormat(TypeRole), CodeSuccessRoleDel: MsgSuccessDelFormat(TypeRole), CodeSuccessRoleUpd: MsgSuccessUpdFormat(TypeRole), CodeSuccessRoleItem: MsgSuccessItemFormat(TypeRole), CodeSuccessRoleList: MsgSuccessListFormat(TypeRole), CodeErrorUserAdd: MsgErrorAddFormat(TypeUser), CodeErrorUserDel: MsgErrorDelFormat(TypeUser), CodeErrorUserUpd: MsgErrorUpdFormat(TypeUser), CodeErrorUserItem: MsgErrorItemFormat(TypeUser), CodeErrorUserList: MsgErrorListFormat(TypeUser), CodeErrorRoleAdd: MsgErrorAddFormat(TypeRole), CodeErrorRoleDel: MsgErrorDelFormat(TypeRole), CodeErrorRoleUpd: MsgErrorUpdFormat(TypeRole), CodeErrorRoleItem: MsgErrorItemFormat(TypeRole), CodeErrorRoleList: MsgErrorListFormat(TypeRole), CodeSuccessAuth: MsgSuccessActionFormat(ActionLogin), CodeErrorAuth: MsgErrorActionFormat(ActionLogin), } // Msg 获取消息 func Msg(code int) string { msg, ok := MsgList[code] if ok { return msg } return MsgError } // MsgSuccessFormat 成功消息格式化 func MsgSuccessFormat(typeName string, action string) string { return fmt.Sprintf("%s %s %s", typeName, action, MsgSuccess) } // MsgErrorFormat 失败消息格式化 func MsgErrorFormat(typeName string, action string) string { return fmt.Sprintf("%s %s %s", typeName, action, MsgError) } // MsgSuccessAddFormat 添加成功消息格式化 func MsgSuccessAddFormat(typeName string) string { return MsgSuccessFormat(typeName, ActionAdd) } // MsgSuccessDelFormat 删除成功消息格式化 func MsgSuccessDelFormat(typeName string) string { return MsgSuccessFormat(typeName, ActionDel) } // MsgSuccessUpdFormat 修改成功消息格式化 func MsgSuccessUpdFormat(typeName string) string { return MsgSuccessFormat(typeName, ActionUpd) } // MsgSuccessItemFormat 详情查询成功消息格式化 func MsgSuccessItemFormat(typeName string) string { return MsgSuccessFormat(typeName, ActionItem) } // MsgSuccessListFormat 列表查询添加成功消息格式化 func MsgSuccessListFormat(typeName string) string { return MsgSuccessFormat(typeName, ActionList) } // MsgErrorAddFormat 添加失败消息格式化 func MsgErrorAddFormat(typeName string) string { return MsgErrorFormat(typeName, ActionAdd) } // MsgErrorDelFormat 删除失败消息格式化 func MsgErrorDelFormat(typeName string) string { return MsgErrorFormat(typeName, ActionDel) } // MsgErrorUpdFormat 修改失败消息格式化 func MsgErrorUpdFormat(typeName string) string { return MsgErrorFormat(typeName, ActionUpd) } // MsgErrorItemFormat 详情查询失败消息格式化 func MsgErrorItemFormat(typeName string) string { return MsgErrorFormat(typeName, ActionItem) } // MsgErrorListFormat 列表查询添加失败消息格式化 func MsgErrorListFormat(typeName string) string { return MsgErrorFormat(typeName, ActionList) } // MsgSuccessActionFormat 操作成功消息格式化 func MsgSuccessActionFormat(action string) string { return fmt.Sprintf("%s %s", action, MsgSuccess) } // MsgErrorActionFormat 操作失败消息格式化 func MsgErrorActionFormat(action string) string { return fmt.Sprintf("%s %s", action, MsgError) }
true
80c6ec63dd46dc33841bf8855fe105097f4cb1cd
Go
edualb/godmitri
/element/actinium_test.go
UTF-8
1,383
2.5625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package element import "testing" func TestActiniumGetPeriod(t *testing.T) { a := Actinium{} want := "7th period" got := a.GetPeriod() if got != want { t.Errorf("Actinium.GetPeriod() = got %v, want %v", got, want) } } func TestActiniumGetGroup(t *testing.T) { a := Actinium{} want := "3B" got := a.GetGroup() if got != want { t.Errorf("Actinium.GetGroup() = got %v, want %v", got, want) } } func TestActiniumGetCategory(t *testing.T) { a := Actinium{} want := "Actinoid" got := a.GetCategory() if got != want { t.Errorf("Actinium.GetCategory() = got %v, want %v", got, want) } } func TestActiniumGetName(t *testing.T) { a := Actinium{} want := "Actinium" got := a.GetName() if got != want { t.Errorf("Actinium.GetName() = got %v, want %v", got, want) } } func TestActiniumGetSimbol(t *testing.T) { a := Actinium{} want := "Ac" got := a.GetSimbol() if got != want { t.Errorf("Actinium.GetSimbol() = got %v, want %v", got, want) } } func TestActiniumGetAtomicNumber(t *testing.T) { a := Actinium{} want := 89 got := a.GetAtomicNumber() if got != want { t.Errorf("Actinium.GetAtomicNumber() = got %v, want %v", got, want) } } func TestActiniumGetAtomicWeight(t *testing.T) { a := Actinium{} var want float32 = 227 got := a.GetAtomicWeight() if got != want { t.Errorf("Actinium.GetAtomicWeight() = got %v, want %v", got, want) } }
true
7ee25ff84fc8e8658ac6a9951c113b6009b5bee4
Go
ilya-mim/oac2020
/day07/main.go
UTF-8
2,470
3.5625
4
[]
no_license
[]
no_license
package main import ( "container/list" "fmt" "io/ioutil" "regexp" "strconv" "strings" ) type bagRecord struct { color string count int } func readRules(path string) (map[string][]bagRecord, error) { content, err := ioutil.ReadFile(path) if err != nil { return nil, err } lines := strings.Split(string(content), "\n") rules := make(map[string][]bagRecord) reMain := regexp.MustCompile(`(?P<color>[a-z ]+) bags contain (?P<nobags>no other bags.)?`) reSub := regexp.MustCompile(`(?P<count>\d+) (?P<color>[a-z ]+) bags?[,|.]`) for _, line := range lines { matchesMain := reMain.FindStringSubmatch(line) matchesSub := reSub.FindAllStringSubmatch(line, -1) if matchesMain[2] != "" { rules[matchesMain[1]] = nil } else { rules[matchesMain[1]] = make([]bagRecord, len(matchesSub)) for i := 0; i < len(matchesSub); i++ { count, _ := strconv.Atoi(matchesSub[i][1]) rules[matchesMain[1]][i] = bagRecord{ color: matchesSub[i][2], count: count, } } } } return rules, nil } // TODO: ugly func calcOutside(rules map[string][]bagRecord, color string) int { count := 0 colorMap := make(map[string]bool) colors := list.New() colors.PushBack(color) for front := colors.Front(); front != nil; front = front.Next() { for key, bags := range rules { for _, bag := range bags { if bag.color == front.Value { if _, ok := colorMap[key]; !ok { colorMap[key] = true colors.PushBack(key) count++ } break } } } } return count } func calcInside(rules map[string][]bagRecord, color string) int { count := 0 colors := list.New() colors.PushBack(bagRecord{ color: color, count: 1, }) for front := colors.Front(); front != nil; front = front.Next() { for color, bags := range rules { if color == front.Value.(bagRecord).color { for _, bag := range bags { count += bag.count * front.Value.(bagRecord).count colors.PushBack(bagRecord{ color: bag.color, count: bag.count * front.Value.(bagRecord).count, }) fmt.Println("Bag color:", bag.color, bag.count*front.Value.(bagRecord).count) } break } } } return count } func main() { rules, err := readRules("input.txt") if err != nil { fmt.Println("File reading error", err) return } count := calcOutside(rules, "shiny gold") fmt.Println("Bag count outside:", count) count = calcInside(rules, "shiny gold") fmt.Println("Bag count inside:", count) }
true
2f7ed7df6d6da3e2a4a752214eceaf3407128b09
Go
BruceMaa/Panda
/wechat/mp/qrcode.go
UTF-8
4,212
2.703125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package mp import ( "encoding/json" "fmt" "github.com/BruceMaa/Panda/wechat/common" ) const ( WechatQrcodeCreateApi = `https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s` // 创建二维码API WechatQrcodeShowApi = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s` // 显示二维码API ) const ( WechatQrcodeScene = "QR_SCENE" // 二维码类型-临时的整型参数值 WechatQrcodeStrScene = "QR_STR_SCENE" // 二维码类型-临时的字符串参数值 WechatQrcodeLimitScene = "QR_LIMIT_SCENE" // 二维码类型-永久的整型参数值 WechatQrcodeLimitStrScene = "QR_LIMIT_STR_SCENE" // 二维码类型-永久的字符串参数值 ) type ( QrcodeRequest struct { ExpireSeconds int64 `json:"expire_seconds"` // 该二维码有效时间,以秒为单位。 最大不超过2592000(即30天),此字段如果不填,则默认有效期为30秒。 ActionName string `json:"action_name"` // 二维码类型,QR_SCENE为临时的整型参数值,QR_STR_SCENE为临时的字符串参数值,QR_LIMIT_SCENE为永久的整型参数值,QR_LIMIT_STR_SCENE为永久的字符串参数值 ActionInfo struct { Scene struct { SceneId int64 `json:"scene_id,omitempty"` // 场景值ID,临时二维码时为32位非0整型,永久二维码时最大值为100000(目前参数只支持1--100000) SceneStr string `json:"scene_str,omitempty"` // 场景值ID(字符串形式的ID),字符串类型,长度限制为1到64 } `json:"scene"` } `json:"action_info"` // 二维码详细信息 } QrcodeResponse struct { Ticket string `json:"ticket"` // 获取的二维码ticket,凭借此ticket可以在有效时间内换取二维码。 ExpireSeconds int64 `json:"expire_seconds,omitempty"` // 该二维码有效时间,以秒为单位。 最大不超过2592000(即30天)。 Url string `json:"url"` // 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片 } ) // 创建临时二维码,整型场景值 func (wm *WechatMp) QrcodeIntCreate(accessToken string, sceneId, expireSeconds int64) (*QrcodeResponse, error) { qrcodeRequest := &QrcodeRequest{ ExpireSeconds: expireSeconds, ActionName: WechatQrcodeScene, } qrcodeRequest.ActionInfo.Scene.SceneId = sceneId return qrcodeCreate(accessToken, qrcodeRequest) } // 创建临时二维码,字符串场景值 func (wm *WechatMp) QrcodeStrCreate(accessToken string, sceneStr string, expireSeconds int64) (*QrcodeResponse, error) { qrcodeRequest := &QrcodeRequest{ ExpireSeconds: expireSeconds, ActionName: WechatQrcodeStrScene, } qrcodeRequest.ActionInfo.Scene.SceneStr = sceneStr return qrcodeCreate(accessToken, qrcodeRequest) } // 创建永久二维码,整型场景值 func (wm *WechatMp) QrcodeIntLimitCreate(accessToken string, sceneId int64) (*QrcodeResponse, error) { qrcodeRequest := &QrcodeRequest{ ActionName: WechatQrcodeLimitScene, } qrcodeRequest.ActionInfo.Scene.SceneId = sceneId return qrcodeCreate(accessToken, qrcodeRequest) } // 创建永久二维码,字符串场景值 func (wm *WechatMp) QrcodeStrLimitCreate(accessToken, sceneStr string) (*QrcodeResponse, error) { qrcodeRequest := &QrcodeRequest{ ActionName: WechatQrcodeLimitStrScene, } qrcodeRequest.ActionInfo.Scene.SceneStr = sceneStr return qrcodeCreate(accessToken, qrcodeRequest) } // 创建二维码 func qrcodeCreate(accessToken string, qrcodeRequest *QrcodeRequest) (*QrcodeResponse, error) { resp, err := common.HTTPPostJson(fmt.Sprintf(WechatQrcodeCreateApi, accessToken), qrcodeRequest) if err != nil { fmt.Fprintf(common.WechatErrorLoggerWriter, "QrcodeCreate http error: %+v\n", err) return nil, err } var qrcodeResp QrcodeResponse if err = json.Unmarshal(resp, &qrcodeResp); err != nil { fmt.Fprintf(common.WechatErrorLoggerWriter, "QrcodeCreate json.Unmarshal() error: %+v\n", err) return nil, err } return &qrcodeResp, nil } // 显示二维码图片 func (wm *WechatMp) QrcodeShow(ticket string) ([]byte, error) { return common.HTTPGet(fmt.Sprintf(WechatQrcodeShowApi, ticket)) }
true
f56d6ce2f87d4a9dfd4e4f44b62990972cfac2ea
Go
dddjjj-atp/Weekend3
/main.go
UTF-8
891
3.046875
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "io/ioutil" "log" "net/http" ) type WeatherInfoJson struct { Weatherinfo WeatherinfoObject } type WeatherinfoObject struct { City string Temp string WD string WS string SD string Time string } func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) resp, err := http.Get("http://www.weather.com.cn/data/sk/101280101.html") if err != nil { log.Fatal(err) } defer resp.Body.Close() input, err := ioutil.ReadAll(resp.Body) var jsonWeather WeatherInfoJson json.Unmarshal(input, &jsonWeather) log.Println("城市:", jsonWeather.Weatherinfo.City) log.Println("温度:", jsonWeather.Weatherinfo.Temp, "℃") log.Println("风向:", jsonWeather.Weatherinfo.WD) log.Println("风力:", jsonWeather.Weatherinfo.WS) log.Println("湿度:", jsonWeather.Weatherinfo.SD) log.Println("时间:", jsonWeather.Weatherinfo.Time) }
true
6f07a36a6b2e46c9fec3b39ac3784e6fac198165
Go
magicmatatjahu/go-template
/template/controller.go
UTF-8
3,890
2.703125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
{%- from "../partials/go.template" import messageName -%} {%- from "../partials/go.template" import getOpBinding -%} package asyncapi import ( "asyncapi/transport" "asyncapi/channel" "asyncapi/message" "asyncapi/operation" "errors" ) type Controller struct { Transport transport.PubSub contentWriters map[string]transport.ContentWriter contentReaders map[string]transport.ContentReader } {% for ch_name, ch in asyncapi.channels() -%} {%- if ch.hasPublish() -%} {# These vars are effectively global to this file #} {%- set opName = ch.publish().id() | toGoPublicID -%} {%- set msgName = messageName(ch.publish().message()) -%} // {{ ch.publish().id() | toGoPublicID }} implements operation.Producer func (c Controller) {{ ch.publish().id() | toGoPublicID }}(params channel.{{opName}}Params, msg message.{{msgName}}) error { // Define any operation bindings. These are constant per operation {%- set bindingList = "" -%} {%- set counter = 0 -%} {%- for protocol, binding in ch.publish().bindings() -%} {{ getOpBinding(protocol, binding) }} {#- Append bindings variable name to a string of operation bindings (used in Subscribe below) -#} {%- if counter < ch.publish().bindings() | length -%} {%- set bindingList = bindingList + ", " -%} {% endif -%} {%- set bindingList = bindingList + protocol + "Bindings" -%} {%- set counter = counter + 1 %} {%- endfor %} // Throw error for missing content type encoder w, ok := c.contentWriters[msg.ContentType] if !ok { return errors.New("no message writer is registered for content type: " + msg.ContentType) } // Throw error if failed to encode payload var err error if msg.RawPayload, err = w.Write(msg.Body); err != nil { return err } // Publish the underlying transport.Message with the transport layer return c.Transport.Publish(params.Build(), msg.Message{{bindingList}}) } {% else -%} {# These vars are effectively global to this file #} {%- set opName = ch.subscribe().id() | toGoPublicID -%} {%- set msgName = messageName(ch.subscribe().message()) -%} // {{ ch.subscribe().id() | toGoPublicID }} implements operation.Consumer func (c Controller) {{ ch.subscribe().id() | toGoPublicID }}(params channel.{{opName}}Params, fn operation.{{msgName}}Handler) error { // Define any operation bindings. These are constant per operation {%- set bindingList = "" -%} {%- set counter = 0 -%} {%- for protocol, binding in ch.subscribe().bindings() -%} {{ getOpBinding(protocol, binding) }} {#- Append bindings variable name to a string of operation bindings (used in Subscribe below) -#} {%- if counter < ch.subscribe().bindings() | length -%} {%- set bindingList = bindingList + ", " -%} {% endif -%} {%- set bindingList = bindingList + protocol + "Bindings" -%} {%- set counter = counter + 1 %} {%- endfor %} // Subscribe with the transport layer. Wrap message handler /w logic to decode // transport.Message payload into {{msgName}} message c.Transport.Subscribe(params.Build(), func(ch string, rawMessage transport.Message) { // Init a new message object & attempt to use the defined content.Reader to parse // the message payload msg := message.New{{msgName}}(rawMessage) // TODO: Throw error before subscribing if expected content type reader is not registered r, ok := c.contentReaders[msg.ContentType] if !ok { panic("no ContentReader registered for contentType: " + msg.ContentType) } if err := r.Read(msg.RawPayload, &msg.Body); err != nil { panic(err) } // Parse the params out of the channel recParams := &channel.{{opName}}Params{} if err := recParams.Parse(ch); err != nil { panic(err) } // Call the operation's message handler fn(*recParams, msg) }{{bindingList}}) // TODO: Return an ErrorStream struct wrapping a chan error // instead of panics return nil } {% endif %} {% endfor -%}
true
50f0f164a5dff4a0b2ca15a49d4d20d57b5f2cb8
Go
sherif-fanous/go-feedly
/feedly/boards.go
UTF-8
9,772
2.609375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package feedly import ( "io" "net/http" "net/url" "strings" "github.com/dghubble/sling" "github.com/sfanous/go-feedly/internal/mapstructure" "github.com/sfanous/go-feedly/internal/mime" "github.com/sfanous/go-feedly/pkg/time" ) // BoardService provides methods for managing personal boards, aka tags. type BoardService struct { sling *sling.Sling } // newFeedService returns a new BoardService. func newBoardService(sling *sling.Sling) *BoardService { return &BoardService{ sling: sling, } } // Board is a Feedly board. type Board struct { Cover *string `json:"cover,omitempty"` Created *time.Time `json:"created,omitempty"` Customizable *bool `json:"customizable,omitempty"` Description *string `json:"description,omitempty"` Enterprise *bool `json:"enterprise,omitempty"` HTMLURL *string `json:"htmlUrl,omitempty"` ID *string `json:"id,omitempty"` IsPublic *bool `json:"isPublic,omitempty"` Label *string `json:"label,omitempty"` ShowHighlights *bool `json:"showHighlights,omitempty"` ShowNotes *bool `json:"showNotes,omitempty"` StreamID *string `json:"streamId,omitempty"` UnmappedFields map[string]interface{} `json:"-" mapstructure:",remain"` } // AddEntry adds one entry to one or more existing boards. func (s *BoardService) AddEntry(BoardIDs []string, entryID string) (*http.Response, error) { bodyJSON := &struct { EntryID string `json:"entryId,omitempty"` }{ EntryID: entryID, } apiError := new(APIError) resp, err := s.sling.New().Put("tags/"+url.PathEscape(strings.Join(BoardIDs, ","))).BodyJSON(bodyJSON).Receive(nil, apiError) return resp, relevantError(err, apiError) } // AddMultipleEntries adds one or more entries to one or more existing boards. func (s *BoardService) AddMultipleEntries(BoardIDs []string, entryIDs []string) (*http.Response, error) { bodyJSON := &struct { EntryIds []string `json:"entryIds,omitempty"` }{ EntryIds: entryIDs, } apiError := new(APIError) resp, err := s.sling.New().Put("tags/"+url.PathEscape(strings.Join(BoardIDs, ","))).BodyJSON(bodyJSON).Receive(nil, apiError) return resp, relevantError(err, apiError) } // BoardCreateOptionalParams are the optional parameters for BoardService.Create. type BoardCreateOptionalParams struct { Description *string `json:"description,omitempty"` ID *string `json:"id,omitempty"` IsPublic *bool `json:"isPublic,omitempty"` ShowHighlights *bool `json:"showHighlights,omitempty"` ShowNotes *bool `json:"showNotes,omitempty"` } // BoardCreateResponse represents the response from BoardService.Create. type BoardCreateResponse struct { Boards []Board `json:"boards"` UnmappedFields map[string]interface{} `json:"-" mapstructure:",remain"` } // Create creates a new board. func (s *BoardService) Create(label string, optionalParams *BoardCreateOptionalParams) (*BoardCreateResponse, *http.Response, error) { if optionalParams == nil { optionalParams = &BoardCreateOptionalParams{} } bodyJSON := &struct { *BoardCreateOptionalParams Label string `json:"label"` }{ BoardCreateOptionalParams: optionalParams, Label: label, } encodedResponse := make([]map[string]interface{}, 0) decodedResponse := new(BoardCreateResponse) apiError := new(APIError) resp, err := s.sling.New().Post("boards").BodyJSON(bodyJSON).Receive(&encodedResponse, apiError) if err := relevantError(err, apiError); err != nil { return nil, resp, err } if err := mapstructure.Decode(encodedResponse, &decodedResponse.Boards); err != nil { return nil, resp, err } return decodedResponse, resp, nil } // Delete deletes one or more existing boards. func (s *BoardService) Delete(boardIDs []string) (*http.Response, error) { apiError := new(APIError) resp, err := s.sling.New().Delete("tags/"+url.PathEscape(strings.Join(boardIDs, ","))).Receive(nil, apiError) return resp, relevantError(err, apiError) } // DeleteEntry deletes one entry from one or more existing boards. func (s *BoardService) DeleteEntry(BoardIDs []string, entryID string) (*http.Response, error) { bodyJSON := &struct { EntryID string `json:"entryId,omitempty"` }{ EntryID: entryID, } apiError := new(APIError) resp, err := s.sling.New().Delete("tags/"+url.PathEscape(strings.Join(BoardIDs, ","))).BodyJSON(bodyJSON).Receive(nil, apiError) return resp, relevantError(err, apiError) } // DeleteMultipleEntries deletes one or more entries from one or more existing boards. func (s *BoardService) DeleteMultipleEntries(BoardIDs []string, entryIDs []string) (*http.Response, error) { bodyJSON := &struct { EntryIds []string `json:"entryIds,omitempty"` }{ EntryIds: entryIDs, } apiError := new(APIError) resp, err := s.sling.New().Delete("tags/"+url.PathEscape(strings.Join(BoardIDs, ","))).BodyJSON(bodyJSON).Receive(nil, apiError) return resp, relevantError(err, apiError) } // BoardDetailResponse represents the response from BoardService.Details. type BoardDetailResponse struct { Boards []Board `json:"boards"` UnmappedFields map[string]interface{} `json:"-" mapstructure:",remain"` } // Details returns details about a board. func (s *BoardService) Details(boardID string) (*BoardDetailResponse, *http.Response, error) { encodedResponse := make([]map[string]interface{}, 0) decodedResponse := new(BoardDetailResponse) apiError := new(APIError) resp, err := s.sling.New().Get("boards/"+url.PathEscape(boardID)).Receive(&encodedResponse, apiError) if err := relevantError(err, apiError); err != nil { return nil, resp, err } if err := mapstructure.Decode(encodedResponse, &decodedResponse.Boards); err != nil { return nil, resp, err } return decodedResponse, resp, nil } // BoardListOptionalParams are the optional parameters for BoardService.List. type BoardListOptionalParams struct { WithEnterprise *bool `url:"withEnterprise,omitempty"` } // BoardListResponse represents the response from BoardService.List. type BoardListResponse struct { Boards []Board `json:"boards"` UnmappedFields map[string]interface{} `json:"-" mapstructure:",remain"` } // List returns the list of boards. func (s *BoardService) List(optionalParams *BoardListOptionalParams) (*BoardListResponse, *http.Response, error) { if optionalParams == nil { optionalParams = &BoardListOptionalParams{} } encodedResponse := make([]map[string]interface{}, 0) decodedResponse := new(BoardListResponse) apiError := new(APIError) resp, err := s.sling.New().Get("boards").QueryStruct(optionalParams).Receive(&encodedResponse, apiError) if err := relevantError(err, apiError); err != nil { return nil, resp, err } if err := mapstructure.Decode(encodedResponse, &decodedResponse.Boards); err != nil { return nil, resp, err } return decodedResponse, resp, nil } // BoardUpdateOptionalParams are the optional parameters for BoardService.Update. type BoardUpdateOptionalParams struct { DeleteCover *bool `json:"deleteCover,omitempty"` Description *string `json:"description,omitempty"` IsPublic *bool `json:"isPublic,omitempty"` Label *string `json:"label,omitempty"` ShowHighlights *bool `json:"showHighlights,omitempty"` ShowNotes *bool `json:"showNotes,omitempty"` } // BoardUpdateResponse represents the response from BoardService.Update. type BoardUpdateResponse struct { Boards []Board `json:"boards"` UnmappedFields map[string]interface{} `json:"-" mapstructure:",remain"` } // Update updates an existing board. func (s *BoardService) Update(boardID string, optionalParams *BoardUpdateOptionalParams) (*BoardUpdateResponse, *http.Response, error) { if optionalParams == nil { optionalParams = &BoardUpdateOptionalParams{} } bodyJSON := &struct { *BoardUpdateOptionalParams ID string `json:"id"` }{ BoardUpdateOptionalParams: optionalParams, ID: boardID, } encodedResponse := make([]map[string]interface{}, 0) decodedResponse := new(BoardUpdateResponse) apiError := new(APIError) resp, err := s.sling.New().Post("boards").BodyJSON(bodyJSON).Receive(&encodedResponse, apiError) if err := relevantError(err, apiError); err != nil { return nil, resp, err } if err := mapstructure.Decode(encodedResponse, &decodedResponse.Boards); err != nil { return nil, resp, err } return decodedResponse, resp, nil } // BoardUploadCoverImageResponse represents the response from BoardService.UploadCoverImage. type BoardUploadCoverImageResponse struct { Boards []Board `json:"boards"` UnmappedFields map[string]interface{} `json:"-" mapstructure:",remain"` } // UploadCoverImage uploads a new cover image for an existing board. func (s *BoardService) UploadCoverImage(boardID string, coverImage io.Reader) (*BoardUploadCoverImageResponse, *http.Response, error) { body, contentType, err := mime.CreateMultipartMIMEAttachment(coverImage) if err != nil { return nil, nil, err } encodedResponse := make([]map[string]interface{}, 0) decodedResponse := new(BoardUploadCoverImageResponse) apiError := new(APIError) resp, err := s.sling.New().Post("boards/"+url.PathEscape(boardID)).Body(body).Set("Content-Type", contentType).Receive(&encodedResponse, apiError) if err := relevantError(err, apiError); err != nil { return nil, resp, err } if err := mapstructure.Decode(encodedResponse, &decodedResponse.Boards); err != nil { return nil, resp, err } return decodedResponse, resp, nil }
true
355533dc054e28028f8d6dfa0207046acd34be4a
Go
NyaaPantsu/manga
/utils/zip/rar.go
UTF-8
1,157
3.046875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package zip import ( "github.com/nwaples/rardecode" "io" "os" "path/filepath" ) // Returns 1 if the file named src has RAR magic bytes func IsRar(src string) bool { f, err := os.Open(src) if err != nil { return false } defer f.Close() buf := make([]byte, 4) _, err = f.Read(buf) if err != nil { return false } return string(buf) == "Rar!" } // Unrar will un-compress a rar archive, // moving all files and folders to an output directory func Unrar(src, dest string) ([]string, error) { var filenames []string rf, err := os.Open(src) if err != nil { return filenames, err } defer rf.Close() r, err := rardecode.NewReader(rf, "") if err != nil { return filenames, err } for { header, err := r.Next() if err == io.EOF { break } else if err != nil { return filenames, err } // Store filename/path for returning and using later on fpath := filepath.Join(dest, header.Name) filenames = append(filenames, fpath) if header.IsDir { os.MkdirAll(fpath, os.ModePerm) } else { err = MakeFile(fpath, r, header.Mode()) if err != nil { return filenames, err } } } return filenames, nil }
true