text
stringlengths 11
4.05M
|
|---|
package slice
func Reduce[I, V any](slice []I, initReduceValue V, f func(reduceValue V, index int, value I) V) (reduceValue V) {
reduceValue = initReduceValue
for i, v := range slice {
reduceValue = f(reduceValue, i, v)
}
return
}
|
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
package main
import "fmt"
// ---------------------------------------------------------
// EXERCISE: Precedence
//
// Change the expressions to produce the expected outputs
//
// RESTRICTION
// Use parentheses to change the precedence
// ---------------------------------------------------------
func main() {
// This expression should print 20
fmt.Println(10 + 5 - 5 - 10)
// This expression should print -16
fmt.Println(-10 + 0.5 - 1 + 5.5)
// This expression should print -25
fmt.Println(5 + 10*2 - 5)
// This expression should print 0.5
fmt.Println(0.5*2 - 1)
// This expression should print 24
fmt.Println(3 + 1/2*10 + 4)
// This expression should print 15
fmt.Println(10 / 2 * 10 % 7)
// This expression should print 40
// Note that you may need to use floats to solve this
fmt.Println(100 / 5 / 2)
}
|
package iris
import (
"fmt"
"github.com/midtrans/midtrans-go"
assert "github.com/stretchr/testify/require"
"math/rand"
"strconv"
"testing"
"time"
)
var irisCreatorKeySandbox = "IRIS-330198f0-e49d-493f-baae-585cfded355d"
var irisApproverKeySandbox = "IRIS-1595c12b-6814-4e5a-bbbb-9bc18193f47b"
func random() string {
rand.Seed(time.Now().UnixNano())
return strconv.Itoa(rand.Intn(2000-1000) + 100000)
}
func generateDate() (string, string) {
t := time.Now()
var fromDate = t.AddDate(0, -1, 0).Format("2006-01-02")
var toDate = t.Format("2006-01-02")
return fromDate, toDate
}
func mockBeneficiaries() Beneficiaries {
var random = random()
return Beneficiaries{
Name: "MidGoUnitTest" + random,
Account: random,
Bank: "bca",
AliasName: "midgotest" + random,
Email: "midgo" + random + "@mail.com",
}
}
func TestGetBalance(t *testing.T) {
var iris = Client{}
iris.New(irisCreatorKeySandbox, midtrans.Sandbox)
resp2, err2 := iris.GetBalance()
assert.Nil(t, err2)
assert.NotNil(t, resp2)
}
func TestCreateAndUpdateBeneficiaries(t *testing.T) {
iris := Client{}
iris.New(irisCreatorKeySandbox, midtrans.Sandbox)
newBeneficiaries := mockBeneficiaries()
resp1, err1 := iris.CreateBeneficiaries(newBeneficiaries)
assert.Nil(t, err1)
assert.Equal(t, resp1.Status, "created")
getListAndUpdateBeneficiaries(t, newBeneficiaries)
}
func getListAndUpdateBeneficiaries(t *testing.T, beneficiaries Beneficiaries) {
iris := Client{}
iris.New(irisCreatorKeySandbox, midtrans.Sandbox)
beneficiariesList, _ := iris.GetBeneficiaries()
b := Beneficiaries{}
for _, account := range beneficiariesList {
if account.AliasName == beneficiaries.AliasName {
b = account
break
}
}
updateBeneficiaries := Beneficiaries{
Name: b.Name,
Account: b.Account,
Bank: b.Bank,
AliasName: b.AliasName + "edt",
Email: b.Email,
}
resp, _ := iris.UpdateBeneficiaries(b.AliasName, updateBeneficiaries)
assert.Equal(t, resp.Status, "updated")
}
func createPayout() []CreatePayoutDetailResponse {
p := CreatePayoutDetailReq{
BeneficiaryName: "Tony Stark",
BeneficiaryAccount: "1380011819286",
BeneficiaryBank: "mandiri",
BeneficiaryEmail: "tony.stark@mail.com",
Amount: random(),
Notes: "MidGoUnitTestApproved",
}
var payouts []CreatePayoutDetailReq
payouts = append(payouts, p)
cp := CreatePayoutReq{Payouts: payouts}
iris := Client{}
iris.New(irisCreatorKeySandbox, midtrans.Sandbox)
payoutReps, err := iris.CreatePayout(cp)
fmt.Println(payoutReps, err)
return payoutReps.Payouts
}
func getPayoutDetails(refNo string) string {
iris := Client{}
iris.New(irisCreatorKeySandbox, midtrans.Sandbox)
payoutReps, err := iris.GetPayoutDetails(refNo)
fmt.Println(payoutReps, err)
return payoutReps.ReferenceNo
}
func TestCreateAndApprovePayout(t *testing.T) {
var payouts = createPayout()
assert.Equal(t, payouts[0].Status, "queued")
var refNos []string
refNos = append(refNos, payouts[0].ReferenceNo)
ap := ApprovePayoutReq{
ReferenceNo: refNos,
OTP: "335163",
}
iris := Client{}
iris.New(irisApproverKeySandbox, midtrans.Sandbox)
approveResp, err2 := iris.ApprovePayout(ap)
assert.Nil(t, err2)
assert.Equal(t, approveResp.Status, "ok")
assert.Equal(t, getPayoutDetails(payouts[0].ReferenceNo), payouts[0].ReferenceNo)
}
func TestCreateAndRejectPayout(t *testing.T) {
var payouts = createPayout()
assert.Equal(t, payouts[0].Status, "queued")
var refNos []string
refNos = append(refNos, payouts[0].ReferenceNo)
ap := RejectPayoutReq{
ReferenceNo: refNos,
RejectReason: "MidGoUnitTest",
}
iris := Client{}
iris.New(irisApproverKeySandbox, midtrans.Sandbox)
approveResp, err2 := iris.RejectPayout(ap)
assert.Nil(t, err2)
assert.Equal(t, approveResp.Status, "ok")
}
func TestPayoutHistory(t *testing.T) {
fromDate, toDate := generateDate()
iris := Client{}
iris.New(irisApproverKeySandbox, midtrans.Sandbox)
resp, err := iris.GetTransactionHistory(fromDate, toDate)
assert.Nil(t, err)
assert.NotNil(t, resp)
}
func TestGetTopUpChannels(t *testing.T) {
iris := Client{}
iris.New(irisApproverKeySandbox, midtrans.Sandbox)
resp, err := iris.GetTopUpChannels()
assert.Nil(t, err)
assert.NotNil(t, resp)
}
func TestGetListBeneficiaryBank(t *testing.T) {
iris := Client{}
iris.New(irisApproverKeySandbox, midtrans.Sandbox)
resp, err := iris.GetBeneficiaryBanks()
assert.Nil(t, err)
assert.NotNil(t, resp)
}
func TestValidateBankAccount(t *testing.T) {
iris := Client{}
iris.New(irisApproverKeySandbox, midtrans.Sandbox)
resp, err := iris.ValidateBankAccount("mandiri", "1111222233333")
assert.Nil(t, err)
assert.Equal(t, resp.AccountNo, "1111222233333")
}
func TestCreatePayoutFail(t *testing.T) {
iris := Client{}
iris.New(irisCreatorKeySandbox, midtrans.Sandbox)
p1 := CreatePayoutDetailReq{
BeneficiaryAccount: "1380011819286",
BeneficiaryBank: "mandiri",
BeneficiaryEmail: "tony.stark@mail.com",
Amount: random(),
Notes: "MidGoUnitTest",
}
p2 := CreatePayoutDetailReq{
BeneficiaryAccount: "1380011819286",
BeneficiaryBank: "mandiri",
BeneficiaryEmail: "jon.snow@mail.com",
Amount: random(),
Notes: "MidGoUnitTest",
}
var payouts []CreatePayoutDetailReq
payouts = append(payouts, p1)
payouts = append(payouts, p2)
cp := CreatePayoutReq{Payouts: payouts}
payoutReps, err := iris.CreatePayout(cp)
assert.NotNil(t, payoutReps)
assert.NotNil(t, err)
assert.Equal(t, "An error occurred when creating payouts", payoutReps.ErrorMessage)
}
|
package fakes
import (
"fmt"
"net/http"
"github.com/cloudfoundry-incubator/notifications/cf"
)
type CloudController struct {
CurrentToken string
GetUsersBySpaceGuidError error
GetUsersByOrganizationGuidError error
LoadSpaceError error
LoadOrganizationError error
UsersBySpaceGuid map[string][]cf.CloudControllerUser
UsersByOrganizationGuid map[string][]cf.CloudControllerUser
Spaces map[string]cf.CloudControllerSpace
Orgs map[string]cf.CloudControllerOrganization
}
func NewCloudController() *CloudController {
return &CloudController{
UsersBySpaceGuid: make(map[string][]cf.CloudControllerUser),
UsersByOrganizationGuid: make(map[string][]cf.CloudControllerUser),
}
}
func (fake *CloudController) GetUsersBySpaceGuid(guid, token string) ([]cf.CloudControllerUser, error) {
fake.CurrentToken = token
if users, ok := fake.UsersBySpaceGuid[guid]; ok {
return users, fake.GetUsersBySpaceGuidError
} else {
return make([]cf.CloudControllerUser, 0), fake.GetUsersBySpaceGuidError
}
}
func (fake *CloudController) GetUsersByOrgGuid(guid, token string) ([]cf.CloudControllerUser, error) {
fake.CurrentToken = token
if users, ok := fake.UsersByOrganizationGuid[guid]; ok {
return users, fake.GetUsersByOrganizationGuidError
} else {
return make([]cf.CloudControllerUser, 0), fake.GetUsersByOrganizationGuidError
}
}
func (fake *CloudController) LoadSpace(guid, token string) (cf.CloudControllerSpace, error) {
if fake.LoadSpaceError != nil {
return cf.CloudControllerSpace{}, fake.LoadSpaceError
}
if space, ok := fake.Spaces[guid]; ok {
return space, nil
} else {
return cf.CloudControllerSpace{}, cf.NewFailure(http.StatusNotFound, fmt.Sprintf(`{"code":40004,"description":"The app space could not be found: %s","error_code":"CF-SpaceNotFound"}`, guid))
}
}
func (fake *CloudController) LoadOrganization(guid, token string) (cf.CloudControllerOrganization, error) {
if fake.LoadOrganizationError != nil {
return cf.CloudControllerOrganization{}, fake.LoadOrganizationError
}
if org, ok := fake.Orgs[guid]; ok {
return org, nil
} else {
return cf.CloudControllerOrganization{}, cf.NewFailure(http.StatusNotFound, fmt.Sprintf(`{"code":30003,"description":"The organization could not be found: %s","error_code":"CF-OrganizationNotFound"}`, guid))
}
}
|
package services
// import (
// "errors"
// "time"
// "github.com/dgrijalva/jwt-go"
// )
// // Set our secret.
// // TODO: Use generated key from README
// var mySigningKey = []byte("secret")
// // Token defines a token for our application
// type Token string
// // TokenService provides a token
// type TokenService interface {
// Get(u *User) (string, error)
// }
// type tokenService struct {
// UserService services.userService
// }
// // CustomClaims type holds the token claims
// type CustomClaims struct {
// Admin bool `json:"admin"`
// User *User `json:"user"`
// jwt.StandardClaims
// }
// // NewTokenService creates a new UserService
// func NewTokenService() TokenService {
// return &tokenService{}
// }
// // Get retrieves a token for a user
// // TODO: Take login credentials and verify them against what's in database
// func (s *tokenService) Get(u *User) (string, error) {
// // Try to log in the user
// user, err := s.UserService.Read(u.ID)
// if err != nil {
// return "", errors.New("Failed to retrieve user")
// }
// if user == nil {
// return "", errors.New("Failed to retrieve user")
// }
// claims := CustomClaims{
// Admin: true,
// User: u,
// StandardClaims: jwt.StandardClaims{
// ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
// Issuer: "test",
// },
// }
// token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// // Sign token with key
// tokenString, err := token.SignedString(mySigningKey)
// if err != nil {
// return "", errors.New("Failed to sign token")
// }
// return tokenString, nil
// }
|
package pubsub
import (
"context"
"errors"
"fmt"
"sync"
"github.com/siatris/go-pubsub-ws/pkg/websocket"
"github.com/go-redis/redis/v8"
)
type Middleware func(websocket.WSMessage) websocket.WSMessage
type Subscription interface {
Subscriber() websocket.WSConn
Use(Middleware)
Namespaces() []string
Handle(websocket.WSMessage) websocket.WSMessage
ReceiveMessage(ctx context.Context) (websocket.WSMessage, error)
}
type subscription struct {
conn websocket.WSConn
namespaces []string
middlewares []Middleware
sub *redis.PubSub
sync.RWMutex
}
func (s *subscription) ReceiveMessage(ctx context.Context) (websocket.WSMessage, error) {
msgi, err := s.sub.Receive(ctx)
if err != nil {
return nil, err
}
switch msg := msgi.(type) {
case *redis.Message:
return websocket.NewMessage(s.conn, msg.Channel, msg.Payload), nil
case *redis.Subscription:
return websocket.NewMessage(s.conn, fmt.Sprintf(SUBSCRIBED_TYPE, msg.Channel), msg), nil
default:
return nil, errors.New("Invalid message")
}
}
func (s *subscription) Subscriber() websocket.WSConn {
return s.conn
}
func (s *subscription) Namespaces() []string {
s.RLock()
defer s.RUnlock()
return s.namespaces
}
func (s *subscription) Use(middleware Middleware) {
s.Lock()
defer s.Unlock()
s.middlewares = append(s.middlewares, middleware)
}
func (s *subscription) Handle(msg websocket.WSMessage) websocket.WSMessage {
var m websocket.WSMessage = msg
for _, middleware := range s.middlewares {
m = middleware(m)
}
return m
}
|
package main
import (
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
)
func simple_deadlock() {
c := make(chan bool)
// c <- true // fatal error: all goroutines are asleep - deadlock! --> goroutine 1 [chan send]:
<-c // fatal error: all goroutines are asleep - deadlock! --> goroutine 1 [chan receive]:
// mengapa ini terjadi,
// yap dikarenakan tidak ada sinyal yang dikirimkan(send)
// tiba2 saja melakukan penerimaan(receive)
// deadlock-chan receive; terjadi karena utas yang dibuat dan aktif lebih banyak
// daripada yang semestinya mengantri
// INTINYA --> tidak ada yang mengantri; sedangkan utas dipaksa dibuat dan dipaksa aktif
// secara dasar, program membutuhkan 3 utas, namun;
// pada waktu yang sama, ketika deadlock terdeteksi, maka 4 utas akan dibuat;
// 1. untuk go-routine, berjalannya program inti
// 2. untuk monitoring system; `sysmon`
// 3. untuk garbage collector, yang dijalankan oleh go-routine program inti
// 4. yang terakhir dibuat ketika go-routine program utama/inti diblockir selama inisialisasi
// maka ketika ini terjadi, go membuat utas baru(time-up) untuk rutin yang lain
// setiap utas terjadi idle, detektor akan dinotis. deadlock terjadi ketika nilai utas idle sama dengan
// banyaknya utas yang aktif dikurangi dengan jumlah utas yang dimiliki sistem.
// INTINYA --> keseluruhan proses membutuhkan 4 utas, dan sistem-sendiri menggunakan 4 utas
// 4utas proses - 4 utas sistem = 0 utas(habis/null)
// disisi lain, deadlock terjadi karena utas aktif berjumlah keseluruhan 3,
// disaat yang sama ketiga utas itu mengalami idle, hingga tejadilah buntu
// NB. Perlu diingat, perilaku ini tetap memiliki batasan, setiap utas akan diusahakan aktif
// sehingga kerapkali hal ini membuat deteksi deadlock
// tidak begitu berguna pada rutin yang tengah bekerja
}
func advance_deadlock() {
// Praktik baru, dengan melakukan improvisasi dengan menanamkan `sinyal berhenti`
// bila `sinyal interupsi` dikirimkan(send)
s := make(chan os.Signal, 1) //same or equal as `c chan <- os.Signal`
// semua akan berjalan baik
// tapi ketika mendapat "syscall.SIGINT(for interupt)" maka akan dilakukan "syscall.SIGTERM(for terminate)"
// `cause package signal to relay "incoming signal" to "chan of os.signal"`
// pengalihan interaksi(relay) sinyal dari behaviour syscall.SIGINT kepada syscall.SIGTERM
signal.Notify(s, syscall.SIGINT, syscall.SIGKILL)
// inspeksi --> signal.Notify(s, syscall.SIGINT, `what_will_do`)
// ./main.go:55:35: cannot use what_will_do (type what_will_do_Type) as type os.Signal in argument to signal.Notify:
// int does not implement os.Signal (missing Signal method)
// membuat channel baru
c := make(chan bool)
select {
case <-c: // menjalankan channel c --> mengelola/menerima sinyal(receive)
// ketika menjalankan channel c berlangsung, sebenarnya program mengalami deadlock
case <-s: // menjalankan sinyal s --> mengelola/menerima sinyal(receive)
// tidak jadi deadlock karena,
// masih ada utas aktif dan berlangsung, yaitu rutin oleh `channel s`
// rutin ini berjalan dengan menunggu pengiriman sinyal(send) oleh interaksi syscall.SIGINT
println("program stopped")
// ketika sinyal dari `channel s` terpenuhi (syscall.SIGINT)
// println("program stopped") // atau turunan dari blok `case <-s:` akan dijalankan scr tuntas
}
println("keluar\n")
// ketika interaksi sinyal.SIGINT dijalankan maka akan mendapat/menerima sinyal(receive) yang sebenarnya
// hingga program tidak benar-benar mengalami deadlock
// program diselesaikan hingga baris terakhir
// dan diteruskan dengan melakukan perintah syscall.SIGKILL
// perintah ini dijalankan oleh utas yang mengerjakan `signal.Notify(...` pada baris ke 56
// yaitu utas `s :=...` sebagai pengelola kongkuren rutin teratas
}
func deadlock_with_debuging() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
time.Sleep(5 * time.Second)
c := make(chan bool)
<-c
}
func checkCh() {
ch := make(chan int)
go func() {
select {
case <-ch:
log.Printf("1.channel")
default:
log.Printf("1.default")
}
select {
case <-ch:
log.Printf("2.channel")
}
close(ch)
select {
case <-ch:
log.Printf("3.channel")
default:
log.Printf("3.default")
}
}()
time.Sleep(time.Second)
ch <- 1
time.Sleep(time.Second)
}
func main() {
// PENGENALAN / SIMPLE DEADLOCK
// UNCOMMENT CODE BELLOW TO SEE ALL DESCRIPTION BEHAVIOUR
// simple_deadlock()
// DEADLOCK DENGAN PENJELASAN MENDALAM DAN PENANGANANNYA
// UNCOMMENT CODE BELLOW TO SEE ALL DESCRIPTION BEHAVIOUR
// advance_deadlock()
// saatnya melakukan pengamatan lebih dalam !!
// deadlock_with_debuging()
// https://golang.org/pkg/net/http/pprof/
// wget -O trace.out http://localhost:6060/debug/pprof/trace?seconds=5
// go tool trace trace.out
// checkCh()
}
|
package main
import "fmt"
func main() {
fmt.Println(maxSumTwoNoOverlap([]int{
2, 1, 5, 6, 0, 9, 5, 0, 3, 8,
}, 4, 2))
}
// 0,6,5,2,2,5,1,9,4
func maxSumTwoNoOverlap(nums []int, firstLen int, secondLen int) int {
n := len(nums)
max := func(a, b int) int {
if a > b {
return a
}
return b
}
s := make([]int, n+1)
for i, v := range nums {
s[i+1] = s[i] + v
}
f := func(firstLen, secondLen int) int {
var ans int
maxSumA := 0
for i := firstLen + secondLen; i <= n; i++ {
maxSumA = max(maxSumA, s[i-secondLen]-s[i-secondLen-firstLen]) // s[i-secondLen]-s[i-secondLen-firstLen] 为 a 数组的和
ans = max(ans, maxSumA+s[i]-s[i-secondLen]) // 为 s[i]-s[i-secondLen] 为b 数组的和
}
return ans
}
return max(
f(firstLen, secondLen),
f(secondLen, firstLen),
)
}
|
package server
import (
"fmt"
"net/http"
)
type RequestHandler func(http.ResponseWriter, *http.Request) bool
type RequestBroker struct {
Routers map[string][]RequestHandler
HttpMethodNotSupported RequestHandler
NoRouterServedRequest RequestHandler
}
func (r *RequestBroker) serveOrRejectWithRouters(
routers []RequestHandler, w http.ResponseWriter, req *http.Request) bool {
for _, router := range routers {
requestServed := router(w, req)
if requestServed {
return true
}
}
return false
}
func (r *RequestBroker) Resolve(w http.ResponseWriter, req *http.Request) {
routers, ok := r.Routers[req.Method]
if ok {
requestServed := r.serveOrRejectWithRouters(routers, w, req)
if !requestServed {
r.NoRouterServedRequest(w, req)
}
} else {
r.HttpMethodNotSupported(w, req)
}
}
func DefaultHandleUnsupportedHttpMethod(
w http.ResponseWriter, req *http.Request) bool {
fmt.Fprintf(w, "nope\nThis http method is unsupported: %s", req.Method)
return true
}
func DefaultHandleNoRouterServedRequest(
w http.ResponseWriter, req *http.Request) bool {
fmt.Fprintf(w, "nope\nNone of handlers served request!")
return true
}
func NewRequestBroker(routers map[string][]RequestHandler) *RequestBroker {
return &RequestBroker{
routers,
DefaultHandleUnsupportedHttpMethod,
DefaultHandleNoRouterServedRequest}
}
|
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"sync"
"github.com/amenzhinsky/iothub/cmd/internal"
"github.com/amenzhinsky/iothub/iotdevice"
"github.com/amenzhinsky/iothub/iotdevice/transport"
"github.com/amenzhinsky/iothub/iotdevice/transport/mqtt"
)
var transports = map[string]func() (transport.Transport, error){
"mqtt": func() (transport.Transport, error) {
return mqtt.New(), nil
},
"amqp": func() (transport.Transport, error) {
return nil, errors.New("not implemented")
},
"http": func() (transport.Transport, error) {
return nil, errors.New("not implemented")
},
}
var (
debugFlag bool
compressFlag bool
quiteFlag bool
transportFlag string
midFlag string
cidFlag string
qosFlag int
// x509 flags
tlsCertFlag string
tlsKeyFlag string
deviceIDFlag string
hostnameFlag string
)
func main() {
if err := run(); err != nil {
if err != internal.ErrInvalidUsage {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
}
os.Exit(1)
}
}
const help = `iothub-device helps iothub devices to communicate with the cloud.
$IOTHUB_DEVICE_CONNECTION_STRING environment variable is required unless you use x509 authentication.`
func run() error {
cli, err := internal.New(help, func(f *flag.FlagSet) {
f.BoolVar(&debugFlag, "debug", false, "enable debug mode")
f.BoolVar(&compressFlag, "compress", false, "compress data (remove JSON indentations)")
f.StringVar(&transportFlag, "transport", "mqtt", "transport to use <mqtt|amqp|http>")
f.StringVar(&tlsCertFlag, "tls-cert", "", "path to x509 cert file")
f.StringVar(&tlsKeyFlag, "tls-key", "", "path to x509 key file")
f.StringVar(&deviceIDFlag, "device-id", "", "device id, required for x509")
f.StringVar(&hostnameFlag, "hostname", "", "hostname to connect to, required for x509")
}, []*internal.Command{
{
Name: "send",
Alias: "s",
Help: "PAYLOAD [KEY VALUE]...",
Desc: "send a message to the cloud (D2C)",
Handler: wrap(send),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&midFlag, "mid", "", "identifier for the message")
f.StringVar(&cidFlag, "cid", "", "message identifier in a request-reply")
f.IntVar(&qosFlag, "qos", mqtt.DefaultQoS, "QoS value, 0 or 1 (mqtt only)")
},
},
{
Name: "watch-events",
Alias: "we",
Desc: "subscribe to messages sent from the cloud (C2D)",
Handler: wrap(watchEvents),
},
{
Name: "watch-twin",
Alias: "wt",
Desc: "subscribe to desired twin state updates",
Handler: wrap(watchTwin),
},
{
Name: "direct-method",
Alias: "dm",
Help: "NAME",
Desc: "handle the named direct method, reads responses from STDIN",
Handler: wrap(directMethod),
ParseFunc: func(f *flag.FlagSet) {
f.BoolVar(&quiteFlag, "quite", false, "disable additional hints")
},
},
{
Name: "twin-state",
Alias: "ts",
Desc: "retrieve desired and reported states",
Handler: wrap(twin),
},
{
Name: "update-twin",
Alias: "ut",
Help: "[KEY VALUE]...",
Desc: "updates the twin device deported state, null means delete the key",
Handler: wrap(updateTwin),
},
})
if err != nil {
return err
}
return cli.Run(context.Background(), os.Args...)
}
func wrap(fn func(context.Context, *flag.FlagSet, *iotdevice.Client) error) internal.HandlerFunc {
return func(ctx context.Context, f *flag.FlagSet) error {
mk, ok := transports[transportFlag]
if !ok {
return fmt.Errorf("unknown transport %q", transportFlag)
}
t, err := mk()
if err != nil {
return err
}
opts := []iotdevice.ClientOption{iotdevice.WithTransport(t)}
if tlsCertFlag != "" && tlsKeyFlag != "" {
if hostnameFlag == "" {
return errors.New("hostname is required for x509 authentication")
}
if deviceIDFlag == "" {
return errors.New("device-id is required for x509 authentication")
}
opts = append(opts,
iotdevice.WithX509FromFile(deviceIDFlag, hostnameFlag, tlsCertFlag, tlsKeyFlag),
)
}
c, err := iotdevice.New(opts...)
if err != nil {
return err
}
if err := c.Connect(ctx); err != nil {
return err
}
return fn(ctx, f, c)
}
}
func send(ctx context.Context, f *flag.FlagSet, c *iotdevice.Client) error {
if f.NArg() < 1 {
return internal.ErrInvalidUsage
}
var props map[string]string
if f.NArg() > 1 {
var err error
props, err = internal.ArgsToMap(f.Args()[1:])
if err != nil {
return err
}
}
return c.SendEvent(ctx, []byte(f.Arg(0)),
iotdevice.WithSendProperties(props),
iotdevice.WithSendMessageID(midFlag),
iotdevice.WithSendCorrelationID(cidFlag),
iotdevice.WithSendQoS(qosFlag),
)
}
func watchEvents(ctx context.Context, f *flag.FlagSet, c *iotdevice.Client) error {
if f.NArg() != 0 {
return internal.ErrInvalidUsage
}
sub, err := c.SubscribeEvents(ctx)
if err != nil {
return err
}
for msg := range sub.C() {
if err = internal.OutputJSON(msg, compressFlag); err != nil {
return err
}
}
return sub.Err()
}
func watchTwin(ctx context.Context, f *flag.FlagSet, c *iotdevice.Client) error {
if f.NArg() != 0 {
return internal.ErrInvalidUsage
}
sub, err := c.SubscribeTwinUpdates(ctx)
if err != nil {
return err
}
for twin := range sub.C() {
if err = internal.OutputJSON(twin, compressFlag); err != nil {
return err
}
}
return sub.Err()
}
func directMethod(ctx context.Context, f *flag.FlagSet, c *iotdevice.Client) error {
if f.NArg() != 1 {
return internal.ErrInvalidUsage
}
// if an error occurs during the method invocation,
// immediately return and display the error.
errc := make(chan error, 1)
in := bufio.NewReader(os.Stdin)
mu := &sync.Mutex{}
if err := c.RegisterMethod(ctx, f.Arg(0),
func(p map[string]interface{}) (map[string]interface{}, error) {
mu.Lock()
defer mu.Unlock()
b, err := json.Marshal(p)
if err != nil {
errc <- err
return nil, err
}
if quiteFlag {
fmt.Println(string(b))
} else {
fmt.Printf("Payload: %s\n", string(b))
fmt.Printf("Enter json response: ")
}
b, _, err = in.ReadLine()
if err != nil {
errc <- err
return nil, err
}
var v map[string]interface{}
if err = json.Unmarshal(b, &v); err != nil {
errc <- errors.New("unable to parse json input")
return nil, err
}
return v, nil
}); err != nil {
return err
}
return <-errc
}
func twin(ctx context.Context, _ *flag.FlagSet, c *iotdevice.Client) error {
desired, reported, err := c.RetrieveTwinState(ctx)
if err != nil {
return err
}
b, err := json.Marshal(desired)
if err != nil {
return err
}
fmt.Println("desired: " + string(b))
b, err = json.Marshal(reported)
if err != nil {
return err
}
fmt.Println("reported: " + string(b))
return nil
}
func updateTwin(ctx context.Context, f *flag.FlagSet, c *iotdevice.Client) error {
if f.NArg() == 0 {
return internal.ErrInvalidUsage
}
s, err := internal.ArgsToMap(f.Args())
if err != nil {
return err
}
m := make(iotdevice.TwinState, len(s))
for k, v := range s {
if v == "null" {
m[k] = nil
} else {
m[k] = v
}
}
ver, err := c.UpdateTwinState(ctx, m)
if err != nil {
return err
}
fmt.Printf("version: %d\n", ver)
return nil
}
|
package benchmark
/*
func Test_Use_reflectvalue_deepcopy(t *testing.T) {
dst := testDataDst{}
deepcopy.Copy(&dst, &td).Do()
assert.Equal(t, td, dst)
dst.Slice[0] = "aaa"
fmt.Println("deepcopy:", td.Slice)
}
func Test_Use_Ptr_coven(t *testing.T) {
c, err := coven.NewConverter(testDataDst{}, testDataSrc{})
assert.NoError(t, err)
dst := testDataDst{}
c.Convert(&dst, &td)
assert.Equal(t, td, dst)
// coven并不是一个深度拷贝库
// 修改dst里面的数据, td里面的slice数据也跟着被改变
dst.Slice[0] = "aaa"
fmt.Println("coven:", td.Slice)
}
// 看下coven是如何处理指针变量的
// 结论coven只是拷贝指针地址
func Test_Use_Ptr_coven_Cycle(t *testing.T) {
type Ring struct {
R *Ring
}
c, err := coven.NewConverter(Ring{}, Ring{})
assert.NoError(t, err)
R := Ring{}
R.R = &R
r2 := Ring{}
err = c.Convert(&r2, &R)
fmt.Printf("%p\n", R.R)
fmt.Printf("%p\n", r2.R)
}
*/
|
package main
import f "fmt"
func main() {
a := make(map[string]int)
a["age"] = 27
a["height"] = 175
f.Println(a)
b := map[string]float64{
"pi": 3.141592,
"sqrt2": 1.41421356,
}
f.Println(b["pi"], b["sqrt2"])
f.Println("-------------------")
capacityUnit := make(map[string]string)
capacityUnit["1byte"] = "1024 bit"
capacityUnit["1MB"] = "1024 Byte"
capacityUnit["1GB"] = "1024 MB"
capacityUnit["1TB"] = "1024 GB"
capacityUnit["1PB"] = "1024 TB"
value, ok := capacityUnit["1YB"]
f.Println(value, ok)
if result, ok := capacityUnit["1GB"]; ok {
f.Println(result, ok)
}
f.Println("-------------------")
for key, result := range capacityUnit {
f.Println(key, " : ", result)
}
f.Println("-------------------")
for _, result := range capacityUnit {
f.Println(result)
}
delete(capacityUnit, "1PB")
f.Println(capacityUnit)
}
|
package p_test
import (
"testing"
pp "github.com/Kretech/xgo/p"
"github.com/Kretech/xgo/test"
)
func TestArgsNameWithAlias(t *testing.T) {
as := test.A(t)
a := 3
b := 4
a1 := pp.VarName(a, b)
as.Equal(a1, []string{`a`, `b`})
}
|
package dep
import "testing"
func TestListen(t *testing.T) {
// todo
}
|
package memrepo
import (
"github.com/scjalliance/drivestream/commit"
"github.com/scjalliance/drivestream/resource"
)
// FileEntry holds version history for a file.
type FileEntry struct {
Versions map[resource.Version]resource.FileData
Views map[resource.ID]map[commit.SeqNum]resource.Version
}
func newFileEntry() FileEntry {
return FileEntry{
Versions: make(map[resource.Version]resource.FileData),
Views: make(map[resource.ID]map[commit.SeqNum]resource.Version),
}
}
|
package domain
const (
// Title Errors
TaskErrorTitleEmptyCode = iota
// Invalid Task ID Error
TaskErrorIDInvalidCode
// Description Errors
TaskErrorDescriptionEmptyCode
// Date Errors
TaskErrorDueDateEmptyCode
TaskErrorDueDateInvalidCode
// Priority Errors
TaskErrorPriorityEmptyCode
TaskErrorInvalidPriorityCode
// Status Errors
TaskErrorStatusEmptyCode
TaskErrorInvalidStatusCode
// Domain Errors
TaskErrorDomainEmptyCode
TaskErrorInvalidDomainCode
// Category Errors
TaskErrorCategoryEmptyCode
TaskErrorInvalidCategoryCode
// Parent UID Errors
TaskErrorAssetIDEmptyCode
TaskErrorInvalidAssetIDCode
// Task Domain Errors
TaskErrorInventoryIDEmptyCode
TaskErrorInvalidInventoryIDCode
TaskErrorInvalidAreaIDCode
// Task General Errors
TaskErrorTaskNotFoundCode
)
// TaskError is a custom error from Go built-in error
type TaskError struct {
Code int
}
func (e TaskError) Error() string {
switch e.Code {
case TaskErrorTitleEmptyCode:
return "Task title is required."
case TaskErrorIDInvalidCode:
return "Task ID is invalid."
case TaskErrorDescriptionEmptyCode:
return "Task description is required."
case TaskErrorDueDateEmptyCode:
return "Task due date is required."
case TaskErrorDueDateInvalidCode:
return "Task due date cannot be earlier than the current date."
case TaskErrorPriorityEmptyCode:
return "Task priority is required."
case TaskErrorInvalidPriorityCode:
return "Task priority is invalid."
case TaskErrorStatusEmptyCode:
return "Task status is required."
case TaskErrorInvalidStatusCode:
return "Task status is invalid."
case TaskErrorDomainEmptyCode:
return "Task domain is required."
case TaskErrorInvalidDomainCode:
return "Task domain is invalid."
case TaskErrorCategoryEmptyCode:
return "Task category is required."
case TaskErrorInvalidCategoryCode:
return "Task category is invalid."
case TaskErrorAssetIDEmptyCode:
return "Task must have a referenced asset."
case TaskErrorInvalidAssetIDCode:
return "Task asset reference is invalid."
case TaskErrorInventoryIDEmptyCode:
return "This Task category requires an inventory reference."
case TaskErrorInvalidInventoryIDCode:
return "Task material reference is invalid."
case TaskErrorInvalidAreaIDCode:
return "Task area reference is invalid."
case TaskErrorTaskNotFoundCode:
return "Task not found"
default:
return "Unrecognized Task Error Code"
}
}
|
package handlers
import (
"fmt"
"net/url"
"github.com/authelia/authelia/v4/internal/authentication"
"github.com/authelia/authelia/v4/internal/authorization"
"github.com/authelia/authelia/v4/internal/middlewares"
"github.com/authelia/authelia/v4/internal/session"
"github.com/authelia/authelia/v4/internal/utils"
)
// Handler is the middlewares.RequestHandler for Authz.
func (authz *Authz) Handler(ctx *middlewares.AutheliaCtx) {
var (
object authorization.Object
autheliaURL *url.URL
provider *session.Session
err error
)
if object, err = authz.handleGetObject(ctx); err != nil {
ctx.Logger.WithError(err).Error("Error getting Target URL and Request Method")
ctx.ReplyStatusCode(authz.config.StatusCodeBadRequest)
return
}
if !utils.IsURISecure(object.URL) {
ctx.Logger.Errorf("Target URL '%s' has an insecure scheme '%s', only the 'https' and 'wss' schemes are supported so session cookies can be transmitted securely", object.URL.String(), object.URL.Scheme)
ctx.ReplyStatusCode(authz.config.StatusCodeBadRequest)
return
}
if provider, err = ctx.GetSessionProviderByTargetURL(object.URL); err != nil {
ctx.Logger.WithError(err).WithField("target_url", object.URL.String()).Error("Target URL does not appear to have a relevant session cookies configuration")
ctx.ReplyStatusCode(authz.config.StatusCodeBadRequest)
return
}
if autheliaURL, err = authz.getAutheliaURL(ctx, provider); err != nil {
ctx.Logger.WithError(err).WithField("target_url", object.URL.String()).Error("Error occurred trying to determine the external Authelia URL for Target URL")
ctx.ReplyStatusCode(authz.config.StatusCodeBadRequest)
return
}
var (
authn Authn
strategy AuthnStrategy
)
if authn, strategy, err = authz.authn(ctx, provider); err != nil {
authn.Object = object
ctx.Logger.WithError(err).Error("Error occurred while attempting to authenticate a request")
switch strategy {
case nil:
ctx.ReplyUnauthorized()
default:
strategy.HandleUnauthorized(ctx, &authn, authz.getRedirectionURL(&object, autheliaURL))
}
return
}
authn.Object = object
authn.Method = friendlyMethod(authn.Object.Method)
ruleHasSubject, required := ctx.Providers.Authorizer.GetRequiredLevel(
authorization.Subject{
Username: authn.Details.Username,
Groups: authn.Details.Groups,
IP: ctx.RemoteIP(),
},
object,
)
switch isAuthzResult(authn.Level, required, ruleHasSubject) {
case AuthzResultForbidden:
ctx.Logger.Infof("Access to '%s' is forbidden to user '%s'", object.URL.String(), authn.Username)
ctx.ReplyForbidden()
case AuthzResultUnauthorized:
var handler HandlerAuthzUnauthorized
if strategy != nil {
handler = strategy.HandleUnauthorized
} else {
handler = authz.handleUnauthorized
}
handler(ctx, &authn, authz.getRedirectionURL(&object, autheliaURL))
case AuthzResultAuthorized:
authz.handleAuthorized(ctx, &authn)
}
}
func (authz *Authz) getAutheliaURL(ctx *middlewares.AutheliaCtx, provider *session.Session) (autheliaURL *url.URL, err error) {
if autheliaURL, err = authz.handleGetAutheliaURL(ctx); err != nil {
return nil, err
}
switch {
case authz.implementation == AuthzImplLegacy:
return autheliaURL, nil
case autheliaURL != nil:
switch {
case utils.HasURIDomainSuffix(autheliaURL, provider.Config.Domain):
return autheliaURL, nil
default:
return nil, fmt.Errorf("authelia url '%s' is not valid for detected domain '%s' as the url does not have the domain as a suffix", autheliaURL.String(), provider.Config.Domain)
}
}
if provider.Config.AutheliaURL != nil {
return provider.Config.AutheliaURL, nil
}
return nil, fmt.Errorf("authelia url lookup failed")
}
func (authz *Authz) getRedirectionURL(object *authorization.Object, autheliaURL *url.URL) (redirectionURL *url.URL) {
if autheliaURL == nil {
return nil
}
redirectionURL, _ = url.ParseRequestURI(autheliaURL.String())
if redirectionURL.Path == "" {
redirectionURL.Path = "/"
}
qry := redirectionURL.Query()
qry.Set(queryArgRD, object.URL.String())
if object.Method != "" {
qry.Set(queryArgRM, object.Method)
}
redirectionURL.RawQuery = qry.Encode()
return redirectionURL
}
func (authz *Authz) authn(ctx *middlewares.AutheliaCtx, provider *session.Session) (authn Authn, strategy AuthnStrategy, err error) {
for _, strategy = range authz.strategies {
if authn, err = strategy.Get(ctx, provider); err != nil {
if strategy.CanHandleUnauthorized() {
return Authn{Type: authn.Type, Level: authentication.NotAuthenticated, Username: anonymous}, strategy, err
}
return Authn{Type: authn.Type, Level: authentication.NotAuthenticated, Username: anonymous}, nil, err
}
if authn.Level != authentication.NotAuthenticated {
break
}
}
if strategy.CanHandleUnauthorized() {
return authn, strategy, err
}
return authn, nil, nil
}
|
package game
import (
"encoding/json"
"errors"
"fmt"
)
type ResultType string
const (
Ones ResultType = "ones"
Twos = "twos"
Threes = "threes"
Fours = "fours"
Fives = "fives"
Sixes = "sixes"
ThreeOfAKind = "threeofakind"
FourOfAKind = "fourofakind"
FullHouse = "fullhouse"
SmallStraight = "smallstraight"
Straight = "straight"
Kniffel = "kniffel"
Chance = "chance"
)
var AllResults []ResultType = []ResultType{
Ones,
Twos,
Threes,
Fours,
Fives,
Sixes,
ThreeOfAKind,
FourOfAKind,
FullHouse,
SmallStraight,
Straight,
Kniffel,
Chance,
}
func (rt *ResultType) UnmarshalJSON(b []byte) error {
var s string
json.Unmarshal(b, &s)
inputResultType := ResultType(s)
if err := inputResultType.IsValid(); err != nil {
return err
}
*rt = inputResultType
return nil
}
func (rt *ResultType) IsValid() error {
if findInSlice(rt, AllResults) >= 0 {
return nil
}
return errors.New(fmt.Sprintf("%v is an Invalid Result Type", rt))
}
func findInSlice(search *ResultType, slice []ResultType) int {
for i, rs := range slice {
if rs == *search {
return i
}
}
return -1
}
|
package main
import (
"fmt"
"io/ioutil"
"os"
"encoding/json"
"github.com/buger/jsonparser"
"strings"
"YJparser/yamlparser"
"text/template"
)
type Swagger struct{
SwagVersion string `json:"swagger"`
ObjectsFlag bool
ApiTypeFlag bool
Package string
Paths json.RawMessage
Definitions json.RawMessage
Defs []*Definitionsprops
}
var Swag Swagger
type Definitionsprops struct {
Name string
Usage string
Properties map[string]interface{} `json:"properties"`
Indprop []Property
}
type Property struct {
Name string
Type string `json:"type"`
Format string `json:"format"`
Items interface{} `json:"items"`
Enum interface{} `json:"enums"`
Refs string `json:"$refs"`
AdditionalProperties interface{} `json:additionalProperties`
Default bool `json:"default"`
}
type AdditionalProps struct{
Type string
Refs string
Items interface{}
}
func HandleRefs(aInRefVal string,aInDefName string,usage string) string{
defintion := strings.SplitAfter(aInRefVal, "#/definitions/")
fmt.Println(defintion[1])
def, _, _, _ := jsonparser.Get(Swag.Definitions, defintion[1])
if defintion[1] == aInDefName {
fmt.Println("This will cause loop")
return defintion[1]
}
ParseDefintions(defintion[1],def,defintion[1],usage)
return defintion[1]
}
func ParseDefintions( aInDefintionName string, jsonRawDef []byte, aInMetaTargetName string, usage string){
var vardef Definitionsprops
_ = json.Unmarshal(jsonRawDef, &vardef)
// IF it is first Element, Proceed without checking
if (len(Swag.Defs) > 0) {
for i := range (Swag.Defs){
if aInDefintionName == Swag.Defs[i].Name {
fmt.Println(aInDefintionName,"This defintion already added here")
return
}
}
}
vardef.Name = aInMetaTargetName
vardef.Usage = usage
fmt.Println(vardef)
//v,_,_,_ = jsonparser.Get(swag.Definitions,defintion[1],"properties")
fmt.Println("================================")
for key, val := range vardef.Properties {
lname := key
ltype := val.(map[string]interface{})["type"]
if ltype == nil {
ltype = ""
}
lFormat := val.(map[string]interface{})["format"]
if lFormat == nil {
lFormat = ""
}
lItems := val.(map[string]interface{})["items"]
if lItems != nil {
fmt.Println("lItems:",lItems)
for keyItem,valItem := range (lItems).(map[string]interface{}) {
if keyItem == "type"{
if ltype == "array"{
ltype = "Collection("+valItem.(string)+")"
}else{
ltype = valItem.(string)
}
}
if keyItem == "$ref"{
parsedRefName := HandleRefs(valItem.(string),vardef.Name,vardef.Usage)
if ltype == "array"{
ltype = "Collection("+parsedRefName+")"
}else{
ltype = parsedRefName
}
}
}
}else{
lItems = ""
}
lEnum := val.(map[string]interface{})["enum"]
if lEnum == nil {
lEnum = ""
}
lDefault := val.(map[string]interface{})["default"]
if lDefault == nil {
lDefault = false
}
lRefs := val.(map[string]interface{})["$ref"]
if lRefs != nil {
parsedRefName := HandleRefs(lRefs.(string),vardef.Name,vardef.Usage)
ltype = parsedRefName
}else{
lRefs = ""
}
lAddProps := val.(map[string]interface{})["additionalProperties"]
if lAddProps != nil {
fmt.Println("Add Props:",lAddProps)
var tmpAddType string
for keyItem,valItem := range (lAddProps).(map[string]interface{}) {
if keyItem =="type"{
if valItem.(string) != ""{
tmpAddType = valItem.(string)
}else{
tmpAddType = ""
}
}
if keyItem == "items" {
for k,v := range (valItem).(map[string]interface{}) {
if k == "$ref"{
parsedRefName := HandleRefs(v.(string),vardef.Name,vardef.Usage)
if tmpAddType == "array"{
tmpAddType = "Collection("+parsedRefName+")"
}else{
tmpAddType = parsedRefName
}
}
}
}
if keyItem == "$ref"{
parsedRefName := HandleRefs(valItem.(string),vardef.Name,vardef.Usage)
if tmpAddType == "array"{
tmpAddType = "Collection("+parsedRefName+")"
}else{
tmpAddType =parsedRefName
}
}
}
if ltype == "object"{
ltype = tmpAddType
}
}else {
lAddProps = nil
}
fmt.Println("================================")
fmt.Println("Property Name:", lname)
fmt.Println("Type:", ltype)
fmt.Println("Format:", lFormat)
fmt.Println("Items:", lItems)
fmt.Println("Enum:", lEnum)
fmt.Println("Refs:", lRefs)
fmt.Println("Default:", lDefault)
fmt.Println("lAddProps:", lAddProps)
fmt.Println("================================")
tmpProperty := Property{Name:string(lname), Type:ltype.(string), Format:lFormat.(string), Items:lItems, Enum:lEnum,Refs:lRefs.(string),AdditionalProperties:lAddProps, Default:lDefault.(bool)}
vardef.Indprop = append(vardef.Indprop, tmpProperty)
}
Swag.Defs = append(Swag.Defs,&vardef)
fmt.Println(Swag.Defs)
}
const (
dirFilePerm os.FileMode = 0777
modelDirectory string = "model"
metaDirectory string = "meta/"
projectKey string = "bitbucket-eng-sjc1.cisco.com/an"
)
func loadTemplate(name string) *template.Template {
gopath := os.Getenv("GOPATH")
if gopath == "" {
fmt.Print("Environment variable 'GOPATH' must be set.")
}
fname := name
fmt.Printf("Parsing template '%s'", fname)
t, err := template.ParseFiles(fname)
if err != nil {
fmt.Print("Invalid adgen template : ", err)
}
return t
}
func createDir(name string) {
if _, err := os.Stat(name); os.IsNotExist(err) {
err := os.MkdirAll(name, dirFilePerm)
if err != nil {
fmt.Printf("cannot make dir '%s' : %s", name, err)
}
}
}
func createFile(name string) *os.File {
f, err := os.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, dirFilePerm)
if err != nil {
fmt.Printf("Failed to create file '%s' : %s", name, err.Error())
}
return f
}
func generateModel(mg Swagger){
var t *template.Template
var f *os.File
fmt.Print("Generating Model File")
t = loadTemplate("Model.gotmpl")
createDir("GenModel")
f = createFile("GenModel/ModelGen.yaml")
defer func(f *os.File) {
if err := f.Close(); err != nil {
fmt.Print("Failed to close file: ", err)
}
}(f)
err := t.Execute(f, mg)
if err != nil {
fmt.Print("Error processing template")
}
}
func main() {
filePath := "./swagger_webapp.json";
fmt.Printf( "// reading file %s\n", filePath )
file, err1 := ioutil.ReadFile( filePath )
if _, err := os.Stat(filePath); os.IsNotExist(err) {
fmt.Println("Swagger Specfile doesnt exist:",filePath)
return
}
// parsing Yaml to populate structures
if err1 != nil {
fmt.Printf( "// error while reading file %s\n", filePath )
fmt.Printf("File error: %v\n", err1)
os.Exit(1)
}
err2 := json.Unmarshal(file,&Swag)
fmt.Printf("this is swag value : %s \n",Swag.SwagVersion)
fmt.Println("================================")
meta := yamlparser.Model{}
lMetaExist := yamlparser.ParseYaml(&meta)
if (lMetaExist){
Swag.Package = meta.Package
Swag.ObjectsFlag = false
Swag.ApiTypeFlag = false
fmt.Println(meta)
for i := range meta.Objects {
fmt.Println(string(meta.Objects[i].SourceName))
v, _, _, _ := jsonparser.Get(Swag.Paths, "/" + meta.Objects[i].SourceName, "get", "responses", "200", "schema", "$ref")
if string(v) == "" {
it, _, _, _ := jsonparser.Get(Swag.Paths, "/" + meta.Objects[i].SourceName, "get", "responses", "200", "schema", "type")
if string(it) == "array"{
v, _, _, _ = jsonparser.Get(Swag.Paths, "/" + meta.Objects[i].SourceName, "get", "responses", "200", "schema", "items","$ref")
}
}
fmt.Printf("%s\n", string(v))
fmt.Println("================================")
defintion := strings.SplitAfter(string(v), "#/definitions/")
fmt.Println(defintion[1])
def, _, _, _ := jsonparser.Get(Swag.Definitions, defintion[1])
switch meta.Objects[i].Usage {
case "mo":
Swag.ObjectsFlag = true
case "type":
Swag.ApiTypeFlag = true
}
ParseDefintions(defintion[1],def,meta.Objects[i].TargetName,meta.Objects[i].Usage)
}
generateModel(Swag)
}
fmt.Print(err2)
}
|
// Go program to illustrate
// the concept of Goroutine
package main
import "fmt"
func display(str string) {
for w := 0; w < 6; w++ {
fmt.Println(str)
}
}
func main() {
// Calling Goroutine
go display("Welcome")
// Calling normal function
display("GeeksforGeeks")
}
/*
In the above written program,
We simply create a display() function and then call this function in two
different ways first one is a Goroutine, i.e. go display(“Welcome”)
and another one is a normal function, i.e. display(“GeeksforGeeks”).
But there is a problem, it only displays the result of the normal function
that does not display the result of Goroutine because when a new Goroutine
executed, the Goroutine call return immediately. The control does not wait
for Goroutine to complete their execution just like normal function they always
move forward to the next line after the Goroutine call and ignores the value returned
by the Goroutine.
So, to executes a Goroutine properly, we made some changes in our program
as shown in the below code:
*/
package main
import (
"fmt"
"time"
)
func display(str string) {
for w := 0; w < 6; w++ {
time.Sleep(1 * time.Second)
fmt.Println(str)
}
}
func main() {
// Calling Goroutine
go display("Welcome")
// Calling normal function
display("GeeksforGeeks")
}
/*Output of this program will be
Welcome
GeeksforGeeks
GeeksforGeeks
Welcome
Welcome
GeeksforGeeks
GeeksforGeeks
Welcome
Welcome
GeeksforGeeks
GeeksforGeeks
*/
/*
We added the Sleep() method in our program which makes the
main Goroutine sleeps for 1 second in between 1-second the new
executes, displays “welcome” on the screen, and then terminate after
1-second main Goroutine re-schedule and perform its operation.
This process continues until the value of the w<6 after that the main Goroutine terminates.
Here, both Goroutine and the normal function work concurrently.
*/
|
package main
import "fmt"
func main() {
// n := 2548
y := "browsing under an umbrella"
// fmt.Printf("%x", n)
fmt.Printf("%b", y)
}
|
package controllers
import (
"{{.PackageName}}/helpers"
"{{.PackageName}}/models"
"github.com/labstack/echo"
)
func find{{.ModelName}}ByID(c echo.Context) (*models.{{.ModelName}}, *helpers.ResponseError) {
c.Request().ParseForm()
{{.InstanceName}}, _ := models.FindOne{{.ModelName}}ByID(c.Param("{{.InstanceName | Underscore}}_id"))
if {{.InstanceName}} == nil {
return nil, Err{{.ModelName}}NotFound
}
return {{.InstanceName}}, nil
}
// vi:syntax=go
|
package service
import (
"github.com/goscaffold/logger"
"github.com/goscaffold/snowflake"
micro "github.com/micro/go-micro"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/server"
tracingWrapper "github.com/micro/go-plugins/wrapper/trace/opentracing"
opentracing "github.com/opentracing/opentracing-go"
"log"
"mix/test/config"
"mix/test/utils/dispatcher"
"mix/test/utils/flags"
"mix/test/utils/trace"
)
func (p *Callback) init(serviceFlags *flags.Flags, microService micro.Service) {
p.initNodeId(serviceFlags)
p.initConfig(serviceFlags)
p.initLogger(p.config.Logger)
p.initDispatcher(microService.Client())
p.initSnowflake()
p.initOpenTracing(serviceFlags, microService)
}
func (p *Callback) initNodeId(serviceFlags *flags.Flags) {
p.nodeId = serviceFlags.NodeId
}
func (p *Callback) initConfig(serviceFlags *flags.Flags) {
p.config = InitConfig(serviceFlags)
}
func (p *Callback) initLogger(conf *config.Logger) {
p.logger = logger.NewLogger(&logger.Config{
StdoutWriter: p.config.Logger.GetStdoutWriter(),
FileWriter: p.config.Logger.GetFileWriter(),
LogPath: p.config.Logger.GetLogPath(),
Filename: "callback",
LogLevel: "info",
MaxSize: p.config.Logger.GetMaxSize(),
MaxBackups: p.config.Logger.GetMaxBackups(),
MaxAge: p.config.Logger.GetMaxAge(),
Compress: p.config.Logger.GetCompress(),
})
}
func (p *Callback) initSnowflake() {
var err error
p.snowflake, err = snowflake.DefaultGenerator(p.nodeId)
if err != nil {
log.Fatal("Init snowflake error: ", err)
}
}
func (p *Callback) initDispatcher(cli client.Client) {
p.dispatcher = dispatcher.NewDispatcher(cli)
}
func (p *Callback) initOpenTracing(serviceFlags *flags.Flags, microService micro.Service) {
tracer, closer, err := trace.NewTracer(&trace.Config{
ServiceName: serviceFlags.ServiceName,
JaegerHost: p.config.Tracing.Jaeger.GetHost(),
JaegerPort: p.config.Tracing.Jaeger.GetPort(),
SamplerType: p.config.Tracing.Jaeger.GetSamplerType(),
SamplerParam: p.config.Tracing.Jaeger.GetSamplerParam(),
ReporterLogSpans: p.config.Tracing.Jaeger.GetReporterLogSpans(),
})
if err != nil {
log.Fatal(err)
}
p.tracingCloser = closer
opentracing.SetGlobalTracer(tracer)
err = microService.Server().Init(server.WrapHandler(tracingWrapper.NewHandlerWrapper(opentracing.GlobalTracer())))
if err != nil {
log.Fatal(err)
}
}
|
package main
/*
* @lc app=leetcode.cn id=189 lang=golang
*
* [189] 轮转数组
*/
/*
1. 最基础实现,暴力解
2. 空间复杂度O(1)
3. 时间复杂度O(k * n)
4. 提交最后一个case 超时。说明逻辑没有问题,执行时间需要优化
*/
// @lc code=start
func rotate(nums []int, k int) {
for i := 0; i < k; i++ {
tmp := nums[len(nums)-1]
for j := len(nums) - 2; j > -1; j-- {
nums[j+1] = nums[j]
}
nums[0] = tmp
}
}
// @lc code=end
|
package main
import (
"encoding/base64"
"encoding/json"
"github.com/google/uuid"
"github.com/googollee/go-socket.io"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"golang.org/x/crypto/bcrypt"
_ "golang.org/x/oauth2"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"html/template"
_ "io"
"io/ioutil"
"log"
"net/http"
"os"
_ "strconv"
"strings"
"time"
)
type User struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Username string `bson:"username"`
Firstname string `bson:"firstname"`
Lastname string `bson:"lastname"`
Password string `bson:"password"`
}
type Session struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Username string `bson:"username"`
LastActive int64 `bson:"last_active"`
SessionID string `bson:"sessionID"`
}
type Project struct {
ID string `bson:"_id,omitempty"`
Title string
Lang string
Desc string
Room string `bson:"project_room,omitempty"`
Text string `bson:"text,omitempty"`
}
type TemplateData struct {
Response string `json:"response,omitempty"`
Data string `json:"data,omitempty"`
Lang string `json:"lang,omitempty"`
File string `json:"file,omitempty"`
Code string `json:"code,omitempty"`
Tree template.JS `json:"tree,omitempty"`
Error string `json:"error,omitempty"`
Username string `json:"username,omitempty"`
}
type FSNode struct {
Name string `bson:"name"`
Data []byte `bson:"data,omitempty"`
Children []FSNode `bson:"children,omitempty"`
}
var cookieHandler = securecookie.New(
securecookie.GenerateRandomKey(64),
securecookie.GenerateRandomKey(32))
var users *mgo.Collection
//var files *mgo.Collection
var projects *mgo.Collection
var sessions *mgo.Collection
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal("Socket Error: ", err)
}
uri := os.Getenv("MONGODB_URI")
if uri == "" {
uri = "127.0.0.1"
}
log.Println("Connecting to db at " + uri)
session, err := mgo.Dial(uri)
if err != nil {
log.Fatal("MongoDB Error: ", err)
}
dbName := os.Getenv("MONGODB")
//log.Println(dbName)
users = session.DB(dbName).C("users")
//files = session.DB(dbName).C("files")
projects = session.DB(dbName).C("projects")
sessions = session.DB(dbName).C("sessions")
defer session.Close()
// Possible change: create a shared data system
// to conserve server ram for scaling purposes
// using pointers in the variables below
// All users
activeUsers := make(map[string]socketio.Socket)
// Users per room
rooms := make(map[string][]string)
// updates before the last save
recentUpdates := make(map[string][]string)
server.On("connection", func(so socketio.Socket) {
activeUsers[so.Id()] = so
//so.Join("default")
// Binds the socket id to the users account temporary
so.On("user:bind", func(data string) {
// checks to see if the current users
log.Println("Socket.IO - room:bind " + data)
})
// Joins a specific room
so.On("room:join", func(data string) {
log.Println("Socket.IO - room:join " + data)
// Check to see if this user is able to join the room
//roomName := json.Unmarshal(data)...?
var result Project
projects.Find(bson.M{"project_name": data}).One(&result)
room := result.Room
rooms[room] = append(rooms[room], so.Id())
so.Join(room)
// Not optimal for scaling
so.Emit("code:change", result.Text)
for _, value := range recentUpdates[room] {
so.Emit("code:update", value)
}
})
// Joins a specific room
so.On("room:leave", func(data string) {
//delete(rooms[data], so.Id())
so.Leave(data)
log.Println("Socket.IO - room:leave " + data)
})
// Updates letter by letter
so.On("code:update", func(data string) {
// Not optimal for scaling
for id, socket := range activeUsers {
if id != so.Id() {
socket.Emit("code:update", data)
recentUpdates["default"] = append(recentUpdates["default"], data)
}
}
})
// Updates new users that join session
so.On("code:sync", func(data string) {
})
// Saves data to database
so.On("code:save", func(data string) {
})
// Checks if all users in the room are in sync
so.On("code:check", func(data string) {
})
so.On("terminal:command", func(data string) {
})
so.On("terminal:join", func(data string) {
})
so.On("terminal:leave", func(data string) {
})
so.On("user:log", func() {
log.Printf("active users: %d", activeUsers)
})
// When the user disconnects
// (in case of a temporary disconnection,
// saving the session would be a good idea)
so.On("disconnection", func() {
delete(activeUsers, so.Id())
})
})
server.On("error", func(so socketio.Socket, err error) {
log.Println("error:", err)
})
r := mux.NewRouter()
r.HandleFunc("/", homepage)
r.HandleFunc("/netcode", netcode).Methods("GET")
r.HandleFunc("/command", command).Methods("POST")
r.HandleFunc("/code", code).Methods("GET")
r.HandleFunc("/users/{username}", nil).Methods("GET")
r.HandleFunc("/code", code).Methods("GET")
r.HandleFunc("/projects", _projects).Methods("GET")
r.HandleFunc("/projects/{p_name}", nil).Methods("GET")
// Authentication
r.HandleFunc("/login", login).Methods("GET")
r.HandleFunc("/register", register).Methods("GET")
r.HandleFunc("/login", _login).Methods("POST")
r.HandleFunc("/register", _register).Methods("POST")
r.HandleFunc("/logout", logout).Methods("GET")
r.Handle("/socket.io/", server)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/")))
http.Handle("/", r)
log.Println("Serving at http://localhost:" + port)
log.Fatal(http.ListenAndServe(":"+port, nil))
// log.Println("Serving at https://localhost" )
// log.Fatal(http.ListenAndServeTLS(":443", "server.crt", "server.key", nil))
}
func tercon(z bool, a interface{}, b interface{}) interface{} {
if z {
return a
}
return b
}
func SetFlash(w http.ResponseWriter, name string, value string) {
c := &http.Cookie{Name: name, Value: encode([]byte(value))}
http.SetCookie(w, c)
}
func GetFlash(w http.ResponseWriter, r *http.Request, name string) []byte {
c, err := r.Cookie(name)
if err != nil {
switch err {
case http.ErrNoCookie:
return nil
default:
log.Fatal(err)
return nil
}
}
value, err := decode(c.Value)
if err != nil {
log.Fatal(err)
return nil
}
dc := &http.Cookie{Name: name, MaxAge: -1, Expires: time.Unix(1, 0)}
http.SetCookie(w, dc)
return value
}
func encode(src []byte) string {
return base64.URLEncoding.EncodeToString(src)
}
func decode(src string) ([]byte, error) {
return base64.URLEncoding.DecodeString(src)
}
// Password to hash
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 4)
return string(bytes), err
}
// Check if password and hash matvh
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func getID(request *http.Request) (id string) {
if cookie, err := request.Cookie("session"); err == nil {
cookieValue := make(map[string]string)
if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
id = cookieValue["id"]
}
}
return id
}
func getUsername(request *http.Request) (username string) {
if cookie, err := request.Cookie("session"); err == nil {
cookieValue := make(map[string]string)
if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
id := cookieValue["id"]
var sess Session
sessions.Find(bson.M{"sessionID": id}).One(&sess)
username = sess.Username
}
}
return username
}
func setSession(username string, response http.ResponseWriter) {
id := uuid.New().String()
sessions.Insert(&Session{
SessionID: id,
LastActive: time.Now().Unix(),
Username: strings.ToLower(username),
})
value := map[string]string{"id": id}
if encoded, err := cookieHandler.Encode("session", value); err == nil {
cookie := &http.Cookie{
Name: "session",
Value: encoded,
Path: "/",
}
http.SetCookie(response, cookie)
}
}
func clearSession(id string, response http.ResponseWriter) {
sessions.Remove(bson.M{"sessionID": id})
cookie := &http.Cookie{
Name: "session",
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(response, cookie)
}
// Routes
func homepage(w http.ResponseWriter, r *http.Request) {
start := time.Now()
paths := []string{
"src/index.html",
"src/partials/navbar.html",
"src/partials/footer.html"}
tmpl := template.Must(template.ParseFiles(paths...))
homeItems := struct {
Username string
Projects []Project
}{
Username: getUsername(r),
}
err := tmpl.Execute(w, homeItems)
if err != nil {
log.Fatalf("template execution: %s", err)
os.Exit(1)
}
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func netcode(w http.ResponseWriter, r *http.Request) {
start := time.Now()
paths := []string{
"src/netcode.html",
"src/partials/navbar.html",
"src/partials/footer.html",
}
tmpl := template.Must(template.ParseFiles(paths...))
var data = TemplateData{
Lang: "HTML",
File: "netcode.html",
Code: `let welcomeTo = "Netcode"`,
Tree: `[{text:"Folder 1",nodes:[{text:"Folder 2",nodes:[{text:"File 1"}]},{text:"File 2"}]},{text:"Folder 3"},{text:"Folder 4"}]`,
Username: getUsername(r),
}
err := tmpl.Execute(w, data)
if err != nil {
log.Fatalf("template execution: %s", err)
}
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func calculator(w http.ResponseWriter, r *http.Request) {
start := time.Now()
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func command(w http.ResponseWriter, r *http.Request) {
// Optimize this by putting this code in the socket
start := time.Now()
response := ""
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
cmd := string(body)
if cmd == "" {
response = " "
} else {
id := getID(r)
if id != "" {
var sess Session
sessions.Find(bson.M{"sessionID": id}).One(&sess)
username := sess.Username
switch cmd {
case "whoami":
response = username
break
case "id":
response = id
break
default:
response = "netcode: " + cmd + ": command not recognized"
}
} else {
response = "You need to log in"
}
}
json.NewEncoder(w).Encode(TemplateData{Response: response})
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func code(w http.ResponseWriter, r *http.Request) {
start := time.Now()
paths := []string{
"src/code.html",
"src/partials/themes.html",
"src/partials/theme-options.html",
"src/partials/navbar.html",
"src/partials/footer.html"}
tmpl := template.Must(template.ParseFiles(paths...))
var data = TemplateData{
Username: getUsername(r),
}
err := tmpl.Execute(w, data)
if err != nil {
log.Fatalf("template execution: %s", err)
}
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func _projects(w http.ResponseWriter, r *http.Request) {
start := time.Now()
paths := []string{
"src/projects.html",
"src/partials/navbar.html",
"src/partials/footer.html"}
tmpl := template.Must(template.ParseFiles(paths...))
var data = TemplateData{
Username: getUsername(r),
}
err := tmpl.Execute(w, data)
if err != nil {
log.Fatalf("template execution: %s", err)
}
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func login(w http.ResponseWriter, r *http.Request) {
start := time.Now()
paths := []string{
"src/login.html",
"src/partials/navbar.html",
"src/partials/footer.html"}
tmpl := template.Must(template.ParseFiles(paths...))
var data = struct {
Error string
Username string
}{
Error: string(GetFlash(w, r, "error")),
Username: getUsername(r),
}
err := tmpl.Execute(w, data)
if err != nil {
log.Fatalf("template execution: %s", err)
}
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func register(w http.ResponseWriter, r *http.Request) {
start := time.Now()
paths := []string{
"src/register.html",
"src/partials/navbar.html",
"src/partials/footer.html"}
tmpl := template.Must(template.ParseFiles(paths...))
err := tmpl.Execute(w, nil)
if err != nil {
log.Fatalf("template execution: %s", err)
}
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func _login(w http.ResponseWriter, r *http.Request) {
start := time.Now()
username := r.FormValue("Username")
pass := r.FormValue("Password")
redirectTarget := "/login"
user := User{}
if username != "" && pass != "" {
err := users.Find(bson.M{"username": username}).One(&user)
if err != nil {
SetFlash(w, "error", "User does not exist")
} else if CheckPasswordHash(pass, user.Password) {
setSession(username, w)
redirectTarget = "/"
} else {
SetFlash(w, "error", "Incorrect password")
}
}
http.Redirect(w, r, redirectTarget, 302)
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func _register(w http.ResponseWriter, r *http.Request) {
start := time.Now()
username := r.FormValue("Username")
pass := r.FormValue("Password")
confirmpass := r.FormValue("ConfirmPassword")
redirectTarget := "/register"
if pass != confirmpass {
SetFlash(w, "error", "Your passwords are different")
} else if username != "" && pass != "" && confirmpass != "" {
hash, _ := HashPassword(pass)
err := users.Insert(bson.M{"username": username, "password": hash})
if err != nil {
log.Fatal(err)
}
redirectTarget = "/login"
SetFlash(w, "success", "Your account was created please log in")
}
http.Redirect(w, r, redirectTarget, 302)
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
func logout(w http.ResponseWriter, r *http.Request) {
start := time.Now()
clearSession(getID(r), w)
http.Redirect(w, r, "/", 302)
log.Printf(r.Method+" - "+r.URL.Path+" - %v\n", time.Now().Sub(start))
}
|
package v1
import (
"context"
"reflect"
"github.com/aws/aws-sdk-go/service/ec2"
"github.o-in.dwango.co.jp/naari3/ingress-sg-validator/pkg/aws/services"
)
type mockEC2 struct {
services.EC2
store []*ec2.SecurityGroup
}
// Only support 'GroupIds' and part of 'Filter'
func (c *mockEC2) DescribeSecurityGroupsAsList(ctx context.Context, input *ec2.DescribeSecurityGroupsInput) ([]*ec2.SecurityGroup, error) {
var result []*ec2.SecurityGroup
groupIds := []string{}
for _, gid := range input.GroupIds {
groupIds = append(groupIds, *gid)
}
var nameFilter *ec2.Filter
for _, f := range input.Filters {
if *f.Name == "tag:Name" {
nameFilter = f
break
}
}
names := []string{}
if nameFilter != nil {
for _, v := range nameFilter.Values {
names = append(names, *v)
}
}
for _, sg := range c.store {
if sg != nil && contains(groupIds, *sg.GroupId) {
result = append(result, sg)
} else if nameFilter != nil && *nameFilter.Name == "tag:Name" && contains(names, *(sg.GroupName)) {
result = append(result, sg)
}
}
return result, nil
}
func contains(list interface{}, elem interface{}) bool {
listV := reflect.ValueOf(list)
if listV.Kind() == reflect.Slice {
for i := 0; i < listV.Len(); i++ {
item := listV.Index(i).Interface()
if !reflect.TypeOf(elem).ConvertibleTo(reflect.TypeOf(item)) {
continue
}
target := reflect.ValueOf(elem).Convert(reflect.TypeOf(item)).Interface()
if ok := reflect.DeepEqual(item, target); ok {
return true
}
}
}
return false
}
|
package gcs_proxy
import (
"testing"
"github.com/stretchr/testify/assert"
"net/http/httptest"
"net/http"
"errors"
)
type StubRepository struct {
getObjects func(path string) ([]Object, error)
getObject func(path string) ([]byte, error)
isFile func(path string) (bool, error)
}
func (s StubRepository) GetObject(path string) ([]byte, error) {
if s.getObject == nil {
return []byte(""), nil
}
return s.getObject(path)
}
func (s StubRepository) IsFile(path string) (bool, error) {
if s.isFile == nil {
return false, nil
}
return s.isFile(path)
}
func (s StubRepository) GetObjects(path string) ([]Object, error) {
if s.getObjects == nil {
return []Object{}, nil
}
return s.getObjects(path)
}
func TestItRespondsWithA200OnSlash(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(NewServer(StubRepository{}).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Result().StatusCode)
}
func TestItRendersFiles(t *testing.T) {
files := []Object{
File{Name: "file1"},
File{Name: "file2"},
File{Name: "file3"},
}
repository := StubRepository{}
repository.getObjects = func(path string) ([]Object, error) {
return files, nil
}
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(NewServer(repository).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Result().StatusCode)
assert.Contains(t, string(rr.Body.Bytes()), files[0].GetName())
assert.Contains(t, string(rr.Body.Bytes()), files[1].GetName())
assert.Contains(t, string(rr.Body.Bytes()), files[2].GetName())
}
func TestItRendersFilesWhenTraversing(t *testing.T) {
slashPath := "/"
slashFiles := []Object{
File{Name: "file1"},
File{Name: "file2"},
Directory{Name: "imADirectory"},
}
directoryPath := "/imADirectory"
directoryFiles := []Object{
File{Path: "imADirectory/directoryFile1", Name: "directoryFile1"},
File{Path: "imADirectory/directoryFile2", Name: "directoryFile1"},
File{Path: "imADirectory/directoryFile3", Name: "directoryFile1"},
}
repository := StubRepository{}
repository.getObjects = func(path string) ([]Object, error) {
if path == slashPath {
return slashFiles, nil
}
if path == directoryPath {
return directoryFiles, nil
}
t.Error("Should not get here")
return []Object{}, nil
}
req, _ := http.NewRequest("GET", slashPath, nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(NewServer(repository).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Result().StatusCode)
assert.Contains(t, string(rr.Body.Bytes()), slashFiles[0].GetName())
assert.Contains(t, string(rr.Body.Bytes()), slashFiles[1].GetName())
assert.Contains(t, string(rr.Body.Bytes()), slashFiles[2].GetName())
req, _ = http.NewRequest("GET", directoryPath, nil)
rr = httptest.NewRecorder()
handler = http.HandlerFunc(NewServer(repository).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Result().StatusCode)
assert.Contains(t, string(rr.Body.Bytes()), directoryFiles[0].GetName())
assert.Contains(t, string(rr.Body.Bytes()), directoryFiles[1].GetName())
assert.Contains(t, string(rr.Body.Bytes()), directoryFiles[2].GetName())
assert.Contains(t, string(rr.Body.Bytes()), directoryFiles[0].GetPath())
assert.Contains(t, string(rr.Body.Bytes()), directoryFiles[1].GetPath())
assert.Contains(t, string(rr.Body.Bytes()), directoryFiles[2].GetPath())
}
func TestItReturnsTheContentOfTheFile(t *testing.T) {
requestPath := "/file1"
file1Content := "imAFile"
repository := StubRepository{}
repository.isFile = func(path string) (bool, error) {
return path == requestPath, nil
}
repository.getObject = func(path string) ([]byte, error) {
if path == requestPath {
return []byte(file1Content), nil
}
t.Fatal("Should not get here")
return []byte(""), nil
}
req, _ := http.NewRequest("GET", requestPath, nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(NewServer(repository).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Result().StatusCode)
assert.Equal(t, string(rr.Body.Bytes()), file1Content)
}
func TestItReturnsTheRightContentTypeOfTheFile(t *testing.T) {
requestPath := "/file1.html"
file1Content := "imAFile"
repository := StubRepository{}
repository.isFile = func(path string) (bool, error) {
return path == requestPath, nil
}
repository.getObject = func(path string) ([]byte, error) {
if path == requestPath {
return []byte(file1Content), nil
}
t.Fatal("Should not get here")
return []byte(""), nil
}
req, _ := http.NewRequest("GET", requestPath, nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(NewServer(repository).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Result().StatusCode)
assert.Equal(t, "text/html; charset=utf-8", rr.Result().Header.Get("Content-Type"))
assert.Equal(t, string(rr.Body.Bytes()), file1Content)
}
func TestItReturnsAnyErrorFromGetObjects(t *testing.T) {
expectedError := errors.New("nooooes")
repository := StubRepository{}
repository.getObjects = func(path string) ([]Object, error) {
return []Object{}, expectedError
}
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(NewServer(repository).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusInternalServerError, rr.Result().StatusCode)
assert.Contains(t, string(rr.Body.Bytes()), expectedError.Error())
}
func TestItReturnsAnyErrorFromGetObject(t *testing.T) {
expectedError := errors.New("nooooes")
filePath := "path/to/file"
repository := StubRepository{}
repository.isFile = func(path string) (bool, error) {
if path == filePath {
return true, nil
}
t.Error("Should not get here")
return false, nil
}
repository.getObject = func(path string) ([]byte, error) {
if path == filePath {
return nil, expectedError
}
t.Error("Should not get here")
return nil, nil
}
req, _ := http.NewRequest("GET", filePath, nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(NewServer(repository).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusInternalServerError, rr.Result().StatusCode)
assert.Contains(t, string(rr.Body.Bytes()), expectedError.Error())
}
func TestItReturnsAnyErrorFromIsFile(t *testing.T) {
expectedError := errors.New("nooooes")
filePath := "path/to/file"
repository := StubRepository{}
repository.isFile = func(path string) (bool, error) {
if path == filePath {
return false, expectedError
}
t.Error("Should not get here")
return false, nil
}
req, _ := http.NewRequest("GET", filePath, nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(NewServer(repository).Handler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusInternalServerError, rr.Result().StatusCode)
assert.Contains(t, string(rr.Body.Bytes()), expectedError.Error())
}
|
package problem0239
func maxSlidingWindow(nums []int, k int) []int {
deque := &Deque{}
result := make([]int, len(nums)-k+1)
for i := 0; i < len(nums); i++ {
for !deque.IsEmpty() && i-deque.First() >= k {
deque.Shift()
}
for !deque.IsEmpty() && nums[i] > nums[deque.Last()] {
deque.Pop()
}
deque.Push(i)
if i >= k-1 {
result[i-k+1] = nums[deque.First()]
}
}
return result
}
type Deque struct {
data []int
}
func (d *Deque) Push(num int) {
d.data = append(d.data, num)
}
func (d *Deque) Pop() {
d.data = d.data[0 : len(d.data)-1]
}
func (d *Deque) Shift() {
d.data = d.data[1:len(d.data)]
}
func (d *Deque) First() int {
return d.data[0]
}
func (d *Deque) Last() int {
return d.data[len(d.data)-1]
}
func (d *Deque) IsEmpty() bool {
return len(d.data) == 0
}
|
package example
import (
"github.com/GoAdminGroup/go-admin/context"
"github.com/GoAdminGroup/go-admin/modules/auth"
"github.com/GoAdminGroup/go-admin/modules/db"
"github.com/GoAdminGroup/go-admin/modules/service"
)
func (e *Example) initRouter(prefix string, srv service.List) *context.App {
app := context.NewApp()
route := app.Group(prefix)
route.GET("/example", auth.Middleware(db.GetConnection(srv)), e.TestHandler)
return app
}
|
package main
import "fmt"
func main() {
b := 255
a := &b
fmt.Printf("%T and %v\n", a, a)
var c *int
if c == nil {
fmt.Println("Zero value is:", c)
c = &b
fmt.Println("New value is:", c)
}
intPntr := new(int)
fmt.Printf("Type %T val %v Type pntr value %T Ptr Value %v\n", intPntr, intPntr, *intPntr, *intPntr)
*intPntr = 25
fmt.Printf("Type %T val %v Type pntr value %T Ptr Value %v\n", intPntr, intPntr, *intPntr, *intPntr)
}
|
// Package eskip-match provides a cli tool and utilities to
// helps you test Skipper (https://github.com/zalando/skipper)
// `.eskip` files routing matching logic.
package main
import (
"log"
"os"
"github.com/rbarilani/eskip-match/cli"
)
var logFatal = log.Fatal
func main() {
app := cli.NewApp()
app.Version = "0.4.1"
err := app.Run(os.Args)
if err != nil {
logFatal(err)
}
}
|
/*
Copyright 2021. The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package policydefinition
import (
"context"
"fmt"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/oam/testutil"
"github.com/oam-dev/kubevela/pkg/oam/util"
)
var _ = Describe("Test DefinitionRevision created by PolicyDefinition", func() {
ctx := context.Background()
namespace := "test-revision"
var ns v1.Namespace
BeforeEach(func() {
ns = v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
Expect(k8sClient.Create(ctx, &ns)).Should(SatisfyAny(BeNil(), &util.AlreadyExistMatcher{}))
})
Context("Test PolicyDefinition", func() {
It("Test update PolicyDefinition", func() {
defName := "test-def"
req := reconcile.Request{NamespacedName: client.ObjectKey{Name: defName, Namespace: namespace}}
def1 := defWithNoTemplate.DeepCopy()
def1.Name = defName
def1.Spec.Schematic.CUE.Template = fmt.Sprintf(defTemplate, "test-v1")
By("create policyDefinition")
Expect(k8sClient.Create(ctx, def1)).Should(SatisfyAll(BeNil()))
testutil.ReconcileRetry(&r, req)
By("check whether definitionRevision is created")
defRevName1 := fmt.Sprintf("%s-v1", defName)
var defRev1 v1beta1.DefinitionRevision
Eventually(func() error {
err := k8sClient.Get(ctx, client.ObjectKey{Namespace: namespace, Name: defRevName1}, &defRev1)
return err
}, 10*time.Second, time.Second).Should(BeNil())
By("update policyDefinition")
def := new(v1beta1.PolicyDefinition)
Eventually(func() error {
err := k8sClient.Get(ctx, client.ObjectKey{Namespace: namespace, Name: defName}, def)
if err != nil {
return err
}
def.Spec.Schematic.CUE.Template = fmt.Sprintf(defTemplate, "test-v2")
return k8sClient.Update(ctx, def)
}, 10*time.Second, time.Second).Should(BeNil())
testutil.ReconcileRetry(&r, req)
By("check whether a new definitionRevision is created")
tdRevName2 := fmt.Sprintf("%s-v2", defName)
var tdRev2 v1beta1.DefinitionRevision
Eventually(func() error {
return k8sClient.Get(ctx, client.ObjectKey{Namespace: namespace, Name: tdRevName2}, &tdRev2)
}, 10*time.Second, time.Second).Should(BeNil())
})
It("Test only update PolicyDefinition Labels, Shouldn't create new revision", func() {
def := defWithNoTemplate.DeepCopy()
defName := "test-def-update"
def.Name = defName
defKey := client.ObjectKey{Namespace: namespace, Name: defName}
req := reconcile.Request{NamespacedName: defKey}
def.Spec.Schematic.CUE.Template = fmt.Sprintf(defTemplate, "test")
Expect(k8sClient.Create(ctx, def)).Should(BeNil())
testutil.ReconcileRetry(&r, req)
By("Check revision create by PolicyDefinition")
defRevName := fmt.Sprintf("%s-v1", defName)
revKey := client.ObjectKey{Namespace: namespace, Name: defRevName}
var defRev v1beta1.DefinitionRevision
Eventually(func() error {
return k8sClient.Get(ctx, revKey, &defRev)
}, 10*time.Second, time.Second).Should(BeNil())
By("Only update PolicyDefinition Labels")
var checkRev v1beta1.PolicyDefinition
Eventually(func() error {
err := k8sClient.Get(ctx, defKey, &checkRev)
if err != nil {
return err
}
checkRev.SetLabels(map[string]string{
"test-label": "test-defRev",
})
return k8sClient.Update(ctx, &checkRev)
}, 10*time.Second, time.Second).Should(BeNil())
testutil.ReconcileRetry(&r, req)
newDefRevName := fmt.Sprintf("%s-v2", defName)
newRevKey := client.ObjectKey{Namespace: namespace, Name: newDefRevName}
Expect(k8sClient.Get(ctx, newRevKey, &defRev)).Should(HaveOccurred())
})
})
Context("Test PolicyDefinition Controller clean up", func() {
It("Test clean up definitionRevision", func() {
var revKey client.ObjectKey
var defRev v1beta1.DefinitionRevision
defName := "test-clean-up"
revisionNum := 1
defKey := client.ObjectKey{Namespace: namespace, Name: defName}
req := reconcile.Request{NamespacedName: defKey}
By("create a new PolicyDefinition")
def := defWithNoTemplate.DeepCopy()
def.Name = defName
def.Spec.Schematic.CUE.Template = fmt.Sprintf(defTemplate, fmt.Sprintf("test-v%d", revisionNum))
Expect(k8sClient.Create(ctx, def)).Should(BeNil())
By("update PolicyDefinition")
checkRev := new(v1beta1.PolicyDefinition)
for i := 0; i < defRevisionLimit+1; i++ {
Eventually(func() error {
err := k8sClient.Get(ctx, defKey, checkRev)
if err != nil {
return err
}
checkRev.Spec.Schematic.CUE.Template = fmt.Sprintf(defTemplate, fmt.Sprintf("test-v%d", revisionNum))
return k8sClient.Update(ctx, checkRev)
}, 10*time.Second, time.Second).Should(BeNil())
testutil.ReconcileRetry(&r, req)
revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", defName, revisionNum)}
revisionNum++
var defRev v1beta1.DefinitionRevision
Eventually(func() error {
return k8sClient.Get(ctx, revKey, &defRev)
}, 10*time.Second, time.Second).Should(BeNil())
}
By("create new PolicyDefinition will remove oldest definitionRevision")
Eventually(func() error {
err := k8sClient.Get(ctx, defKey, checkRev)
if err != nil {
return err
}
checkRev.Spec.Schematic.CUE.Template = fmt.Sprintf(defTemplate, fmt.Sprintf("test-v%d", revisionNum))
return k8sClient.Update(ctx, checkRev)
}, 10*time.Second, time.Second).Should(BeNil())
testutil.ReconcileRetry(&r, req)
revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", defName, revisionNum)}
revisionNum++
Eventually(func() error {
return k8sClient.Get(ctx, revKey, &defRev)
}, 10*time.Second, time.Second).Should(BeNil())
deletedRevision := new(v1beta1.DefinitionRevision)
deleteRevKey := types.NamespacedName{Namespace: namespace, Name: defName + "-v1"}
listOpts := []client.ListOption{
client.InNamespace(namespace),
client.MatchingLabels{
oam.LabelPolicyDefinitionName: defName,
},
}
defRevList := new(v1beta1.DefinitionRevisionList)
Eventually(func() error {
err := k8sClient.List(ctx, defRevList, listOpts...)
if err != nil {
return err
}
if len(defRevList.Items) != defRevisionLimit+1 {
return fmt.Errorf("error defRevison number wants %d, actually %d", defRevisionLimit+1, len(defRevList.Items))
}
err = k8sClient.Get(ctx, deleteRevKey, deletedRevision)
if err == nil || !apierrors.IsNotFound(err) {
return fmt.Errorf("haven't clean up the oldest revision")
}
return nil
}, time.Second*30, time.Microsecond*300).Should(BeNil())
By("update app again will continue to delete the oldest revision")
Eventually(func() error {
err := k8sClient.Get(ctx, defKey, checkRev)
if err != nil {
return err
}
checkRev.Spec.Schematic.CUE.Template = fmt.Sprintf(defTemplate, fmt.Sprintf("test-v%d", revisionNum))
return k8sClient.Update(ctx, checkRev)
}, 10*time.Second, time.Second).Should(BeNil())
testutil.ReconcileRetry(&r, req)
revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", defName, revisionNum)}
Eventually(func() error {
return k8sClient.Get(ctx, revKey, &defRev)
}, 10*time.Second, time.Second).Should(BeNil())
deleteRevKey = types.NamespacedName{Namespace: namespace, Name: defName + "-v2"}
Eventually(func() error {
err := k8sClient.List(ctx, defRevList, listOpts...)
if err != nil {
return err
}
if len(defRevList.Items) != defRevisionLimit+1 {
return fmt.Errorf("error defRevison number wants %d, actually %d", defRevisionLimit+1, len(defRevList.Items))
}
err = k8sClient.Get(ctx, deleteRevKey, deletedRevision)
if err == nil || !apierrors.IsNotFound(err) {
return fmt.Errorf("haven't clean up the oldest revision")
}
return nil
}, time.Second*30, time.Microsecond*300).Should(BeNil())
})
})
})
var defTemplate = `
output: {
apiVersion: "batch/v1"
kind: "Job"
spec: {
parallelism: parameter.count
completions: parameter.count
template: spec: {
restartPolicy: parameter.restart
containers: [{
name: "%s"
image: parameter.image
if parameter["cmd"] != _|_ {
command: parameter.cmd
}
}]
}
}
}
parameter: {
// +usage=Specify number of tasks to run in parallel
// +short=c
count: *1 | int
// +usage=Which image would you like to use for your service
// +short=i
image: string
// +usage=Define the job restart policy, the value can only be Never or OnFailure. By default, it's Never.
restart: *"Never" | string
// +usage=Commands to run in the container
cmd?: [...string]
}
`
var defWithNoTemplate = &v1beta1.PolicyDefinition{
TypeMeta: metav1.TypeMeta{
Kind: "PolicyDefinition",
APIVersion: "core.oam.dev/v1beta1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-defrev",
Namespace: "test-revision",
},
Spec: v1beta1.PolicyDefinitionSpec{
Schematic: &common.Schematic{
CUE: &common.CUE{},
},
},
}
|
package main
import (
"log"
"time"
"github.com/garyburd/redigo/redis"
)
type Worker struct {
Name string
Address string
conn redis.Conn
}
func NewWorker(name string, addr string) *Worker {
return &Worker{Name: name, Address: addr}
}
func (w *Worker) Connect() {
c, err := NewConn()
if err != nil {
log.Fatal(err)
}
w.conn = c
}
func (w *Worker) Close() {
w.conn.Close()
}
func (w *Worker) HeartBeat() {
w.Connect()
defer w.Close()
key := workerKeyPrefix + w.Name
_, err := w.conn.Do("HMSET", key, "addr", w.Address, "name", w.Name)
if err != nil {
log.Println(err)
}
for {
_, err := w.conn.Do("Expire", key, 5)
if err != nil {
break
}
time.Sleep(time.Second * 3)
}
}
|
package rpc
import (
"context"
"gate/config"
"google.golang.org/grpc"
"log"
"message"
"time"
)
var GateToClusterClient *GateToCluster
var connect grpc.ClientConnInterface
var client message.ServerServiceClient
//连接cluster
type GateToCluster struct {
connect grpc.ClientConnInterface
}
func (g *GateToCluster) Start(rpcUrl string) {
conn, err := grpc.Dial(rpcUrl, grpc.WithInsecure())
if err != nil {
log.Fatalf("%v", err)
}
connect = conn
client = message.NewServerServiceClient(connect)
}
func (g *GateToCluster) Stop() {
//connect.Close()
}
/**
注册到cluster服务器
*/
func RegisterToCluster() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
result, err := client.ServerRegister(ctx, &message.ServerInfo{
Id: config.GateConfig.Id,
BelongID: config.GateConfig.Id,
Ip: "localhost",
Type: 2,
Port: 80,
State: 1,
Version: "",
Content: "gate",
Online: 0,
MaxUserCount: 2000,
HttpPort: 80,
OpenTime: "",
MaintainTime: "",
Name: "client",
Wwwip: "",
XXX_NoUnkeyedLiteral: struct{}{},
XXX_unrecognized: nil,
XXX_sizecache: 0,
})
if err != nil {
log.Fatal("%v", err)
}
log.Printf("%s", result)
}
|
package gsm7bit
import "unicode"
func init() {
for index, r := range reverseLookup {
forwardLookup[r] = byte(index)
}
for r, b := range forwardEscapes {
reverseEscapes[b] = r
}
}
const esc, cr byte = 0x1B, 0x0D
var forwardLookup = map[rune]byte{}
var reverseLookup = [256]rune{
0x40, 0xA3, 0x24, 0xA5, 0xE8, 0xE9, 0xF9, 0xEC, 0xF2, 0xE7, 0x0A, 0xD8, 0xF8, 0x0D, 0xC5, 0xE5,
0x0394, 0x005F, 0x03A6, 0x0393, 0x039B, 0x03A9, 0x03A0, 0x03A8, 0x03A3, 0x0398, 0x039E, 0x00A0,
0xC6, 0xE6, 0xDF, 0xC9, 0x20, 0x21, 0x22, 0x23, 0xA4, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B,
0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B,
0x3C, 0x3D, 0x3E, 0x3F, 0xA1, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B,
0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0xC4,
0xD6, 0xD1, 0xDC, 0xA7, 0xBF, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B,
0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xE4,
0xF6, 0xF1, 0xFC, 0xE0,
}
var forwardEscapes = map[rune]byte{
0x0C: 0x0A, 0x5B: 0x3C, 0x5C: 0x2F, 0x5D: 0x3E, 0x5E: 0x14, 0x7B: 0x28, 0x7C: 0x40, 0x7D: 0x29, 0x7E: 0x3D,
0x20AC: 0x65,
}
var reverseEscapes = map[byte]rune{}
var DefaultAlphabet = &unicode.RangeTable{R16: []unicode.Range16{
{0x000A, 0x000A, 1}, {0x000C, 0x000D, 1}, {0x0020, 0x005F, 1}, {0x0061, 0x007E, 1}, {0x00A0, 0x00A1, 1},
{0x00A3, 0x00A5, 1}, {0x00A7, 0x00A7, 1}, {0x00BF, 0x00BF, 1}, {0x00C4, 0x00C6, 1}, {0x00C9, 0x00C9, 1},
{0x00D1, 0x00D1, 1}, {0x00D6, 0x00D6, 1}, {0x00D8, 0x00D8, 1}, {0x00DC, 0x00DC, 1}, {0x00DF, 0x00E0, 1},
{0x00E4, 0x00E9, 1}, {0x00EC, 0x00EC, 1}, {0x00F1, 0x00F2, 1}, {0x00F6, 0x00F6, 1}, {0x00F8, 0x00F9, 1},
{0x00FC, 0x00FC, 1}, {0x0393, 0x0394, 1}, {0x0398, 0x0398, 1}, {0x039B, 0x039B, 1}, {0x039E, 0x039E, 1},
{0x03A0, 0x03A0, 1}, {0x03A3, 0x03A3, 1}, {0x03A6, 0x03A6, 1}, {0x03A8, 0x03A9, 1}, {0x20AC, 0x20AC, 1},
}}
|
package r2
import (
"net/http"
"net/url"
)
// PostForm sets the request post form and the content type.
func PostForm(postForm url.Values) Option {
return func(r *Request) {
if r.Header == nil {
r.Header = http.Header{}
}
r.Header.Set(HeaderContentType, ContentTypeApplicationFormEncoded)
r.PostForm = postForm
}
}
// PostFormValue sets a request post form value.
func PostFormValue(key, value string) Option {
return func(r *Request) {
if r.Header == nil {
r.Header = http.Header{}
}
r.Header.Set(HeaderContentType, ContentTypeApplicationFormEncoded)
if r.PostForm == nil {
r.PostForm = url.Values{}
}
r.PostForm.Set(key, value)
}
}
|
package utils
/**
RPC通信配置
*/
const RPCURL = "http://127.0.0.1:8332"
const RPCUSER = "user"
const RPCPASSSWORD = "pwd"
const RPCBERSION = "2.0"
|
package main
import (
"fmt"
"math"
)
var XX = 200
const YY = 300 //常量不会分配地址
func main() {
const (
x uint16 = 120
y
s
s1 = "abc"
z
)
println(x, " ", y, " ", s, " ", s1, " ", z)
const (
a = iota
a1
b float32 = iota
c
)
println(a, " ", a1, " ", b, " ", c)
// println(&XX, &YY) // error
fmt.Printf("%v %v \n", math.MaxUint8, math.MaxInt64)
}
|
package hash
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"github.com/vlorc/lua-vm/base"
"hash"
)
type SHA1Factory struct{}
type SHA256Factory struct{}
type SHA512Factory struct{}
type MD5Factory struct{}
type HMACFactory struct{}
func __sum(h hash.Hash, buf ...base.Buffer) base.Buffer {
for _, v := range buf {
h.Write(v)
}
return base.Buffer(h.Sum(nil))
}
func (SHA1Factory) New() hash.Hash {
return sha1.New()
}
func (SHA1Factory) Sum(buf ...base.Buffer) base.Buffer {
return __sum(sha1.New(), buf...)
}
func (MD5Factory) New() hash.Hash {
return md5.New()
}
func (MD5Factory) Sum(buf ...base.Buffer) base.Buffer {
return __sum(md5.New(), buf...)
}
func (SHA256Factory) New() hash.Hash {
return sha256.New()
}
func (SHA256Factory) Sum(buf ...base.Buffer) base.Buffer {
return __sum(sha256.New(), buf...)
}
func (SHA512Factory) New() hash.Hash {
return sha512.New()
}
func (SHA512Factory) Sum(buf ...base.Buffer) base.Buffer {
return __sum(sha512.New(), buf...)
}
var __table = map[string]func() hash.Hash{
"md5": md5.New,
"sha1": sha1.New,
"sha256": sha256.New,
"sha512": sha512.New,
"MD5": md5.New,
"SHA1": sha1.New,
"SHA256": sha256.New,
"SHA512": sha512.New,
}
func (HMACFactory) New(method, secret string) hash.Hash {
return hmac.New(__table[method], []byte(secret))
}
func (f HMACFactory) Sum(method, secret string, buf ...base.Buffer) base.Buffer {
return __sum(f.New(method, secret), buf...)
}
|
package handlers
import (
"github.com/kkurahar/go-gin-lightweight/helpers/log"
"github.com/kkurahar/go-gin-lightweight/resources"
)
var (
tagResource = resources.NewResourceTag()
logger = log.NewLogger()
)
|
package generated
//go:generate dataloaden ServiceLoader int *github.com/syncromatics/kafmesh/internal/graph/model.Service
//go:generate dataloaden ServiceSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.Service
//go:generate dataloaden ProcessorLoader int *github.com/syncromatics/kafmesh/internal/graph/model.Processor
//go:generate dataloaden ProcessorSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.Processor
//go:generate dataloaden SinkSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.Sink
//go:generate dataloaden SourceSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.Source
//go:generate dataloaden ViewSinkSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.ViewSink
//go:generate dataloaden ViewSourceSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.ViewSource
//go:generate dataloaden ViewSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.View
//go:generate dataloaden ComponentLoader int *github.com/syncromatics/kafmesh/internal/graph/model.Component
//go:generate dataloaden InputSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.ProcessorInput
//go:generate dataloaden JoinSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.ProcessorJoin
//go:generate dataloaden LookupSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.ProcessorLookup
//go:generate dataloaden OutputSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.ProcessorOutput
//go:generate dataloaden PodSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.Pod
//go:generate dataloaden TopicLoader int *github.com/syncromatics/kafmesh/internal/graph/model.Topic
//go:generate dataloaden ComponentSliceLoader int []*github.com/syncromatics/kafmesh/internal/graph/model.Component
|
// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package testkit
import (
"crypto/tls"
"sync"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/session/txninfo"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/util"
)
// MockSessionManager is a mocked session manager which is used for test.
type MockSessionManager struct {
PS []*util.ProcessInfo
PSMu sync.RWMutex
SerID uint64
TxnInfo []*txninfo.TxnInfo
Dom *domain.Domain
Conn map[uint64]session.Session
mu sync.Mutex
ConAttrs map[uint64]map[string]string
internalSessions map[interface{}]struct{}
}
// ShowTxnList is to show txn list.
func (msm *MockSessionManager) ShowTxnList() []*txninfo.TxnInfo {
msm.mu.Lock()
defer msm.mu.Unlock()
if len(msm.TxnInfo) > 0 {
return msm.TxnInfo
}
rs := make([]*txninfo.TxnInfo, 0, len(msm.Conn))
for _, se := range msm.Conn {
info := se.TxnInfo()
if info != nil {
rs = append(rs, info)
}
}
return rs
}
// ShowProcessList implements the SessionManager.ShowProcessList interface.
func (msm *MockSessionManager) ShowProcessList() map[uint64]*util.ProcessInfo {
msm.PSMu.RLock()
defer msm.PSMu.RUnlock()
ret := make(map[uint64]*util.ProcessInfo)
if len(msm.PS) > 0 {
for _, item := range msm.PS {
ret[item.ID] = item
}
return ret
}
msm.mu.Lock()
for connID, pi := range msm.Conn {
ret[connID] = pi.ShowProcess()
}
msm.mu.Unlock()
if msm.Dom != nil {
for connID, pi := range msm.Dom.SysProcTracker().GetSysProcessList() {
ret[connID] = pi
}
}
return ret
}
// GetProcessInfo implements the SessionManager.GetProcessInfo interface.
func (msm *MockSessionManager) GetProcessInfo(id uint64) (*util.ProcessInfo, bool) {
msm.PSMu.RLock()
defer msm.PSMu.RUnlock()
for _, item := range msm.PS {
if item.ID == id {
return item, true
}
}
msm.mu.Lock()
defer msm.mu.Unlock()
if sess := msm.Conn[id]; sess != nil {
return sess.ShowProcess(), true
}
if msm.Dom != nil {
if pinfo, ok := msm.Dom.SysProcTracker().GetSysProcessList()[id]; ok {
return pinfo, true
}
}
return &util.ProcessInfo{}, false
}
// GetConAttrs returns the connection attributes of all connections
func (msm *MockSessionManager) GetConAttrs() map[uint64]map[string]string {
return msm.ConAttrs
}
// Kill implements the SessionManager.Kill interface.
func (*MockSessionManager) Kill(uint64, bool, bool) {
}
// KillAllConnections implements the SessionManager.KillAllConnections interface.
func (*MockSessionManager) KillAllConnections() {
}
// UpdateTLSConfig implements the SessionManager.UpdateTLSConfig interface.
func (*MockSessionManager) UpdateTLSConfig(*tls.Config) {
}
// ServerID get server id.
func (msm *MockSessionManager) ServerID() uint64 {
return msm.SerID
}
// GetAutoAnalyzeProcID implement SessionManager interface.
func (msm *MockSessionManager) GetAutoAnalyzeProcID() uint64 {
return uint64(1)
}
// StoreInternalSession is to store internal session.
func (msm *MockSessionManager) StoreInternalSession(s interface{}) {
msm.mu.Lock()
if msm.internalSessions == nil {
msm.internalSessions = make(map[interface{}]struct{})
}
msm.internalSessions[s] = struct{}{}
msm.mu.Unlock()
}
// DeleteInternalSession is to delete the internal session pointer from the map in the SessionManager
func (msm *MockSessionManager) DeleteInternalSession(s interface{}) {
msm.mu.Lock()
delete(msm.internalSessions, s)
msm.mu.Unlock()
}
// GetInternalSessionStartTSList is to get all startTS of every transaction running in the current internal sessions
func (msm *MockSessionManager) GetInternalSessionStartTSList() []uint64 {
msm.mu.Lock()
defer msm.mu.Unlock()
ret := make([]uint64, 0, len(msm.internalSessions))
for internalSess := range msm.internalSessions {
se := internalSess.(sessionctx.Context)
sessVars := se.GetSessionVars()
sessVars.TxnCtxMu.Lock()
startTS := sessVars.TxnCtx.StartTS
sessVars.TxnCtxMu.Unlock()
ret = append(ret, startTS)
}
return ret
}
// KillNonFlashbackClusterConn implement SessionManager interface.
func (msm *MockSessionManager) KillNonFlashbackClusterConn() {
for _, se := range msm.Conn {
processInfo := se.ShowProcess()
ddl, ok := processInfo.StmtCtx.GetPlan().(*core.DDL)
if !ok {
msm.Kill(se.GetSessionVars().ConnectionID, false, false)
continue
}
_, ok = ddl.Statement.(*ast.FlashBackToTimestampStmt)
if !ok {
msm.Kill(se.GetSessionVars().ConnectionID, false, false)
continue
}
}
}
// CheckOldRunningTxn is to get all startTS of every transactions running in the current internal sessions
func (msm *MockSessionManager) CheckOldRunningTxn(job2ver map[int64]int64, job2ids map[int64]string) {
msm.mu.Lock()
for _, se := range msm.Conn {
session.RemoveLockDDLJobs(se, job2ver, job2ids, false)
}
msm.mu.Unlock()
}
|
package main
import (
"errors"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/jinzhu/configor"
log "github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v2"
)
/**
* ConfigurationLoader contains all methods to load/save configuration files
*/
type ConfigurationLoader struct {
}
/**
* The Project Configuration
*/
type ProjectConfigrationFile struct {
Commands []struct {
// name of the container
Name string
// description for the container
Description string
// the commands provided by the image
Provides []string
// docker image
Image string
// docker image tag
Tag string
// target directory to mount your project inside of the container
Directory string `default:"/project"`
// wrap the executed command inside of the container into a shell (ex. if you use globs)
Shell string `default:"none"`
// commands that should run in the container before the actual command is executed
BeforeScript []string `yaml:"before_script"`
// the command scope (internal use only) - global or project
Scope string
}
}
/**
* The EnvCLI Configuration
*/
type PropertyConfigurationFile struct {
ConfigurationPath string `default:""`
HTTPProxy string `default:""`
HTTPSProxy string `default:""`
}
/**
* Load the project config
*/
func (configurationLoader ConfigurationLoader) loadProjectConfig(configFile string) (ProjectConfigrationFile, error) {
var cfg ProjectConfigrationFile
if _, err := os.Stat(configFile); os.IsNotExist(err) {
return cfg, errors.New("project configuration file not found")
}
log.Debug("Loading project configuration file " + configFile)
configor.New(&configor.Config{Debug: false}).Load(&cfg, configFile)
return cfg, nil
}
/**
* Load the property config
*/
func (configurationLoader ConfigurationLoader) loadPropertyConfig(configFile string) (PropertyConfigurationFile, error) {
var cfg PropertyConfigurationFile
if _, err := os.Stat(configFile); os.IsNotExist(err) {
return cfg, errors.New("global property file not found")
}
log.Debug("Loading property configuration file " + configFile)
configor.New(&configor.Config{Debug: false}).Load(&cfg, configFile)
return cfg, nil
}
/**
* Save the global config
*/
func (configurationLoader ConfigurationLoader) savePropertyConfig(configFile string, cfg PropertyConfigurationFile) error {
log.Debug("Saving property configuration file " + configFile)
fileContent, err := yaml.Marshal(&cfg)
if err != nil {
return err
}
return ioutil.WriteFile(configFile, fileContent, 0600)
}
/**
* Get the execution directory
*/
func (configurationLoader ConfigurationLoader) getExecutionDirectory() string {
ex, err := os.Executable()
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Couldn't detect execution directory!")
return ""
}
return filepath.Dir(ex)
}
/**
* Get the working directory
*/
func (configurationLoader ConfigurationLoader) getWorkingDirectory() string {
workingDir, err := os.Getwd()
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Couldn't detect working directory!")
}
return workingDir
}
/**
* Get the project root directory by searching for the envcli config
*/
func (configurationLoader ConfigurationLoader) getProjectDirectory() string {
currentDirectory := configurationLoader.getWorkingDirectory()
var projectDirectory = ""
directoryParts := strings.Split(currentDirectory, string(os.PathSeparator))
for projectDirectory == "" {
if _, err := os.Stat(filepath.Join(currentDirectory, "/.envcli.yml")); err == nil {
return currentDirectory
}
if directoryParts[0]+"\\" == currentDirectory {
return ""
}
currentDirectory = filepath.Dir(currentDirectory)
}
return ""
}
/**
* Get the relative path of the project directory to the current working directory
*/
func (configurationLoader ConfigurationLoader) getRelativePathToWorkingDirectory() string {
currentDirectory := configurationLoader.getWorkingDirectory()
projectDirectory := configurationLoader.getProjectDirectory()
relativePath := strings.Replace(currentDirectory, projectDirectory, "", 1)
relativePath = strings.Replace(relativePath, "\\", "/", -1)
relativePath = strings.Trim(relativePath, "/")
return relativePath
}
/**
* Merge two configurations and keep the origin in the Scope
* TODO: Handle conflicts with a warning / by order project definition have precedence right now
*/
func (configurationLoader ConfigurationLoader) mergeConfigurations(configProject ProjectConfigrationFile, configGlobal ProjectConfigrationFile) ProjectConfigrationFile {
var cfg = ProjectConfigrationFile{}
for _, command := range configProject.Commands {
command.Scope = "Project"
cfg.Commands = append(cfg.Commands, command)
}
for _, command := range configGlobal.Commands {
command.Scope = "Global"
cfg.Commands = append(cfg.Commands, command)
}
return cfg
}
|
// Copyright 2018 The gitsync 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 hook_test
import (
"context"
"testing"
"github.com/seibert-media/gitsync/pkg/hook"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("hook", func() {
var (
h *hook.Hook
ctx context.Context
)
BeforeEach(func() {
h = &hook.Hook{}
ctx = context.Background()
})
Describe("New", func() {
It("does not return nil", func() {
Expect(hook.New("")).NotTo(BeNil())
})
})
Describe("Call", func() {
It("does not return error", func() {
Expect(h.Call(ctx)).To(BeNil())
})
})
})
func TestGitSync(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Hook Test Suite")
}
|
package cookiejar2
import (
"net/http"
"net/url"
)
type ImmutableCookieJar struct {
Inner http.CookieJar
}
func (i *ImmutableCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
// Immutable, prevent set cookies
}
func (i *ImmutableCookieJar) Cookies(u *url.URL) []*http.Cookie {
return i.Inner.Cookies(u)
}
|
package rules
import (
"github.com/bonjourmalware/melody/internal/filters"
"github.com/bonjourmalware/melody/internal/logging"
)
// Rules abstracts an array of Rule
type Rules []Rule
// Rule describes a parsed Rule object, used to match against a byte array
type Rule struct {
Name string
ID string
Tags map[string]string
Layer string
IPProtocol *ConditionsList
HTTP ParsedHTTPRule
TCP ParsedTCPRule
UDP ParsedUDPRule
ICMPv4 ParsedICMPv4Rule
ICMPv6 ParsedICMPv6Rule
IPs filters.IPRules
Ports filters.PortRules
Metadata Metadata
Additional map[string]string
MatchAll bool
}
// NewRule creates a Rule from a RawRule
func NewRule(rawRule RawRule) Rule {
var portsList = filters.PortRules{
WhitelistedPorts: filters.PortRanges{},
BlacklistedPorts: filters.PortRanges{},
}
var ipsList = filters.IPRules{
WhitelistedIPs: filters.IPRanges{},
BlacklistedIPs: filters.IPRanges{},
}
ipsList.ParseRules(rawRule.Whitelist.IPs, rawRule.Blacklist.IPs)
portsList.ParseRules(rawRule.Whitelist.Ports, rawRule.Blacklist.Ports)
parsedIPProtocol, err := rawRule.IPProtocol.ParseList()
if err != nil {
logging.Errors.Printf("failed to parse rule '%s' : %s", rawRule.Metadata.ID, err)
return Rule{}
}
rule := Rule{
Tags: rawRule.Tags,
IPProtocol: parsedIPProtocol,
ID: rawRule.Metadata.ID,
Layer: rawRule.Layer,
Ports: portsList,
IPs: ipsList,
Metadata: rawRule.Metadata,
Additional: rawRule.Additional,
}
return rule
}
// Filter is a helper filtering out one or multiple Rule according to a function returning true or false
// Similar to array.filter() in python
func (rules Rules) Filter(fn func(rule Rule) bool) Rules {
res := Rules{}
for _, rule := range rules {
if fn(rule) {
res = append(res, rule)
}
}
return res
}
// Parse parses raw rules to create a set of rules as Rules
//func (rawRules RawRules) Parse() Rules {
// rules := Rules{}
// for rname, rule := range rawRules {
// parsedRule := rule.Parse()
// parsedRule.Name = rname
// rules = append(rules, parsedRule)
// }
//
// return rules
//}
|
package marketdata
import "time"
type MarketData struct {
MarketName string `json:"marketname"`
High float64 `json:"high"`
Low float64 `json:"low"`
Volume float64 `json:"volume"`
Created time.Time `json:"created"`
Timestamp time.Time `json:"timestamp"`
}
|
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apiserver
import (
"context"
"encoding/json"
"fmt"
"reflect"
"testing"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apiextensions-apiserver/test/integration/fixtures"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
genericfeatures "k8s.io/apiserver/pkg/features"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/client-go/dynamic"
featuregatetesting "k8s.io/component-base/featuregate/testing"
apiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
"k8s.io/kubernetes/test/integration/framework"
)
// TestApplyCRDNoSchema tests that CRDs and CRs can both be applied to with a PATCH request with the apply content type
// when there is no validation field provided.
func TestApplyCRDNoSchema(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)()
server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), nil, framework.SharedEtcd())
if err != nil {
t.Fatal(err)
}
defer server.TearDownFn()
config := server.ClientConfig
apiExtensionClient, err := clientset.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
noxuDefinition := fixtures.NewMultipleVersionNoxuCRD(apiextensionsv1beta1.ClusterScoped)
noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient)
if err != nil {
t.Fatal(err)
}
kind := noxuDefinition.Spec.Names.Kind
apiVersion := noxuDefinition.Spec.Group + "/" + noxuDefinition.Spec.Version
name := "mytest"
rest := apiExtensionClient.Discovery().RESTClient()
yamlBody := []byte(fmt.Sprintf(`
apiVersion: %s
kind: %s
metadata:
name: %s
spec:
replicas: 1`, apiVersion, kind, name))
result, err := rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to create custom resource with apply: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 1)
// Patch object to change the number of replicas
result, err = rest.Patch(types.MergePatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Body([]byte(`{"spec":{"replicas": 5}}`)).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to update number of replicas with merge patch: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 5)
// Re-apply, we should get conflicts now, since the number of replicas was changed.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err == nil {
t.Fatalf("Expecting to get conflicts when applying object after updating replicas, got no error: %s", result)
}
status, ok := err.(*apierrors.StatusError)
if !ok {
t.Fatalf("Expecting to get conflicts as API error")
}
if len(status.Status().Details.Causes) != 1 {
t.Fatalf("Expecting to get one conflict when applying object after updating replicas, got: %v", status.Status().Details.Causes)
}
// Re-apply with force, should work fine.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("force", "true").
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to apply object with force after updating replicas: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 1)
}
// TestApplyCRDStructuralSchema tests that when a CRD has a structural schema in its validation field,
// it will be used to construct the CR schema used by apply.
func TestApplyCRDStructuralSchema(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)()
server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), nil, framework.SharedEtcd())
if err != nil {
t.Fatal(err)
}
defer server.TearDownFn()
config := server.ClientConfig
apiExtensionClient, err := clientset.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
noxuDefinition := fixtures.NewMultipleVersionNoxuCRD(apiextensionsv1beta1.ClusterScoped)
var c apiextensionsv1beta1.CustomResourceValidation
err = json.Unmarshal([]byte(`{
"openAPIV3Schema": {
"type": "object",
"properties": {
"spec": {
"type": "object",
"x-kubernetes-preserve-unknown-fields": true,
"properties": {
"cronSpec": {
"type": "string",
"pattern": "^(\\d+|\\*)(/\\d+)?(\\s+(\\d+|\\*)(/\\d+)?){4}$"
},
"ports": {
"type": "array",
"x-kubernetes-list-map-keys": [
"containerPort",
"protocol"
],
"x-kubernetes-list-type": "map",
"items": {
"properties": {
"containerPort": {
"format": "int32",
"type": "integer"
},
"hostIP": {
"type": "string"
},
"hostPort": {
"format": "int32",
"type": "integer"
},
"name": {
"type": "string"
},
"protocol": {
"type": "string"
}
},
"required": [
"containerPort",
"protocol"
],
"type": "object"
}
}
}
}
}
}
}`), &c)
if err != nil {
t.Fatal(err)
}
noxuDefinition.Spec.Validation = &c
falseBool := false
noxuDefinition.Spec.PreserveUnknownFields = &falseBool
noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient)
if err != nil {
t.Fatal(err)
}
kind := noxuDefinition.Spec.Names.Kind
apiVersion := noxuDefinition.Spec.Group + "/" + noxuDefinition.Spec.Version
name := "mytest"
rest := apiExtensionClient.Discovery().RESTClient()
yamlBody := []byte(fmt.Sprintf(`
apiVersion: %s
kind: %s
metadata:
name: %s
finalizers:
- test-finalizer
spec:
cronSpec: "* * * * */5"
replicas: 1
ports:
- name: x
containerPort: 80
protocol: TCP`, apiVersion, kind, name))
result, err := rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to create custom resource with apply: %v:\n%v", err, string(result))
}
verifyNumFinalizers(t, result, 1)
verifyFinalizersIncludes(t, result, "test-finalizer")
verifyReplicas(t, result, 1)
verifyNumPorts(t, result, 1)
// Patch object to add another finalizer to the finalizers list
result, err = rest.Patch(types.MergePatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Body([]byte(`{"metadata":{"finalizers":["test-finalizer","another-one"]}}`)).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to add finalizer with merge patch: %v:\n%v", err, string(result))
}
verifyNumFinalizers(t, result, 2)
verifyFinalizersIncludes(t, result, "test-finalizer")
verifyFinalizersIncludes(t, result, "another-one")
// Re-apply the same config, should work fine, since finalizers should have the list-type extension 'set'.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
SetHeader("Accept", "application/json").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to apply same config after adding a finalizer: %v:\n%v", err, string(result))
}
verifyNumFinalizers(t, result, 2)
verifyFinalizersIncludes(t, result, "test-finalizer")
verifyFinalizersIncludes(t, result, "another-one")
// Patch object to change the number of replicas
result, err = rest.Patch(types.MergePatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Body([]byte(`{"spec":{"replicas": 5}}`)).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to update number of replicas with merge patch: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 5)
// Re-apply, we should get conflicts now, since the number of replicas was changed.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err == nil {
t.Fatalf("Expecting to get conflicts when applying object after updating replicas, got no error: %s", result)
}
status, ok := err.(*apierrors.StatusError)
if !ok {
t.Fatalf("Expecting to get conflicts as API error")
}
if len(status.Status().Details.Causes) != 1 {
t.Fatalf("Expecting to get one conflict when applying object after updating replicas, got: %v", status.Status().Details.Causes)
}
// Re-apply with force, should work fine.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("force", "true").
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to apply object with force after updating replicas: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 1)
// New applier tries to edit an existing list item, we should get conflicts.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test_2").
Body([]byte(fmt.Sprintf(`
apiVersion: %s
kind: %s
metadata:
name: %s
spec:
ports:
- name: "y"
containerPort: 80
protocol: TCP`, apiVersion, kind, name))).
DoRaw(context.TODO())
if err == nil {
t.Fatalf("Expecting to get conflicts when a different applier updates existing list item, got no error: %s", result)
}
status, ok = err.(*apierrors.StatusError)
if !ok {
t.Fatalf("Expecting to get conflicts as API error")
}
if len(status.Status().Details.Causes) != 1 {
t.Fatalf("Expecting to get one conflict when a different applier updates existing list item, got: %v", status.Status().Details.Causes)
}
// New applier tries to add a new list item, should work fine.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test_2").
Body([]byte(fmt.Sprintf(`
apiVersion: %s
kind: %s
metadata:
name: %s
spec:
ports:
- name: "y"
containerPort: 8080
protocol: TCP`, apiVersion, kind, name))).
SetHeader("Accept", "application/json").
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to add a new list item to the object as a different applier: %v:\n%v", err, string(result))
}
verifyNumPorts(t, result, 2)
}
// TestApplyCRDNonStructuralSchema tests that when a CRD has a non-structural schema in its validation field,
// it will be used to construct the CR schema used by apply, but any non-structural parts of the schema will be treated as
// nested maps (same as a CRD without a schema)
func TestApplyCRDNonStructuralSchema(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)()
server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), nil, framework.SharedEtcd())
if err != nil {
t.Fatal(err)
}
defer server.TearDownFn()
config := server.ClientConfig
apiExtensionClient, err := clientset.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
noxuDefinition := fixtures.NewNoxuCustomResourceDefinition(apiextensionsv1beta1.ClusterScoped)
var c apiextensionsv1beta1.CustomResourceValidation
err = json.Unmarshal([]byte(`{
"openAPIV3Schema": {
"type": "object",
"properties": {
"spec": {
"anyOf": [
{
"type": "object",
"properties": {
"cronSpec": {
"type": "string",
"pattern": "^(\\d+|\\*)(/\\d+)?(\\s+(\\d+|\\*)(/\\d+)?){4}$"
}
}
}, {
"type": "string"
}
]
}
}
}
}`), &c)
if err != nil {
t.Fatal(err)
}
noxuDefinition.Spec.Validation = &c
noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient)
if err != nil {
t.Fatal(err)
}
kind := noxuDefinition.Spec.Names.Kind
apiVersion := noxuDefinition.Spec.Group + "/" + noxuDefinition.Spec.Version
name := "mytest"
rest := apiExtensionClient.Discovery().RESTClient()
yamlBody := []byte(fmt.Sprintf(`
apiVersion: %s
kind: %s
metadata:
name: %s
finalizers:
- test-finalizer
spec:
cronSpec: "* * * * */5"
replicas: 1`, apiVersion, kind, name))
result, err := rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to create custom resource with apply: %v:\n%v", err, string(result))
}
verifyNumFinalizers(t, result, 1)
verifyFinalizersIncludes(t, result, "test-finalizer")
verifyReplicas(t, result, 1.0)
// Patch object to add another finalizer to the finalizers list
result, err = rest.Patch(types.MergePatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Body([]byte(`{"metadata":{"finalizers":["test-finalizer","another-one"]}}`)).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to add finalizer with merge patch: %v:\n%v", err, string(result))
}
verifyNumFinalizers(t, result, 2)
verifyFinalizersIncludes(t, result, "test-finalizer")
verifyFinalizersIncludes(t, result, "another-one")
// Re-apply the same config, should work fine, since finalizers should have the list-type extension 'set'.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
SetHeader("Accept", "application/json").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to apply same config after adding a finalizer: %v:\n%v", err, string(result))
}
verifyNumFinalizers(t, result, 2)
verifyFinalizersIncludes(t, result, "test-finalizer")
verifyFinalizersIncludes(t, result, "another-one")
// Patch object to change the number of replicas
result, err = rest.Patch(types.MergePatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Body([]byte(`{"spec":{"replicas": 5}}`)).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to update number of replicas with merge patch: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 5.0)
// Re-apply, we should get conflicts now, since the number of replicas was changed.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err == nil {
t.Fatalf("Expecting to get conflicts when applying object after updating replicas, got no error: %s", result)
}
status, ok := err.(*apierrors.StatusError)
if !ok {
t.Fatalf("Expecting to get conflicts as API error")
}
if len(status.Status().Details.Causes) != 1 {
t.Fatalf("Expecting to get one conflict when applying object after updating replicas, got: %v", status.Status().Details.Causes)
}
// Re-apply with force, should work fine.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("force", "true").
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to apply object with force after updating replicas: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 1.0)
}
// verifyNumFinalizers checks that len(.metadata.finalizers) == n
func verifyNumFinalizers(t *testing.T, b []byte, n int) {
obj := unstructured.Unstructured{}
err := obj.UnmarshalJSON(b)
if err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if actual, expected := len(obj.GetFinalizers()), n; actual != expected {
t.Fatalf("expected %v finalizers but got %v:\n%v", expected, actual, string(b))
}
}
// verifyFinalizersIncludes checks that .metadata.finalizers includes e
func verifyFinalizersIncludes(t *testing.T, b []byte, e string) {
obj := unstructured.Unstructured{}
err := obj.UnmarshalJSON(b)
if err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
for _, a := range obj.GetFinalizers() {
if a == e {
return
}
}
t.Fatalf("expected finalizers to include %q but got: %v", e, obj.GetFinalizers())
}
// verifyReplicas checks that .spec.replicas == r
func verifyReplicas(t *testing.T, b []byte, r int) {
obj := unstructured.Unstructured{}
err := obj.UnmarshalJSON(b)
if err != nil {
t.Fatalf("failed to find replicas number in response: %v:\n%v", err, string(b))
}
spec, ok := obj.Object["spec"]
if !ok {
t.Fatalf("failed to find replicas number in response:\n%v", string(b))
}
specMap, ok := spec.(map[string]interface{})
if !ok {
t.Fatalf("failed to find replicas number in response:\n%v", string(b))
}
replicas, ok := specMap["replicas"]
if !ok {
t.Fatalf("failed to find replicas number in response:\n%v", string(b))
}
replicasNumber, ok := replicas.(int64)
if !ok {
t.Fatalf("failed to find replicas number in response: expected int64 but got: %v", reflect.TypeOf(replicas))
}
if actual, expected := replicasNumber, int64(r); actual != expected {
t.Fatalf("expected %v ports but got %v:\n%v", expected, actual, string(b))
}
}
// verifyNumPorts checks that len(.spec.ports) == n
func verifyNumPorts(t *testing.T, b []byte, n int) {
obj := unstructured.Unstructured{}
err := obj.UnmarshalJSON(b)
if err != nil {
t.Fatalf("failed to find ports list in response: %v:\n%v", err, string(b))
}
spec, ok := obj.Object["spec"]
if !ok {
t.Fatalf("failed to find ports list in response:\n%v", string(b))
}
specMap, ok := spec.(map[string]interface{})
if !ok {
t.Fatalf("failed to find ports list in response:\n%v", string(b))
}
ports, ok := specMap["ports"]
if !ok {
t.Fatalf("failed to find ports list in response:\n%v", string(b))
}
portsList, ok := ports.([]interface{})
if !ok {
t.Fatalf("failed to find ports list in response: expected array but got: %v", reflect.TypeOf(ports))
}
if actual, expected := len(portsList), n; actual != expected {
t.Fatalf("expected %v ports but got %v:\n%v", expected, actual, string(b))
}
}
// TestApplyCRDUnhandledSchema tests that when a CRD has a schema that kube-openapi ToProtoModels cannot handle correctly,
// apply falls back to non-schema behavior
func TestApplyCRDUnhandledSchema(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)()
server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), nil, framework.SharedEtcd())
if err != nil {
t.Fatal(err)
}
defer server.TearDownFn()
config := server.ClientConfig
apiExtensionClient, err := clientset.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
noxuDefinition := fixtures.NewNoxuCustomResourceDefinition(apiextensionsv1beta1.ClusterScoped)
// This is a schema that kube-openapi ToProtoModels does not handle correctly.
// https://github.com/kubernetes/kubernetes/blob/38752f7f99869ed65fb44378360a517649dc2f83/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go#L184
var c apiextensionsv1beta1.CustomResourceValidation
err = json.Unmarshal([]byte(`{
"openAPIV3Schema": {
"properties": {
"TypeFooBar": {
"type": "array"
}
}
}
}`), &c)
if err != nil {
t.Fatal(err)
}
noxuDefinition.Spec.Validation = &c
noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient)
if err != nil {
t.Fatal(err)
}
kind := noxuDefinition.Spec.Names.Kind
apiVersion := noxuDefinition.Spec.Group + "/" + noxuDefinition.Spec.Version
name := "mytest"
rest := apiExtensionClient.Discovery().RESTClient()
yamlBody := []byte(fmt.Sprintf(`
apiVersion: %s
kind: %s
metadata:
name: %s
spec:
replicas: 1`, apiVersion, kind, name))
result, err := rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to create custom resource with apply: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 1)
// Patch object to change the number of replicas
result, err = rest.Patch(types.MergePatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Body([]byte(`{"spec":{"replicas": 5}}`)).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to update number of replicas with merge patch: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 5)
// Re-apply, we should get conflicts now, since the number of replicas was changed.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err == nil {
t.Fatalf("Expecting to get conflicts when applying object after updating replicas, got no error: %s", result)
}
status, ok := err.(*apierrors.StatusError)
if !ok {
t.Fatalf("Expecting to get conflicts as API error")
}
if len(status.Status().Details.Causes) != 1 {
t.Fatalf("Expecting to get one conflict when applying object after updating replicas, got: %v", status.Status().Details.Causes)
}
// Re-apply with force, should work fine.
result, err = rest.Patch(types.ApplyPatchType).
AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural).
Name(name).
Param("force", "true").
Param("fieldManager", "apply_test").
Body(yamlBody).
DoRaw(context.TODO())
if err != nil {
t.Fatalf("failed to apply object with force after updating replicas: %v:\n%v", err, string(result))
}
verifyReplicas(t, result, 1)
}
|
/*
Copyright 2021 CodeNotary, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"context"
"io/ioutil"
"os"
"path"
"testing"
"github.com/rs/xid"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
func TestNewUUID(t *testing.T) {
id, err := getOrSetUUID("./", "./defaultDb")
if err != nil {
t.Fatalf("error creating UUID, %v", err)
}
defer os.RemoveAll(IDENTIFIER_FNAME)
if !fileExists(IDENTIFIER_FNAME) {
t.Errorf("uuid file not created, %s", err)
}
uuid := NewUUIDContext(id)
if id.Compare(uuid.UUID) != 0 {
t.Fatalf("NewUUIDContext error expected %v, got %v", id, uuid.UUID)
}
}
func TestExistingUUID(t *testing.T) {
x, _ := xid.FromString("bs6c1kn1lu5qfesu061g")
ioutil.WriteFile(IDENTIFIER_FNAME, x.Bytes(), os.ModePerm)
id, err := getOrSetUUID("./", "./defaultDb")
if err != nil {
t.Fatalf("error creating UUID, %v", err)
}
defer os.RemoveAll(IDENTIFIER_FNAME)
if !fileExists(IDENTIFIER_FNAME) {
t.Errorf("uuid file not created, %s", err)
}
uuid := NewUUIDContext(id)
if id.Compare(uuid.UUID) != 0 {
t.Fatalf("NewUUIDContext error expected %v, got %v", id, uuid.UUID)
}
}
func TestMigrateUUID(t *testing.T) {
defaultDbDir := "defaultDb"
if err := os.Mkdir(defaultDbDir, os.ModePerm); err != nil {
t.Fatalf("error in creating default db dir")
}
defer os.Remove(defaultDbDir)
fileInDefaultDbDir := path.Join(defaultDbDir, IDENTIFIER_FNAME)
x, _ := xid.FromString("bs6c1kn1lu5qfesu061g")
ioutil.WriteFile(fileInDefaultDbDir, x.Bytes(), os.ModePerm)
id, err := getOrSetUUID("./", defaultDbDir)
if err != nil {
t.Fatalf("error creating UUID, %v", err)
}
defer os.RemoveAll(fileInDefaultDbDir)
defer os.RemoveAll(IDENTIFIER_FNAME)
if !fileExists(IDENTIFIER_FNAME) {
t.Errorf("uuid file not created, %s", err)
}
if fileExists(fileInDefaultDbDir) {
t.Errorf("uuid file not moved, %s", err)
}
uuid := NewUUIDContext(id)
if id.Compare(uuid.UUID) != 0 {
t.Fatalf("NewUUIDContext error expected %v, got %v", id, uuid.UUID)
}
}
func TestUUIDContextSetter(t *testing.T) {
id, err := getOrSetUUID("./", "./defaultDb")
if err != nil {
t.Fatalf("error creating UUID, %v", err)
}
defer os.RemoveAll(IDENTIFIER_FNAME)
uuid := NewUUIDContext(id)
transportStream := &mockServerTransportStream{}
srv := &grpc.UnaryServerInfo{}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
ctxUUID, ok := transportStream.SentHeader[SERVER_UUID_HEADER]
if !ok {
t.Fatalf("error setting uuid")
}
x, err := xid.FromString(ctxUUID[0])
if err != nil {
t.Fatalf("error initializing xid from string %s", ctxUUID[0])
}
if uuid.UUID.Compare(x) != 0 {
t.Fatalf("set uuid does is not equal to transmitted uuid")
}
return req, nil
}
var req interface{}
ctx := grpc.NewContextWithServerTransportStream(context.Background(), transportStream)
_, err = uuid.UUIDContextSetter(ctx, req, srv, handler)
if err != nil {
t.Fatalf("error setting uuid UUID, %v", err)
}
}
func TestUUIDStreamContextSetter(t *testing.T) {
id, err := getOrSetUUID("./", "./defaultDb")
if err != nil {
t.Fatalf("error creating UUID, %v", err)
}
defer os.RemoveAll(IDENTIFIER_FNAME)
uuid := NewUUIDContext(id)
srv := grpc.StreamServerInfo{}
ss := mockServerStream{}
handler := func(srv interface{}, stream grpc.ServerStream) error {
ctxUUID, ok := ss.SentHeader[SERVER_UUID_HEADER]
if !ok {
t.Fatalf("error setting uuid")
}
x, err := xid.FromString(ctxUUID[0])
if err != nil {
t.Fatalf("error initializing xid from string %s", ctxUUID[0])
}
if uuid.UUID.Compare(x) != 0 {
t.Fatalf("set uuid does is not equal to transmitted uuid")
}
return nil
}
var req interface{}
err = uuid.UUIDStreamContextSetter(req, &ss, &srv, handler)
if err != nil {
t.Fatalf("error setting uuid UUID, %v", err)
}
}
// implement ServerTransportStream
type mockServerTransportStream struct {
SentHeader metadata.MD
}
func (r *mockServerTransportStream) Method() string { return "" }
func (r *mockServerTransportStream) SetHeader(md metadata.MD) error { return nil }
func (r *mockServerTransportStream) SendHeader(md metadata.MD) error { r.SentHeader = md; return nil }
func (r *mockServerTransportStream) SetTrailer(md metadata.MD) error { return nil }
// implement ServerStream
type mockServerStream struct {
SentHeader metadata.MD
ctx context.Context
}
func (r *mockServerStream) SetHeader(md metadata.MD) error { return nil }
func (r *mockServerStream) SendHeader(md metadata.MD) error { r.SentHeader = md; return nil }
func (r *mockServerStream) SetTrailer(md metadata.MD) {}
func (r *mockServerStream) Context() context.Context { return r.ctx }
func (r *mockServerStream) SendMsg(m interface{}) error { return nil }
func (r *mockServerStream) RecvMsg(m interface{}) error { return nil }
|
package main
import (
"fmt"
"sync"
)
// 定义一个协程计数器
var wg sync.WaitGroup
func test() {
// 这是主进程执行的
for i := 0; i < 1000; i++ {
fmt.Println("test1 你好golang", i)
//time.Sleep(time.Millisecond * 100)
}
// 协程计数器减1
wg.Done()
}
func test2() {
// 这是主进程执行的
for i := 0; i < 1000; i++ {
fmt.Println("test2 你好golang", i)
//time.Sleep(time.Millisecond * 100)
}
// 协程计数器减1
wg.Done()
}
func main() {
// 通过go关键字,就可以直接开启一个协程
wg.Add(1)
go test()
// 协程计数器加1
wg.Add(1)
go test2()
// 这是主进程执行的
for i := 0; i < 1000; i++ {
fmt.Println("main 你好golang", i)
//time.Sleep(time.Millisecond * 100)
}
// 等待所有的协程执行完毕
wg.Wait()
fmt.Println("主线程退出")
}
|
package service
import (
"context"
"fmt"
"net/http"
"github.com/gofrs/uuid"
"github.com/go-ocf/cloud/cloud2cloud-connector/store"
"golang.org/x/oauth2"
)
func (rh *RequestHandler) HandleLinkedAccount(ctx context.Context, data LinkedAccountData, authCode string) (LinkedAccountData, error) {
var oauth oauth2.Config
switch data.State {
case LinkedAccountState_START:
oauth = rh.originCloud.ToOAuth2Config()
oauth.RedirectURL = rh.oauthCallback
ctx = context.WithValue(ctx, oauth2.HTTPClient, http.DefaultClient)
token, err := oauth.Exchange(ctx, authCode)
if err != nil {
return data, fmt.Errorf("cannot exchange origin cloud authorization code for access token: %v", err)
}
data.LinkedAccount.OriginCloud.AccessToken = store.AccessToken(token.AccessToken)
data.LinkedAccount.OriginCloud.Expiry = token.Expiry
data.LinkedAccount.OriginCloud.RefreshToken = token.RefreshToken
data.State = LinkedAccountState_PROVISIONED_ORIGIN_CLOUD
return data, nil
case LinkedAccountState_PROVISIONED_ORIGIN_CLOUD:
var h LinkedCloudHandler
err := rh.store.LoadLinkedClouds(ctx, store.Query{ID: data.LinkedAccount.TargetCloud.LinkedCloudID}, &h)
if err != nil {
return data, fmt.Errorf("cannot find linked cloud with ID %v: %v", data.LinkedAccount.TargetCloud.LinkedCloudID, err)
}
oauth = h.linkedCloud.ToOAuth2Config()
oauth.RedirectURL = rh.oauthCallback
ctx = context.WithValue(ctx, oauth2.HTTPClient, http.DefaultClient)
token, err := oauth.Exchange(ctx, authCode)
if err != nil {
return data, fmt.Errorf("cannot exchange target cloud authorization code for access token: %v", err)
}
data.LinkedAccount.TargetCloud.AccessToken = store.AccessToken(token.AccessToken)
data.LinkedAccount.TargetCloud.Expiry = token.Expiry
data.LinkedAccount.TargetCloud.RefreshToken = token.RefreshToken
data.State = LinkedAccountState_PROVISIONED_TARGET_CLOUD
return data, nil
case LinkedAccountState_PROVISIONED_TARGET_CLOUD:
return data, nil
}
return data, fmt.Errorf("unknown state %v", data.State)
}
func (rh *RequestHandler) oAuthCallback(w http.ResponseWriter, r *http.Request) (int, error) {
authCode := r.FormValue("code")
state := r.FormValue("state")
linkedAccountData, ok := rh.provisionCache.Get(string(state))
if !ok {
return http.StatusBadRequest, fmt.Errorf("invalid/expired OAuth state")
}
rh.provisionCache.Delete(string(state))
data := linkedAccountData.(LinkedAccountData)
newData, err := rh.HandleLinkedAccount(r.Context(), data, authCode)
if err != nil {
return http.StatusBadRequest, err
}
switch newData.State {
case LinkedAccountState_PROVISIONED_ORIGIN_CLOUD:
return rh.HandleOAuth(w, r, newData)
case LinkedAccountState_PROVISIONED_TARGET_CLOUD:
id, err := uuid.NewV4()
if err != nil {
return http.StatusInternalServerError, err
}
newData.LinkedAccount.ID = id.String()
err = rh.store.InsertLinkedAccount(r.Context(), newData.LinkedAccount)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("cannot store linked account for url %v: %v", data.LinkedAccount.TargetURL, err)
}
err = rh.subManager.StartSubscriptions(r.Context(), newData.LinkedAccount)
if err != nil {
rh.store.RemoveLinkedAccount(r.Context(), newData.LinkedAccount.ID)
return http.StatusBadRequest, fmt.Errorf("cannot start subscriptions %v: %v", data.LinkedAccount.TargetURL, err)
}
return http.StatusOK, nil
}
return http.StatusInternalServerError, fmt.Errorf("invalid linked account state - %v", newData.State)
}
func (rh *RequestHandler) OAuthCallback(w http.ResponseWriter, r *http.Request) {
statusCode, err := rh.oAuthCallback(w, r)
if err != nil {
logAndWriteErrorResponse(fmt.Errorf("cannot process oauth callback: %v", err), statusCode, w)
}
}
|
package main
import "fmt"
func main() {
fmt.Println("Printing all even numbers from 1 to 100")
for i := 1; i <= 100; i++ {
if i % 2 == 0 {
fmt.Print("\t", i)
}
}
fmt.Println()
fmt.Println("Printing all odd numbers from 1 to 100")
for i := 1; i <= 100; i++ {
if i % 2 != 0 {
fmt.Print("\t", i)
}
}
fmt.Println()
}
|
package ansi_test
import (
"fmt"
"testing"
"unicode/utf8"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/jcorbin/anansi/ansi"
)
func TestDecodeEscape(t *testing.T) {
type anRead struct {
e ansi.Escape
a []byte
n int
}
type utRead struct {
r rune
m int
}
type ev struct {
anRead
utRead
}
tcs := []struct {
in string
out []ev
}{
{"", nil},
{"hi", []ev{
{anRead{}, utRead{'h', 1}},
{anRead{}, utRead{'i', 1}},
}},
{"hi\x7fello", []ev{
{anRead{}, utRead{'h', 1}},
{anRead{}, utRead{'i', 1}},
{anRead{}, utRead{'\x7f', 1}},
{anRead{}, utRead{'e', 1}},
{anRead{}, utRead{'l', 1}},
{anRead{}, utRead{'l', 1}},
{anRead{}, utRead{'o', 1}},
}},
{"iab\x1b\x1b\x18jk", []ev{
{anRead{}, utRead{'i', 1}},
{anRead{}, utRead{'a', 1}},
{anRead{}, utRead{'b', 1}},
{anRead{}, utRead{'\x1b', 1}},
{anRead{0, nil, 2}, utRead{'j', 1}},
{anRead{}, utRead{'k', 1}},
}},
{"\x1b>num\x1b=app", []ev{
{anRead{ansi.Escape(0xEF3E), nil, 2}, utRead{}},
{anRead{}, utRead{'n', 1}},
{anRead{}, utRead{'u', 1}},
{anRead{}, utRead{'m', 1}},
{anRead{ansi.Escape(0xEF3D), nil, 2}, utRead{}},
{anRead{}, utRead{'a', 1}},
{anRead{}, utRead{'p', 1}},
{anRead{}, utRead{'p', 1}},
}},
{"\x1baint", []ev{
{anRead{ansi.Escape(0xEF61), nil, 2}, utRead{}},
{anRead{}, utRead{'i', 1}},
{anRead{}, utRead{'n', 1}},
{anRead{}, utRead{'t', 1}},
}},
{"\x1b(B$", []ev{
{anRead{ansi.Escape(0xEF28), []byte("B"), 3}, utRead{}},
{anRead{}, utRead{'$', 1}},
}},
{"\x1b\x03(B$", []ev{
{anRead{0, nil, 0}, utRead{'\x03', 1}},
{anRead{ansi.Escape(0xEF28), []byte("B"), 3}, utRead{}},
{anRead{}, utRead{'$', 1}},
}},
{"\x1b\x03(\x04B$", []ev{
{anRead{0, nil, 0}, utRead{'\x03', 1}},
{anRead{0, nil, 0}, utRead{'\x04', 1}},
{anRead{ansi.Escape(0xEF28), []byte("B"), 3}, utRead{}},
{anRead{}, utRead{'$', 1}},
}},
{"\x1bø", []ev{
{anRead{ansi.Escape(0xEF78), nil, 3}, utRead{}},
}},
{"\x1b“(B$", []ev{
{anRead{}, utRead{'“', 3}},
{anRead{ansi.Escape(0xEF28), []byte("B"), 3}, utRead{}},
{anRead{}, utRead{'$', 1}},
}},
{"\x1b“(”B$", []ev{
{anRead{}, utRead{'“', 3}},
{anRead{}, utRead{'”', 3}},
{anRead{ansi.Escape(0xEF28), []byte("B"), 3}, utRead{}},
{anRead{}, utRead{'$', 1}},
}},
{"\x1b[31mred", []ev{
{anRead{ansi.Escape(0xEFED), []byte("31"), 5}, utRead{}},
{anRead{}, utRead{'r', 1}},
{anRead{}, utRead{'e', 1}},
{anRead{}, utRead{'d', 1}},
}},
{"\u009b31mred", []ev{
{anRead{ansi.Escape(0xEFED), []byte("31"), 5}, utRead{}},
{anRead{}, utRead{'r', 1}},
{anRead{}, utRead{'e', 1}},
{anRead{}, utRead{'d', 1}},
}},
{"(\x1bPdemo\x1b\\)", []ev{
{anRead{}, utRead{'(', 1}},
{anRead{ansi.Escape(0x90), []byte("demo"), 8}, utRead{}},
{anRead{}, utRead{')', 1}},
}},
{"(\u0090demo\u009C)", []ev{
{anRead{}, utRead{'(', 1}},
{anRead{ansi.Escape(0x90), []byte("demo"), 8}, utRead{}},
{anRead{}, utRead{')', 1}},
}},
}
const sanity = 100
for _, tc := range tcs {
t.Run(fmt.Sprintf("%q", tc.in), func(t *testing.T) {
i := 0
var out []ev
for p := []byte(tc.in); len(p) > 0; i++ {
if i > sanity {
require.Fail(t, "sanity exhausted")
}
var ev ev
ev.e, ev.a, ev.n = ansi.DecodeEscape(p)
p = p[ev.n:]
if ev.e == 0 {
ev.r, ev.m = utf8.DecodeRune(p)
p = p[ev.m:]
}
out = append(out, ev)
}
assert.Equal(t, tc.out, out)
})
}
}
func TestDecodeNumber(t *testing.T) {
for _, tc := range []struct {
in string
out int
rem string
}{
{"1", 1, ""},
{"2", 2, ""},
{"10", 10, ""},
{"20", 20, ""},
{"13", 13, ""},
{"24", 24, ""},
{";1", 1, ""},
{";2", 2, ""},
{";10", 10, ""},
{";20", 20, ""},
{";13", 13, ""},
{";24", 24, ""},
{"-1", -1, ""},
{"-2", -2, ""},
{"-10", -10, ""},
{"-20", -20, ""},
{"-13", -13, ""},
{"-24", -24, ""},
{"1;42", 1, ";42"},
{"2;42", 2, ";42"},
{"10;42", 10, ";42"},
{"20;42", 20, ";42"},
{"13;42", 13, ";42"},
{"24;42", 24, ";42"},
} {
t.Run(tc.in, func(t *testing.T) {
p := []byte(tc.in)
v, n, err := ansi.DecodeNumber(p)
if assert.NoError(t, err, "unexpected decode error") {
assert.Equal(t, tc.out, v, "expected value")
assert.Equal(t, tc.rem, string(p[n:]), "expected remain")
}
})
}
}
func TestDecodeSGR_roundtrips(t *testing.T) {
for _, tc := range []struct {
attr ansi.SGRAttr
str string
}{
{ansi.SGRAttrClear, "\x1b[0m"},
{ansi.SGRAttrNegative, "\x1b[7m"},
{ansi.SGRRed.FG(), "\x1b[31m"},
{ansi.SGRBrightGreen.FG(), "\x1b[92m"},
{ansi.SGRCube20.FG(), "\x1b[38;5;20m"},
{ansi.SGRGray10.FG(), "\x1b[38;5;241m"},
{ansi.RGB(10, 20, 30).FG(), "\x1b[38;2;10;20;30m"},
{ansi.SGRRed.BG(), "\x1b[41m"},
{ansi.SGRBrightGreen.BG(), "\x1b[102m"},
{ansi.SGRCube20.BG(), "\x1b[48;5;20m"},
{ansi.SGRGray10.BG(), "\x1b[48;5;241m"},
{ansi.RGB(10, 20, 30).BG(), "\x1b[48;2;10;20;30m"},
{ansi.SGRAttrBold | ansi.SGRAttrNegative, "\x1b[1;7m"},
{ansi.SGRAttrClear | ansi.SGRAttrBold | ansi.SGRAttrNegative, "\x1b[0;1;7m"},
{ansi.SGRRed.FG() | ansi.SGRRed.BG(), "\x1b[31;41m"},
{ansi.SGRAttrClear | ansi.SGRRed.FG() | ansi.SGRGreen.BG(), "\x1b[0;31;42m"},
{ansi.SGRAttrBold | ansi.SGRRed.FG() | ansi.SGRGreen.BG(), "\x1b[1;31;42m"},
{ansi.SGRAttrClear | ansi.SGRAttrBold | ansi.SGRRed.FG() | ansi.SGRGreen.BG(), "\x1b[0;1;31;42m"},
{ansi.SGRAttrClear | ansi.SGRAttrBold | ansi.SGRRed.To24Bit().FG() | ansi.SGRGreen.To24Bit().BG(), "\x1b[0;1;38;2;128;0;0;48;2;0;128;0m"},
} {
t.Run(tc.str, func(t *testing.T) {
p := tc.attr.AppendTo(nil)
e, a, n := ansi.DecodeEscape(p)
assert.Equal(t, len(p), n)
require.Equal(t, ansi.SGR, e, "expected full escape decode")
require.Equal(t, tc.str, string(p), "expected control sequence")
attr, n, err := ansi.DecodeSGR(a)
if err != nil {
err = fmt.Errorf("%v @%v in %q", err, n, a)
}
require.NoError(t, err)
assert.Equal(t, len(a), n, "expected full arg decode")
if !assert.Equal(t, tc.attr, attr) {
t.Logf("Encode %016x", uint64(tc.attr))
t.Logf(
"clear:%t bold:%t dim:%t italic:%t underscore:%t negative:%t conceal:%t",
(tc.attr&ansi.SGRAttrClear) != 0,
(tc.attr&ansi.SGRAttrBold) != 0,
(tc.attr&ansi.SGRAttrDim) != 0,
(tc.attr&ansi.SGRAttrItalic) != 0,
(tc.attr&ansi.SGRAttrUnderscore) != 0,
(tc.attr&ansi.SGRAttrNegative) != 0,
(tc.attr&ansi.SGRAttrConceal) != 0,
)
t.Logf("Decode %q => %016x", p, uint64(attr))
t.Logf(
"clear:%t bold:%t dim:%t italic:%t underscore:%t negative:%t conceal:%t",
(attr&ansi.SGRAttrClear) != 0,
(attr&ansi.SGRAttrBold) != 0,
(attr&ansi.SGRAttrDim) != 0,
(attr&ansi.SGRAttrItalic) != 0,
(attr&ansi.SGRAttrUnderscore) != 0,
(attr&ansi.SGRAttrNegative) != 0,
(attr&ansi.SGRAttrConceal) != 0,
)
}
})
}
}
func TestPoint_roundtrip(t *testing.T) {
for _, tc := range []struct {
p ansi.Point
}{
{
p: ansi.Pt(3, 5),
},
} {
t.Run(tc.p.String(), func(t *testing.T) {
seq := ansi.CUP.WithPoint(tc.p)
b := seq.AppendTo(nil)
e, a, n := ansi.DecodeEscape(b)
b = b[n:]
require.Equal(t, ansi.CUP, e)
require.Equal(t, 0, len(b))
p, n, err := ansi.DecodePoint(a)
a = a[n:]
require.NoError(t, err)
require.Equal(t, 0, len(a))
assert.Equal(t, tc.p, p)
})
}
}
|
package main_test
import "testing"
func TestVeri(t *testing.T) {
}
|
package controllers
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/gophergala2016/source/core/config"
"github.com/gophergala2016/source/core/foundation"
"github.com/gophergala2016/source/core/infra/database"
"github.com/gophergala2016/source/core/net/context/accessor"
"github.com/gophergala2016/source/internal/modules/parameters"
)
type (
RootController struct {
foundation.RootController
*apiController
*webController
}
apiController struct {
*RootController
}
webController struct {
*RootController
templateName string
}
APIController interface {
Controller
Preprocess(parameters.RequestParameter) bool
}
WebController interface {
Controller
SetTemplateName(string)
}
Controller interface {
// OK returns 200 OK Status Code
OK(interface{})
// Created returns 201 Created Status Code
Created(interface{})
// NoContent returns 204 No Content Status Code
NoContent(interface{})
// NoContent returns 307 Temporary Redirect Status Code
TemporaryRedirect(interface{})
// BadRequest returns 400 Bad Request Status Code
BadRequest(interface{})
// Unauthorized returns 401 Unauthorized Status Code
Unauthorized(interface{})
// Forbidden returns 403 Forbidden Status Code
Forbidden(interface{})
// NotFound returns 404 Not Found Status Code
NotFound(interface{})
// MethodNotAllowed returns 405 Method Not Allowed Status Code
MethodNotAllowed(interface{})
// NotAcceptable returns 406 Not Acceptable Status Code
NotAcceptable(interface{})
// Conflict returns 409 Conflict Status Code
Conflict(interface{})
// UnsupportedMediaType returns 415 Unsupported Media Type Status Code
UnsupportedMediaType(interface{})
// InternalServerError returns 500 Internal Server Error Status Code
InternalServerError(interface{})
// ServiceUnavailable returns 503 Service Unavailable Status Code
ServiceUnavailable(interface{})
}
)
// SetContext sets foundation.Context to initialize controller.
func (c *RootController) SetContext(ctx foundation.Context) {
c.RootController.SetContext(ctx)
// Set database to context
orm := database.NewGorm()
accessor.SetDatabase(ctx, orm)
}
// API returns APIController Interface
func (c *RootController) API() APIController {
if c.apiController == nil {
c.apiController = &apiController{RootController: c}
}
return c.apiController
}
// Web returns WebController Interface
func (c *RootController) Web() WebController {
if c.webController == nil {
c.webController = &webController{RootController: c}
}
return c.webController
}
// HTML renders the HTTP template specified by its file name.
// It also updates the HTTP code and sets the Content-Type as "text/html".
// See http://golang.org/doc/articles/wiki/
func (c *RootController) HTML(code int, name string, obj interface{}) {
c.GetContext().Render().HTML(code, name, obj)
}
// JSON serializes the given struct as JSON into the response body.
// It also sets the Content-Type as "application/json".
func (c *RootController) JSON(code int, obj interface{}) {
c.GetContext().Render().JSON(code, obj)
}
// IsAllowedMethod checks HTTP Method
func (c RootController) IsAllowedMethod() bool {
switch c.GetContext().Request().Method() {
case "GET", "POST", "PATCH", "PUT", "DELETE":
return true
}
return false
}
// ParseRequestHeader check if need access token.
func (c RootController) ParseRequestHeader(p parameters.RequestParameter) error {
req := c.GetContext().Request()
// API
apiToken := req.Header("Token")
if len(apiToken) <= 0 {
return fmt.Errorf("Not found the ApiToken.")
}
if apiToken != config.GetAPI().Token {
return fmt.Errorf("Not matched the ApiToken.")
}
// AccessToken
if !p.NeedAccessToken() {
return nil
}
auth := req.Header("Authorization")
if len(auth) <= 0 || !strings.HasPrefix(auth, "Bearer ") {
return fmt.Errorf("Not found the Authorization.")
}
p.SetAccessToken(strings.TrimPrefix(auth, "Bearer "))
return nil
}
// ParseRequestParameter applies parameters of request from body and query.
func (c RootController) ParseRequestParameter(p parameters.RequestParameter) error {
req := c.GetContext().Request()
// Request Body
if b := req.Body(); len(b) > 0 {
if err := json.Unmarshal(b, p); err != nil {
return err
}
}
// Request Query
query := map[string]interface{}{}
// Modify query into parsable one
for k, v := range req.Query() {
if strings.HasSuffix(k, "[]") {
// e.g.) foo[]=[]string => foo=[]string
query[k[:len(k)-2]] = v
} else {
// e.g.) foo=[]string => foo=string
query[k] = v[0]
}
}
mapcfg := &mapstructure.DecoderConfig{
WeaklyTypedInput: true,
Result: p,
}
decoder, err := mapstructure.NewDecoder(mapcfg)
if err != nil {
return err
}
if err = decoder.Decode(query); err != nil {
return err
}
return nil
}
// GetRequestParameter returns a value by key.
func (c RootController) GetRequestParameter(key string) interface{} {
req := c.GetContext().Request()
if b := req.Body(); len(b) > 0 {
data := map[string]interface{}{}
if err := json.Unmarshal(b, &data); err != nil {
return err
}
if v, found := data[key]; found {
return v
}
}
query := req.Query()
if v := query[key]; v != nil {
if ref := reflect.ValueOf(v); !ref.IsNil() {
return query.Get(key)
}
}
return nil
}
|
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
betapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/compute/beta/compute_beta_go_proto"
emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/beta"
)
// Server implements the gRPC interface for SslCertificate.
type SslCertificateServer struct{}
// ProtoToSslCertificateTypeEnum converts a SslCertificateTypeEnum enum from its proto representation.
func ProtoToComputeBetaSslCertificateTypeEnum(e betapb.ComputeBetaSslCertificateTypeEnum) *beta.SslCertificateTypeEnum {
if e == 0 {
return nil
}
if n, ok := betapb.ComputeBetaSslCertificateTypeEnum_name[int32(e)]; ok {
e := beta.SslCertificateTypeEnum(n[len("ComputeBetaSslCertificateTypeEnum"):])
return &e
}
return nil
}
// ProtoToSslCertificateSelfManaged converts a SslCertificateSelfManaged resource from its proto representation.
func ProtoToComputeBetaSslCertificateSelfManaged(p *betapb.ComputeBetaSslCertificateSelfManaged) *beta.SslCertificateSelfManaged {
if p == nil {
return nil
}
obj := &beta.SslCertificateSelfManaged{
Certificate: dcl.StringOrNil(p.Certificate),
PrivateKey: dcl.StringOrNil(p.PrivateKey),
}
return obj
}
// ProtoToSslCertificate converts a SslCertificate resource from its proto representation.
func ProtoToSslCertificate(p *betapb.ComputeBetaSslCertificate) *beta.SslCertificate {
obj := &beta.SslCertificate{
Name: dcl.StringOrNil(p.Name),
Id: dcl.Int64OrNil(p.Id),
CreationTimestamp: dcl.StringOrNil(p.CreationTimestamp),
Description: dcl.StringOrNil(p.Description),
SelfLink: dcl.StringOrNil(p.SelfLink),
SelfManaged: ProtoToComputeBetaSslCertificateSelfManaged(p.GetSelfManaged()),
Type: ProtoToComputeBetaSslCertificateTypeEnum(p.GetType()),
ExpireTime: dcl.StringOrNil(p.ExpireTime),
Region: dcl.StringOrNil(p.Region),
Project: dcl.StringOrNil(p.Project),
Location: dcl.StringOrNil(p.Location),
}
for _, r := range p.GetSubjectAlternativeNames() {
obj.SubjectAlternativeNames = append(obj.SubjectAlternativeNames, r)
}
return obj
}
// SslCertificateTypeEnumToProto converts a SslCertificateTypeEnum enum to its proto representation.
func ComputeBetaSslCertificateTypeEnumToProto(e *beta.SslCertificateTypeEnum) betapb.ComputeBetaSslCertificateTypeEnum {
if e == nil {
return betapb.ComputeBetaSslCertificateTypeEnum(0)
}
if v, ok := betapb.ComputeBetaSslCertificateTypeEnum_value["SslCertificateTypeEnum"+string(*e)]; ok {
return betapb.ComputeBetaSslCertificateTypeEnum(v)
}
return betapb.ComputeBetaSslCertificateTypeEnum(0)
}
// SslCertificateSelfManagedToProto converts a SslCertificateSelfManaged resource to its proto representation.
func ComputeBetaSslCertificateSelfManagedToProto(o *beta.SslCertificateSelfManaged) *betapb.ComputeBetaSslCertificateSelfManaged {
if o == nil {
return nil
}
p := &betapb.ComputeBetaSslCertificateSelfManaged{
Certificate: dcl.ValueOrEmptyString(o.Certificate),
PrivateKey: dcl.ValueOrEmptyString(o.PrivateKey),
}
return p
}
// SslCertificateToProto converts a SslCertificate resource to its proto representation.
func SslCertificateToProto(resource *beta.SslCertificate) *betapb.ComputeBetaSslCertificate {
p := &betapb.ComputeBetaSslCertificate{
Name: dcl.ValueOrEmptyString(resource.Name),
Id: dcl.ValueOrEmptyInt64(resource.Id),
CreationTimestamp: dcl.ValueOrEmptyString(resource.CreationTimestamp),
Description: dcl.ValueOrEmptyString(resource.Description),
SelfLink: dcl.ValueOrEmptyString(resource.SelfLink),
SelfManaged: ComputeBetaSslCertificateSelfManagedToProto(resource.SelfManaged),
Type: ComputeBetaSslCertificateTypeEnumToProto(resource.Type),
ExpireTime: dcl.ValueOrEmptyString(resource.ExpireTime),
Region: dcl.ValueOrEmptyString(resource.Region),
Project: dcl.ValueOrEmptyString(resource.Project),
Location: dcl.ValueOrEmptyString(resource.Location),
}
for _, r := range resource.SubjectAlternativeNames {
p.SubjectAlternativeNames = append(p.SubjectAlternativeNames, r)
}
return p
}
// ApplySslCertificate handles the gRPC request by passing it to the underlying SslCertificate Apply() method.
func (s *SslCertificateServer) applySslCertificate(ctx context.Context, c *beta.Client, request *betapb.ApplyComputeBetaSslCertificateRequest) (*betapb.ComputeBetaSslCertificate, error) {
p := ProtoToSslCertificate(request.GetResource())
res, err := c.ApplySslCertificate(ctx, p)
if err != nil {
return nil, err
}
r := SslCertificateToProto(res)
return r, nil
}
// ApplySslCertificate handles the gRPC request by passing it to the underlying SslCertificate Apply() method.
func (s *SslCertificateServer) ApplyComputeBetaSslCertificate(ctx context.Context, request *betapb.ApplyComputeBetaSslCertificateRequest) (*betapb.ComputeBetaSslCertificate, error) {
cl, err := createConfigSslCertificate(ctx, request.ServiceAccountFile)
if err != nil {
return nil, err
}
return s.applySslCertificate(ctx, cl, request)
}
// DeleteSslCertificate handles the gRPC request by passing it to the underlying SslCertificate Delete() method.
func (s *SslCertificateServer) DeleteComputeBetaSslCertificate(ctx context.Context, request *betapb.DeleteComputeBetaSslCertificateRequest) (*emptypb.Empty, error) {
cl, err := createConfigSslCertificate(ctx, request.ServiceAccountFile)
if err != nil {
return nil, err
}
return &emptypb.Empty{}, cl.DeleteSslCertificate(ctx, ProtoToSslCertificate(request.GetResource()))
}
// ListComputeBetaSslCertificate handles the gRPC request by passing it to the underlying SslCertificateList() method.
func (s *SslCertificateServer) ListComputeBetaSslCertificate(ctx context.Context, request *betapb.ListComputeBetaSslCertificateRequest) (*betapb.ListComputeBetaSslCertificateResponse, error) {
cl, err := createConfigSslCertificate(ctx, request.ServiceAccountFile)
if err != nil {
return nil, err
}
resources, err := cl.ListSslCertificate(ctx, request.Project, request.Location)
if err != nil {
return nil, err
}
var protos []*betapb.ComputeBetaSslCertificate
for _, r := range resources.Items {
rp := SslCertificateToProto(r)
protos = append(protos, rp)
}
return &betapb.ListComputeBetaSslCertificateResponse{Items: protos}, nil
}
func createConfigSslCertificate(ctx context.Context, service_account_file string) (*beta.Client, error) {
conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file))
return beta.NewClient(conf), nil
}
|
package main
import (
"fmt"
"time"
"github.com/olebedev/when"
"github.com/olebedev/when/rules/common"
"github.com/olebedev/when/rules/en"
)
func main() {
fmt.Println("vim-go")
w := when.New(nil)
w.Add(en.All...)
w.Add(common.All...)
text := "drop me a line in next wednesday at 2:25 p.m"
text = "December 19th, 2018"
r, err := w.Parse(text, time.Now())
if err != nil {
// an error has occurred
}
if r == nil {
// no matches found
}
fmt.Println(
"the time",
r.Time.String(),
"mentioned in",
text[r.Index:r.Index+len(r.Text)],
)
}
|
package main
import "golang_normal_study/go_log/loginit"
/*
var logger *log.Logger
var logFile *os.File
func init() {
var err error
logFile,err=os.OpenFile("./testlog.log",os.O_RDWR|os.O_CREATE|os.O_APPEND,0644)
if err!=nil{
panic(err)
}
//defer logFile.Close()
logger=log.New(logFile,"\r\n",log.Ldate|log.Ltime)
//writer=bufio.NewWriter(logFile)
//log.SetOutput(writer)
//log.Println("hello121222212112")
//log.Println("helloerrerrrrr")
//writer.Flush()
}
*/
func Add(x, y int) {
sum := x + y
loginit.Logger.Println("两数之和:", sum)
}
func Product(x, y int) {
product := x * y
loginit.Logger.Println("两数乘积:", product)
}
func main() {
defer loginit.LogFile.Close() //init初始化不能关闭文件,否则写不进去
loginit.Logger.Println("111111111")
Add(33, 10)
loginit.Logger.Println("222222222")
Product(2, 3)
loginit.Logger.Println("3333333333")
}
|
package main
func spiralMatrixIII(R int, C int, r0 int, c0 int) [][]int {
leftBound, rightBound := c0, c0
upBound, downBound := r0, r0
result := make([][]int, 0)
for len(result) < R*C {
for i := leftBound; i <= rightBound; i++ {
if isValidCoordinate(upBound, i, R, C) {
result = append(result, []int{upBound, i})
}
}
rightBound++
for i := upBound; i <= downBound; i++ {
if isValidCoordinate(i, rightBound, R, C) {
result = append(result, []int{i, rightBound})
}
}
downBound++
for i := rightBound; i >= leftBound; i-- {
if isValidCoordinate(downBound, i, R, C) {
result = append(result, []int{downBound, i})
}
}
leftBound--
for i := downBound; i >= upBound; i-- {
if isValidCoordinate(i, leftBound, R, C) {
result = append(result, []int{i, leftBound})
}
}
upBound--
}
return result
}
func isValidCoordinate(x, y, R, C int) bool {
return x >= 0 && x <= R-1 && y >= 0 && y <= C-1
}
/*
题目链接: https://leetcode-cn.com/problems/spiral-matrix-iii/
总结:
1. 其实关于矩阵的题,可以封装为一个结构,这样就能减少函数内的代码,也能减少函数参数个数。
*/
|
package services
import "errors"
var errInvalidUserData = errors.New("invalid username or password")
var errUserAlreadyExists = errors.New("this login or email is already used")
|
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
yaml "gopkg.in/yaml.v3"
)
type jqFlags struct {
compact bool
nullAsSingleInputValue bool
exitStatusCodeBasedOnOutput bool
slurp bool
raw bool
rawString bool
color bool
monochrome bool
sort bool
tab bool
arg string
slurpfile string
rawfile string
}
type yq struct {
returnYAML bool
jqCmd exec.Cmd
jqStdout io.ReadCloser
jqStdinWriter io.WriteCloser
files []string
jqFlags
}
func transformToYAML(reader io.Reader, writer io.Writer) error {
dec := json.NewDecoder(reader)
enc := yaml.NewEncoder(writer)
enc.SetIndent(2)
var err error
for {
var m interface{}
if err := dec.Decode(&m); err != nil {
if err == io.EOF {
break
}
return err
}
if err := enc.Encode(m); err != nil {
return err
}
}
return err
}
func transformToJSON(reader io.Reader, writer io.WriteCloser) error {
dec := yaml.NewDecoder(reader)
enc := json.NewEncoder(writer)
enc.SetEscapeHTML(false)
var err error
for {
var m interface{}
if err := dec.Decode(&m); err != nil {
if err == io.EOF {
break
}
if err != nil {
return err
}
}
if m == nil {
continue
}
if err = enc.Encode(m); err != nil {
return err
}
}
return err
}
func (yq *yq) parseFlags(f *flag.FlagSet, osArgs []string) error {
f.BoolVar(&(yq.returnYAML), "y", false, "Transcode jq JSON output back "+
"into YAML and emit it")
f.BoolVar(&(yq.returnYAML), "yaml-output", false, "Transcode jq JSON output back "+
"into YAML and emit it")
f.BoolVar(&(yq.compact), "c", false, "jq Flag: compact instead of "+
"pretty-printed output")
f.BoolVar(&(yq.exitStatusCodeBasedOnOutput), "e", false, "jq Flag: set the "+
"exit status code based on the output")
f.BoolVar(&(yq.nullAsSingleInputValue), "n", false, "jq Flag: use `null` "+
"as the single input value")
f.BoolVar(&(yq.raw), "r", false, "jq Flag: output raw strings, not JSON "+
"texts")
f.BoolVar(&(yq.slurp), "s", false, "jq Flag: read (slurp) all inputs into "+
"an array; apply filter to it")
f.BoolVar(&(yq.rawString), "R", false, "jq Flag: read raw strings, not "+
"JSON texts")
f.BoolVar(&(yq.color), "C", false, "jq Flag: colorize JSON")
f.BoolVar(&(yq.monochrome), "M", false, "jq Flag: monochrome (don't "+
"colorize JSON)")
f.BoolVar(&(yq.sort), "S", false, "jq Flag: sort keys of objects on "+
"output")
f.BoolVar(&(yq.tab), "tab", false, "jq Flag: use tabs for indentation")
f.StringVar(&(yq.arg), "arg", "", "jq Flag: 'a v' set variable $a to value "+
"<v>")
f.StringVar(&(yq.slurpfile), "slurpfile", "", "jq Flag: 'a f' set variable "+
"$a to an array of JSON texts read from <f>")
f.StringVar(&(yq.rawfile), "rawfile", "", "set variable $a to a string "+
"consisting of the contents of <f>")
if len(osArgs) == 1 {
f.Usage()
return errors.New("no arguments passed")
}
err := f.Parse(osArgs[1:])
return err
}
func (yq *yq) appendArgs(argName string, osArgs []string) {
yq.jqCmd.Args = append(yq.jqCmd.Args, argName)
idx := 0
for i, arg := range osArgs {
if arg == argName {
idx = i
break
}
}
yq.jqCmd.Args = append(yq.jqCmd.Args, osArgs[idx+1:idx+3]...)
}
func (yq *yq) compileJqCmd(osArgs []string, stderr io.Writer) error {
var f flag.FlagSet
f.SetOutput(stderr)
f.Usage = func() {
fmt.Fprintf(stderr, "Usage of %s:\n", osArgs[0])
f.PrintDefaults()
}
if err := yq.parseFlags(&f, osArgs); err != nil {
return errors.New("")
}
flagArgs := f.Args()
skippedArgs := 1
yq.jqCmd.Args = append(yq.jqCmd.Args, yq.jqCmd.Path)
if yq.compact {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-c")
}
if yq.nullAsSingleInputValue {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-n")
}
if yq.exitStatusCodeBasedOnOutput {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-e")
}
if yq.raw {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-r")
}
if yq.slurp {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-s")
}
if yq.rawString {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-R")
}
if yq.color {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-C")
}
if yq.monochrome {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-M")
}
if yq.sort {
yq.jqCmd.Args = append(yq.jqCmd.Args, "-S")
}
if yq.tab {
yq.jqCmd.Args = append(yq.jqCmd.Args, "--tab")
}
if yq.arg != "" {
skippedArgs = skippedArgs + 1
yq.appendArgs("--arg", osArgs)
}
if yq.slurpfile != "" {
skippedArgs = skippedArgs + 1
yq.appendArgs("--slurpfile", osArgs)
}
if yq.rawfile != "" {
skippedArgs = skippedArgs + 1
yq.appendArgs("--rawfile", osArgs)
}
yq.jqCmd.Args = append(yq.jqCmd.Args, flagArgs[skippedArgs-1])
for _, arg := range flagArgs[skippedArgs:] {
if _, err := os.Stat(arg); err != nil {
return err
}
yq.files = append(yq.files, arg)
}
reader, writer := io.Pipe()
yq.jqStdinWriter = writer
yq.jqCmd.Stdin = reader
if yq.returnYAML {
var stdoutPipe io.ReadCloser
stdoutPipe, err := yq.jqCmd.StdoutPipe()
if err != nil {
return err
}
yq.jqStdout = stdoutPipe
} else {
yq.jqCmd.Stdout = os.Stdout
}
yq.jqCmd.Stderr = os.Stderr
return nil
}
func (yq *yq) run() error {
var err error
if err = yq.jqCmd.Start(); err != nil {
return err
}
if len(yq.files) == 0 {
err = transformToJSON(os.Stdin, yq.jqStdinWriter)
if err != nil {
yq.jqStdinWriter.Close()
return err
}
} else {
for _, file := range yq.files {
file, err := os.Open(file)
if err != nil {
yq.jqStdinWriter.Close()
return err
}
if err = transformToJSON(file, yq.jqStdinWriter); err != nil {
yq.jqStdinWriter.Close()
return err
}
}
}
yq.jqStdinWriter.Close()
if yq.returnYAML {
if err := transformToYAML(yq.jqStdout, os.Stdout); err != nil {
yq.jqStdinWriter.Close()
return err
}
}
yq.jqCmd.Wait()
return nil
}
func main() {
var y yq
if path, err := exec.LookPath("jq"); err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
} else {
y.jqCmd.Path = path
}
if err := y.compileJqCmd(os.Args, os.Stderr); err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
if err := y.run(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
|
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03600104 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.036.001.04 Document"`
Message *SecuritiesFinancingModificationInstructionV04 `xml:"SctiesFincgModInstr"`
}
func (d *Document03600104) AddMessage() *SecuritiesFinancingModificationInstructionV04 {
d.Message = new(SecuritiesFinancingModificationInstructionV04)
return d.Message
}
// Scope
// An account owner sends a SecuritiesFinancingModificationInstruction to a securities financing transaction account servicer to notify the securities financing transaction account servicer of an update in the details of a repurchase agreement, reverse repurchase agreement, securities lending or securities borrowing transaction that does not impact the original transaction securities quantity.
// Such a change may be:
// - the providing of closing details not available at the time of the sending of the Securities Financing Instruction, for example, termination date for an open repo,
// - the providing of a new rate, for example, a repo rate,
// - the rollover of a position extending the closing or maturity date.
// The account owner/servicer relationship may be:
// - a global custodian which has an account with a local custodian, or
// - an investment management institution which manage a fund account opened at a custodian, or
// - a broker which has an account with a custodian, or
// - a central securities depository participant which has an account with a central securities depository, or
// - a central securities depository which has an account with a custodian, another central securities depository or another settlement market infrastructure, or
// - a central counterparty or a stock exchange or a trade matching utility which need to instruct the settlement of securities financing transactions to a central securities depository or another settlement market infrastructure.
//
// Usage
// The message may also be used to:
// - re-send a message previously sent,
// - provide a third party with a copy of a message for information,
// - re-send to a third party a copy of a message for information
// using the relevant elements in the Business Application Header.
//
// ISO 15022 - 20022 Coexistence
// This ISO 20022 message is reversed engineered from ISO 15022. Both standards will coexist for a certain number of years. Until this coexistence period ends, the usage of certain data types is restricted to ensure interoperability between ISO 15022 and 20022 users. Compliance to these rules is mandatory in a coexistence environment. The coexistence restrictions are described in a Textual Rule linked to the Message Items they concern. These coexistence textual rules are clearly identified as follows: “CoexistenceXxxxRule”.
type SecuritiesFinancingModificationInstructionV04 struct {
// Securities financing transaction identification information, type (repurchase agreement, reverse repurchase agreement, securities lending or securities borrowing), modification information and other parameters.
TransactionTypeAndModificationAdditionalParameters *iso20022.TransactionTypeAndAdditionalParameters7 `xml:"TxTpAndModAddtlParams"`
// Details of the securities financing deal.
TradeDetails *iso20022.SecuritiesTradeDetails5 `xml:"TradDtls"`
// Financial instrument representing a sum of rights of the investor vis-a-vis the issuer.
FinancialInstrumentIdentification *iso20022.SecurityIdentification14 `xml:"FinInstrmId"`
// Details related to the account and quantity involved in the transaction.
QuantityAndAccountDetails *iso20022.QuantityAndAccount16 `xml:"QtyAndAcctDtls"`
// Details of the closing of the securities financing transaction.
SecuritiesFinancingAdditionalDetails *iso20022.SecuritiesFinancingTransactionDetails19 `xml:"SctiesFincgAddtlDtls"`
// Parameters which explicitly state the conditions that must be fulfilled before a particular transaction of a financial instrument can be settled. These parameters are defined by the instructing party in compliance with settlement rules in the market the transaction will settle in.
SettlementParameters *iso20022.SettlementDetails72 `xml:"SttlmParams,omitempty"`
// Identifies the chain of delivering settlement parties.
DeliveringSettlementParties *iso20022.SettlementParties10 `xml:"DlvrgSttlmPties,omitempty"`
// Identifies the chain of receiving settlement parties.
ReceivingSettlementParties *iso20022.SettlementParties10 `xml:"RcvgSttlmPties,omitempty"`
// Total amount of money to be paid or received in exchange for the securities at the opening of a securities financing transaction.
OpeningSettlementAmount *iso20022.AmountAndDirection10 `xml:"OpngSttlmAmt,omitempty"`
// Additional information that cannot be captured in the structured elements and/or any other specific block.
SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"`
}
func (s *SecuritiesFinancingModificationInstructionV04) AddTransactionTypeAndModificationAdditionalParameters() *iso20022.TransactionTypeAndAdditionalParameters7 {
s.TransactionTypeAndModificationAdditionalParameters = new(iso20022.TransactionTypeAndAdditionalParameters7)
return s.TransactionTypeAndModificationAdditionalParameters
}
func (s *SecuritiesFinancingModificationInstructionV04) AddTradeDetails() *iso20022.SecuritiesTradeDetails5 {
s.TradeDetails = new(iso20022.SecuritiesTradeDetails5)
return s.TradeDetails
}
func (s *SecuritiesFinancingModificationInstructionV04) AddFinancialInstrumentIdentification() *iso20022.SecurityIdentification14 {
s.FinancialInstrumentIdentification = new(iso20022.SecurityIdentification14)
return s.FinancialInstrumentIdentification
}
func (s *SecuritiesFinancingModificationInstructionV04) AddQuantityAndAccountDetails() *iso20022.QuantityAndAccount16 {
s.QuantityAndAccountDetails = new(iso20022.QuantityAndAccount16)
return s.QuantityAndAccountDetails
}
func (s *SecuritiesFinancingModificationInstructionV04) AddSecuritiesFinancingAdditionalDetails() *iso20022.SecuritiesFinancingTransactionDetails19 {
s.SecuritiesFinancingAdditionalDetails = new(iso20022.SecuritiesFinancingTransactionDetails19)
return s.SecuritiesFinancingAdditionalDetails
}
func (s *SecuritiesFinancingModificationInstructionV04) AddSettlementParameters() *iso20022.SettlementDetails72 {
s.SettlementParameters = new(iso20022.SettlementDetails72)
return s.SettlementParameters
}
func (s *SecuritiesFinancingModificationInstructionV04) AddDeliveringSettlementParties() *iso20022.SettlementParties10 {
s.DeliveringSettlementParties = new(iso20022.SettlementParties10)
return s.DeliveringSettlementParties
}
func (s *SecuritiesFinancingModificationInstructionV04) AddReceivingSettlementParties() *iso20022.SettlementParties10 {
s.ReceivingSettlementParties = new(iso20022.SettlementParties10)
return s.ReceivingSettlementParties
}
func (s *SecuritiesFinancingModificationInstructionV04) AddOpeningSettlementAmount() *iso20022.AmountAndDirection10 {
s.OpeningSettlementAmount = new(iso20022.AmountAndDirection10)
return s.OpeningSettlementAmount
}
func (s *SecuritiesFinancingModificationInstructionV04) AddSupplementaryData() *iso20022.SupplementaryData1 {
newValue := new(iso20022.SupplementaryData1)
s.SupplementaryData = append(s.SupplementaryData, newValue)
return newValue
}
|
package demoinfocs
import (
"github.com/ghostanalysis/demoinfocs-golang/common"
)
type demoCommand byte
const (
maxEntities = (1 << common.MaxEditctBits)
maxPlayers = 64
maxWeapons = 64
)
const (
dc_Signon demoCommand = iota + 1
dc_Packet
dc_Synctick
dc_ConsoleCommand
dc_UserCommand
dc_DataTables
dc_Stop
dc_CustomData
dc_StringTables
)
const (
stName_InstanceBaseline = "instancebaseline"
stName_UserInfo = "userinfo"
stName_ModelPreCache = "modelprecache"
)
|
package command
import (
"os/exec"
"github.com/satori/go.uuid"
"os"
"fmt"
"bufio"
"log"
"bytes"
)
type Output struct {
Content string `json:"content"`
}
type LogsCommand struct {
StackName string `json:"stackName"`
ServiceName string `json:serviceName`
Instance string `json:instance`
}
type RunCommand struct {
StackName string `json:"stackName"`
StackDefinition string `json:"stackDefinition"`
}
func ExecuteLogsCommand(command LogsCommand) (output *Output, err error) {
cmd := exec.Command("docker", "logs", fmt.Sprintf("%s_%s_%s", command.StackName, command.ServiceName, command.Instance))
var outbuf, errbuf bytes.Buffer
cmd.Stdout = &outbuf
cmd.Stderr = &errbuf
cmd.Start()
cmd.Wait()
stderr := outbuf.String()
return &Output{Content: stderr}, nil
}
func ExecuteRunCommand(command RunCommand) (output *Output, err error) {
randomUuid := uuid.NewV4()
tmpFolder := fmt.Sprintf("%s%s", os.TempDir(), randomUuid)
os.MkdirAll(tmpFolder, os.ModePerm)
defer func() {
log.Print("Deleting temporary folder.\n")
os.RemoveAll(tmpFolder)
}()
filePath := fmt.Sprintf("%s/docker-compose.yml", tmpFolder)
file, err := os.Create(filePath)
if err != nil {
return nil, err
}
writer := bufio.NewWriter(file)
_, err = writer.WriteString(command.StackDefinition)
if err != err {
return nil, err
}
writer.Flush()
log.Print("Executing docker-compose.\n")
cmd := exec.Command("docker-compose", "-p", command.StackName, "-f", filePath, "up", "-d")
var outbuf, errbuf bytes.Buffer
cmd.Stdout = &outbuf
cmd.Stderr = &errbuf
cmd.Start()
cmd.Wait()
stderr := errbuf.String()
return &Output{Content: stderr}, nil
}
|
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
)
/*
@Time : 2021/1/18 10:40 下午
@Author : audiRS7
@File : find4.go
@Software: GoLand
*/
//文件目录树形结构节点
type dirTreeNode struct {
name string
child []dirTreeNode
}
var iCount int = 0
//递归遍历文件目录
func getDirTree(pathName string) (dirTreeNode, error) {
rd, err := ioutil.ReadDir(pathName)
if err != nil {
log.Fatalf("Read dir '%s' failed: %v", pathName, err)
}
var tree, childNode dirTreeNode
tree.name = pathName
var name, fullName string
for _, fileDir := range rd {
name = fileDir.Name()
fullName = pathName + "/" + name
if fileDir.IsDir() {
childNode, err = getDirTree(fullName)
if err != nil {
log.Fatalf("Read dir '%s' failed: %v", fullName, err)
}
} else {
childNode.name = name
childNode.child = nil
//读取文件内容并打印
readLine(fullName, processLine)
iCount++
}
tree.child = append(tree.child, childNode)
}
return tree, nil
}
//递归打印文件目录
func printDirTree(tree dirTreeNode, prefix string) {
fmt.Println(prefix + tree.name)
if len(tree.child) > 0 {
prefix += "----"
for _, childNode := range tree.child {
printDirTree(childNode, prefix)
}
}
}
func processLine(line []byte) {
os.Stdout.Write(line)
}
// read one file and use hookfn to process each line
func readLine(filePth string, hookfn func([]byte)) error {
f, err := os.Open(filePth)
if err != nil {
return err
}
defer f.Close()
bfRd := bufio.NewReader(f)
for {
line, err := bfRd.ReadBytes('\n')
hookfn(line) //放在错误处理前面,即使发生错误,也会处理已经读取到的数据。
if err != nil { //遇到任何错误立即返回,并忽略 EOF 错误信息
if err == io.EOF {
return nil
}
return err
}
}
}
func main() {
dirName := "/Users/jiazhenbing/go/src/example"
tree, err := getDirTree(dirName)
if err != nil {
log.Fatalln("read dir", dirName, "fail: ", err)
}
fmt.Printf("\n")
fmt.Println("File Count:", iCount)
printDirTree(tree, "")
}
|
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package storage
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/pingcap/errors"
berrors "github.com/pingcap/tidb/br/pkg/errors"
)
// HDFSStorage represents HDFS storage.
type HDFSStorage struct {
remote string
}
// NewHDFSStorage creates a new HDFS storage.
func NewHDFSStorage(remote string) *HDFSStorage {
return &HDFSStorage{
remote: remote,
}
}
func getHdfsBin() (string, error) {
hadoopHome, ok := os.LookupEnv("HADOOP_HOME")
if !ok {
return "", errors.Annotatef(berrors.ErrEnvNotSpecified, "please specify environment variable HADOOP_HOME")
}
return filepath.Join(hadoopHome, "bin/hdfs"), nil
}
func getLinuxUser() (string, bool) {
return os.LookupEnv("HADOOP_LINUX_USER")
}
func dfsCommand(args ...string) (*exec.Cmd, error) {
bin, err := getHdfsBin()
if err != nil {
return nil, err
}
cmd := []string{}
user, ok := getLinuxUser()
if ok {
cmd = append(cmd, "sudo", "-u", user)
}
cmd = append(cmd, bin, "dfs")
cmd = append(cmd, args...)
//nolint:gosec
return exec.Command(cmd[0], cmd[1:]...), nil
}
// WriteFile writes a complete file to storage, similar to os.WriteFile
func (s *HDFSStorage) WriteFile(_ context.Context, name string, data []byte) error {
filePath := fmt.Sprintf("%s/%s", s.remote, name)
cmd, err := dfsCommand("-put", "-", filePath)
if err != nil {
return err
}
buf := bytes.Buffer{}
buf.Write(data)
cmd.Stdin = &buf
out, err := cmd.CombinedOutput()
if err != nil {
return errors.Annotate(err, string(out))
}
return nil
}
// ReadFile reads a complete file from storage, similar to os.ReadFile
func (*HDFSStorage) ReadFile(_ context.Context, _ string) ([]byte, error) {
return nil, errors.Annotatef(berrors.ErrUnsupportedOperation, "currently HDFS backend only support rawkv backup")
}
// FileExists return true if file exists
func (s *HDFSStorage) FileExists(_ context.Context, name string) (bool, error) {
filePath := fmt.Sprintf("%s/%s", s.remote, name)
cmd, err := dfsCommand("-ls", filePath)
if err != nil {
return false, err
}
out, err := cmd.CombinedOutput()
if _, ok := err.(*exec.ExitError); ok {
// Successfully exit with non-zero value
return false, nil
}
if err != nil {
return false, errors.Annotate(err, string(out))
}
// Successfully exit with zero value
return true, nil
}
// DeleteFile delete the file in storage
func (*HDFSStorage) DeleteFile(_ context.Context, _ string) error {
return errors.Annotatef(berrors.ErrUnsupportedOperation, "currently HDFS backend only support rawkv backup")
}
// Open a Reader by file path. path is relative path to storage base path
func (*HDFSStorage) Open(_ context.Context, _ string) (ExternalFileReader, error) {
return nil, errors.Annotatef(berrors.ErrUnsupportedOperation, "currently HDFS backend only support rawkv backup")
}
// WalkDir traverse all the files in a dir.
//
// fn is the function called for each regular file visited by WalkDir.
// The argument `path` is the file path that can be used in `Open`
// function; the argument `size` is the size in byte of the file determined
// by path.
func (*HDFSStorage) WalkDir(_ context.Context, _ *WalkOption, _ func(path string, size int64) error) error {
return errors.Annotatef(berrors.ErrUnsupportedOperation, "currently HDFS backend only support rawkv backup")
}
// URI returns the base path as a URI
func (s *HDFSStorage) URI() string {
return s.remote
}
// Create opens a file writer by path. path is relative path to storage base path
func (*HDFSStorage) Create(_ context.Context, _ string, _ *WriterOption) (ExternalFileWriter, error) {
return nil, errors.Annotatef(berrors.ErrUnsupportedOperation, "currently HDFS backend only support rawkv backup")
}
// Rename a file name from oldFileName to newFileName.
func (*HDFSStorage) Rename(_ context.Context, _, _ string) error {
return errors.Annotatef(berrors.ErrUnsupportedOperation, "currently HDFS backend only support rawkv backup")
}
|
//Copyright 2015 gsgo Author. All Rights Reserved.
package logs
import (
"fmt"
"strings"
"sync"
)
//日志等级常量
const (
LevelTrace = iota
LevelDebug
LevelInfo
LevelWarn
LevelError
)
var levelPrefix = []string{"[T]", "[D]", "[I]", "[W]", "[E]"}
func getLoggerLevel(level string) int {
level = strings.ToLower(level)
switch level {
case "trace":
return LevelTrace
case "debug":
return LevelDebug
case "info":
return LevelInfo
case "warn":
return LevelWarn
case "error":
return LevelError
default:
return LevelTrace
}
}
//日志输出终端接口
type LoggerOutputInf interface {
Init(config string) error
WriteMsg(level int, msg string) error
Flush()
Destroy()
}
//日志输出终端函数定义
type loggerType func() LoggerOutputInf
//支持的日志输出终端
var appenderMap = make(map[string]loggerType)
func RegisterLoggerAppender(name string, log loggerType) {
if log == nil {
panic("logs : Register provider is nil")
}
if _, ok := appenderMap[name]; ok {
panic("logs: Duplicate Register provider " + name)
}
appenderMap[name] = log
}
type logMsg struct {
Level int
Msg string
}
//logger class
type Logger4g struct {
lock sync.Mutex
level int
outputs map[string]LoggerOutputInf
msg chan *logMsg
name string
bGoRoutine bool
}
//创建一个新的logger
//usage: NewLogger("defaultlogger",100)
//chanlen:可缓存的日志条数
func NewLogger(name string, chanlen int) *Logger4g {
log1 := &Logger4g{}
log1.level = LevelTrace
log1.outputs = make(map[string]LoggerOutputInf)
if chanlen < 10 {
chanlen = 10
}
log1.msg = make(chan *logMsg, chanlen)
log1.name = name
if log1.bGoRoutine {
go log1.startLogger()
}
return log1
}
func (this *Logger4g) SetThreadable(bGoRoutine bool) {
this.bGoRoutine = bGoRoutine
}
func (this *Logger4g) startLogger() {
for {
select {
case tmpMsg := <-this.msg:
for _, tmpOutput := range this.outputs {
err := tmpOutput.WriteMsg(tmpMsg.Level, tmpMsg.Msg)
if err != nil {
fmt.Println("Error,unable to WriteMsg:", err)
}
}
}
}
}
func (this *Logger4g) flushLogger(msg *logMsg) {
for _, tmpOutput := range this.outputs {
err := tmpOutput.WriteMsg(msg.Level, msg.Msg)
if err != nil {
fmt.Println("Error unable to Write msg:", err)
}
}
}
func (this *Logger4g) SetAppender(appenderName string, config string) error {
this.lock.Lock()
defer this.lock.Unlock()
if log, ok := appenderMap[appenderName]; ok {
lg := log()
err := lg.Init(config)
if err != nil {
fmt.Println("Logs.Logger4g.SetAppender: " + err.Error())
}
this.outputs[appenderName] = lg
} else {
fmt.Println("logs: unkown appendername %s \n", appenderName)
return fmt.Errorf("logs: unkown appendername %s ", appenderName)
}
return nil
}
func (this *Logger4g) writeMsg(level int, msg string) {
if level < this.level {
return
}
tmpMsg := &logMsg{Level: level, Msg: msg}
if this.bGoRoutine {
this.msg <- tmpMsg
} else {
this.flushLogger(tmpMsg)
}
return
}
func (this *Logger4g) Flush() {
for _, l := range this.outputs {
l.Flush()
}
}
func (this *Logger4g) Close() {
for {
if len(this.msg) > 0 {
tmpMsg := <-this.msg
for _, tmpOutput := range this.outputs {
err := tmpOutput.WriteMsg(tmpMsg.Level, tmpMsg.Msg)
if err != nil {
fmt.Printf("Error unable to WriteMsg while closing logger :", err)
}
}
continue
}
break
}
for _, o := range this.outputs {
o.Flush()
o.Destroy()
}
}
func (this *Logger4g) SetLevel(level string) {
this.level = getLoggerLevel(level)
}
func (this *Logger4g) GetLevel() int {
return this.level
}
func (this *Logger4g) Trace(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
this.writeMsg(LevelTrace, msg)
}
func (this *Logger4g) Debug(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
this.writeMsg(LevelDebug, msg)
}
func (this *Logger4g) Info(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
this.writeMsg(LevelInfo, msg)
}
func (this *Logger4g) Warn(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
this.writeMsg(LevelWarn, msg)
}
func (this *Logger4g) Error(format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)
this.writeMsg(LevelError, msg)
}
var DefaultLogger *Logger4g = NewLogger("default", 100)
func init() {
DefaultLogger.SetAppender("console", `{"level":0}`)
}
|
package cmd
import (
"errors"
"fmt"
"github.com/spf13/cobra"
"github.com/wish/ctl/cmd/util/parsing"
"github.com/wish/ctl/pkg/client"
"strings"
)
var supportedGetTypes = [][]string{
{"pods", "pod", "po"},
{"jobs", "job"},
{"configmaps", "configmap", "cm"},
{"deployments", "deployment", "deploy"},
{"replicasets", "replicaset", "rs"},
{"cronjobs", "cronjob"},
{"k8s_env"},
}
func getResourceStr() string {
var str strings.Builder
fmt.Fprintln(&str, "Choose from the list of supported resources:")
for _, names := range supportedGetTypes {
fmt.Fprintf(&str, " * %s\n", names[0])
}
return str.String()
}
func getCmd(c *client.Client) *cobra.Command {
cmd := &cobra.Command{
Use: "get RESOURCE [NAME...] [flags]",
Short: "Prints a table of resources of a type",
Long: `Prints out a table of resource type matching the query.
Optionally, it filters through names match any of the regular expressions set.` + "\n\n" + getResourceStr(),
RunE: func(cmd *cobra.Command, args []string) error {
ctxs, _ := cmd.Flags().GetStringSlice("context")
namespace, _ := cmd.Flags().GetString("namespace")
if len(args) == 0 {
cmd.Help()
return errors.New("no resource type provided")
}
options, err := parsing.ListOptions(cmd, args[1:])
if err != nil {
return err
}
labelColumns, _ := cmd.Flags().GetStringSlice("label-columns")
switch strings.ToLower(args[0]) {
case "pods", "pod", "po":
list, err := c.ListPodsOverContexts(ctxs, namespace, options)
// NOTE: List is unsorted and could be in an inconsistent order
// Output
if err != nil {
printPodList(cmd.OutOrStdout(), list, labelColumns)
return err
}
printPodList(cmd.OutOrStdout(), list, labelColumns)
case "jobs", "job":
list, err := c.ListJobsOverContexts(ctxs, namespace, options)
if err != nil {
printJobList(cmd.OutOrStdout(), list, labelColumns)
return err
}
printJobList(cmd.OutOrStdout(), list, labelColumns)
case "configmaps", "configmap", "cm":
list, err := c.ListConfigMapsOverContexts(ctxs, namespace, options)
if err != nil {
printConfigMapList(cmd.OutOrStdout(), list, labelColumns)
return err
}
printConfigMapList(cmd.OutOrStdout(), list, labelColumns)
case "deployments", "deployment", "deploy":
list, err := c.ListDeploymentsOverContexts(ctxs, namespace, options)
if err != nil {
printDeploymentList(cmd.OutOrStdout(), list, labelColumns)
return err
}
printDeploymentList(cmd.OutOrStdout(), list, labelColumns)
case "replicasets", "replicaset", "rs":
list, err := c.ListReplicaSetsOverContexts(ctxs, namespace, options)
if err != nil {
printReplicaSetList(cmd.OutOrStdout(), list, labelColumns)
return err
}
printReplicaSetList(cmd.OutOrStdout(), list, labelColumns)
case "cronjobs", "cronjob":
list, err := c.ListCronJobsOverContexts(ctxs, namespace, options)
if err != nil {
printCronJobList(cmd.OutOrStdout(), list, labelColumns)
return err
}
printCronJobList(cmd.OutOrStdout(), list, labelColumns)
case "k8s_env":
printK8sEnvList(c.K8Envs)
default:
cmd.Help()
return errors.New(`the resource type "` + args[0] + `" was not found`)
}
return nil
},
}
cmd.Flags().StringSlice("label-columns", nil, "Prints with columns that contain the value of the specified label")
cmd.Flags().StringP("status", "s", "", "Filter pods by specified status")
return cmd
}
|
package config
import (
"strings"
"github.com/spf13/viper"
)
// LoadConfig for
func LoadConfig() {
viper.AddConfigPath("./conf") // 如果没有指定配置文件,则解析默认的配置文件
viper.SetConfigName("config")
viper.SetConfigType("yaml") // 设置配置文件格式为YAML
viper.AutomaticEnv() // 读取匹配的环境变量
viper.SetEnvPrefix("CRAWLAB") // 读取环境变量的前缀为APISERVER
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil { // viper解析配置文件
}
}
|
package main
import (
"os"
"cloud_go/service"
"flag"
)
const (
PORT string = "8080"
)
func main() {
port := os.Getenv("PORT")//get custom environment variables
if len(port) == 0 {
port = PORT
}
flag.StringVar(&port, "p", PORT, "PORT for httpd listening")
flag.Parse()
server := service.NewServer() // get server
server.Run(":" + port) // run the server at specific port
}
|
package main
import(
"fmt"
"time"
"math/rand"
)
func main() {
average := 0
for a := 0; a < 10; a++ {
rand.Seed(time.Now().UnixNano())
start := time.Now()
fmt.Println(connectDB("Database 1"))
fmt.Println(connectDB("Database 2"))
average = average + (int(time.Since(start))/(1000*1000))
fmt.Println(" Next try")
}
fmt.Print("Time in MS: ")
fmt.Print(average/10)
}
func connectDB(db string) string{
// DB access
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
return "Response from "+ db
}
|
package main
import (
"database/sql"
"net/http"
_ "github.com/lib/pq"
)
//ShipmentEnvironmentsByGroupResult ...
type ShipmentEnvironmentsByGroupResult struct {
Group string `json:"group"`
Count int `json:"count"`
}
func shipmentEnvironmentsByGroup(r *http.Request) *Response {
query := `
select
"Shipments".group, count(*) as count
from
"Providers",
"Environments",
"Shipments"
where
"Providers"."environmentId" = "Environments".composite
and "Environments"."shipmentId" = "Shipments"."name"
and "Providers".barge NOT LIKE '%test%'
group by
"Shipments".group
having
count(*) > 45
order by
count(*) desc
;
`
var results []ShipmentEnvironmentsByGroupResult
err := dbQuery(query, func(rows *sql.Rows) {
var group string
var count int
err := rows.Scan(&group, &count)
check(err)
results = append(results, ShipmentEnvironmentsByGroupResult{
Group: group,
Count: count,
})
})
check(err)
return DataJSON(http.StatusOK, results, nil)
}
|
package raft
import (
"bytes"
"encoding/json"
"fmt"
"io"
"reflect"
)
var commandTypes map[string]Command
func init() {
commandTypes = map[string]Command{}
}
type Command interface {
CommandName() string
}
type CommandEncoder interface {
Encode(w io.Writer) error
Decode(r io.Reader) error
}
// Creates a new instance of a command by name.
func newCommand(name string, data []byte) (Command, error) {
// Find the registered command.
command := commandTypes[name]
if command == nil {
panic(fmt.Errorf("raft.Command: Unregistered command type: %s", name))
}
// Make a copy of the command.
v := reflect.New(reflect.Indirect(reflect.ValueOf(command)).Type()).Interface()
copy, ok := v.(Command)
if !ok {
panic(fmt.Sprintf("raft: Unable to copy command: %s (%v)", command.CommandName(), reflect.ValueOf(v).Kind().String()))
}
// If data for the command was passed in the decode it.
if data != nil {
if encoder, ok := copy.(CommandEncoder); ok {
if err := encoder.Decode(bytes.NewReader(data)); err != nil {
return nil, err
}
} else {
if err := json.NewDecoder(bytes.NewReader(data)).Decode(copy); err != nil {
return nil, err
}
}
}
return copy, nil
}
// 注册命令类型
func RegisterCommand(command Command) {
if command == nil {
panic(fmt.Sprintf("raft: Cannot register nil"))
} else if commandTypes[command.CommandName()] != nil {
panic(fmt.Sprintf("raft: Duplicate registration: %s", command.CommandName()))
}
commandTypes[command.CommandName()] = command
}
// Creates a new log entry associated with a log.
func newLogEntry(index uint64, term uint64, command Command) (*LogEntry, error) {
var buf bytes.Buffer
var commandName string
if command != nil {
commandName = command.CommandName()
if encoder, ok := command.(CommandEncoder); ok {
if err := encoder.Encode(&buf); err != nil {
return nil, err
}
} else {
if err := json.NewEncoder(&buf).Encode(command); err != nil {
return nil, err
}
}
}
e := &LogEntry{
Index: index,
Term: term,
CommandName: commandName,
Command: buf.Bytes(),
}
return e, nil
}
|
package cli
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"
"time"
"github.com/10gen/realm-cli/internal/telemetry"
"github.com/10gen/realm-cli/internal/utils/api"
"github.com/10gen/realm-cli/internal/utils/test/assert"
"github.com/10gen/realm-cli/internal/utils/test/mock"
)
type capturedEvent struct {
EventType telemetry.EventType
Data []telemetry.EventData
}
func TestCommandFactoryVersionCheck(t *testing.T) {
now := time.Now()
t.Run("should not warn the user nor update the last version check when client fails to get build info", func(t *testing.T) {
profile := mock.NewProfile(t)
lastVersionCheck := profile.LastVersionCheck().AddDate(0, 0, -2)
profile.SetLastVersionCheck(lastVersionCheck)
var events []capturedEvent
var telemetryService mock.TelemetryService
telemetryService.TrackEventFn = func(eventType telemetry.EventType, data ...telemetry.EventData) {
events = append(events, capturedEvent{eventType, data})
}
out, ui := mock.NewUI()
factory := &CommandFactory{
profile: profile,
telemetryService: telemetryService,
ui: ui,
}
factory.checkForNewVersion(mockVersionClient{status: http.StatusNotFound})
assert.Equal(t, 1, len(events))
assert.Equal(t,
capturedEvent{
telemetry.EventTypeCommandError,
telemetry.EventDataError(api.ErrUnexpectedStatusCode{"get cli version manifest", 404}),
},
events[0],
)
assert.Equal(t, "", out.String())
assert.Equal(t, lastVersionCheck, profile.LastVersionCheck())
})
t.Run("should not warn the user but should update the last version check when client gets build info equal to current", func(t *testing.T) {
profile := mock.NewProfile(t)
lastVersionCheck := profile.LastVersionCheck()
var events []capturedEvent
var telemetryService mock.TelemetryService
telemetryService.TrackEventFn = func(eventType telemetry.EventType, data ...telemetry.EventData) {
events = append(events, capturedEvent{eventType, data})
}
out, ui := mock.NewUI()
factory := &CommandFactory{
profile: profile,
telemetryService: telemetryService,
ui: ui,
}
factory.checkForNewVersion(mockVersionClient{url: "http://somewhere.com"})
assert.Equal(t, 0, len(events))
assert.Equal(t, "", out.String())
assert.True(t, lastVersionCheck.Before(profile.LastVersionCheck()), "version check time should be updated")
})
t.Run("should warn the user and update the last version check when client gets new build info", func(t *testing.T) {
profile := mock.NewProfile(t)
lastVersionCheck := profile.LastVersionCheck()
var events []capturedEvent
var telemetryService mock.TelemetryService
telemetryService.TrackEventFn = func(eventType telemetry.EventType, data ...telemetry.EventData) {
events = append(events, capturedEvent{eventType, data})
}
out, ui := mock.NewUI()
factory := &CommandFactory{
profile: profile,
telemetryService: telemetryService,
ui: ui,
}
factory.checkForNewVersion(mockVersionClient{version: "0.1.0", url: "http://somewhere.com"})
assert.Equal(t, 1, len(events))
assert.Equal(t, capturedEvent{EventType: telemetry.EventTypeCommandVersionCheck}, events[0])
assert.Equal(t, `New version (v0.1.0) of CLI available: http://somewhere.com
Note: This is the only time this alert will display today
To install
npm install -g mongodb-realm-cli@v0.1.0
curl -o ./mongodb-realm-cli http://somewhere.com && chmod +x ./mongodb-realm-cli
`, out.String())
assert.True(t, lastVersionCheck.Before(profile.LastVersionCheck()), "version check time should be updated")
})
t.Run("should not warn user nor update the last version check if the check has already occurred that day", func(t *testing.T) {
lastVersionCheck := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
profile := mock.NewProfile(t)
profile.SetLastVersionCheck(lastVersionCheck)
var events []capturedEvent
var telemetryService mock.TelemetryService
telemetryService.TrackEventFn = func(eventType telemetry.EventType, data ...telemetry.EventData) {
events = append(events, capturedEvent{eventType, data})
}
out, ui := mock.NewUI()
factory := &CommandFactory{
profile: profile,
telemetryService: telemetryService,
ui: ui,
}
factory.checkForNewVersion(mockVersionClient{})
assert.Equal(t, 0, len(events))
assert.Equal(t, "", out.String())
assert.Equal(t, lastVersionCheck, profile.LastVersionCheck())
})
}
type mockVersionClient struct {
status int
version string
url string
}
func (client mockVersionClient) Get(_ string) (*http.Response, error) {
status := client.status
if status == 0 {
status = http.StatusOK
}
version := client.version
if version == "" {
version = Version
}
url := client.url
if url == "" {
url = "http://testurl.com"
}
return &http.Response{
StatusCode: status,
Body: ioutil.NopCloser(strings.NewReader(fmt.Sprintf(`{
"version": %q,
"info": { %q: { "url": %q } }
}`, version, osArch, url))),
}, nil
}
|
package log
import (
"Open_IM/pkg/common/config"
"bufio"
"fmt"
nested "github.com/antonfisher/nested-logrus-formatter"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"os"
"time"
)
var logger *Logger
type Logger struct {
*logrus.Logger
Pid int
}
func init() {
logger = loggerInit("")
}
func NewPrivateLog(moduleName string) {
logger = loggerInit(moduleName)
}
func loggerInit(moduleName string) *Logger {
var logger = logrus.New()
//All logs will be printed
logger.SetLevel(logrus.Level(config.Config.Log.RemainLogLevel))
//Close std console output
src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
panic(err)
}
writer := bufio.NewWriter(src)
logger.SetOutput(writer)
//Log Console Print Style Setting
logger.SetFormatter(&nested.Formatter{
TimestampFormat: "2006-01-02 15:04:05.000",
HideKeys: false,
FieldsOrder: []string{"PID", "FilePath", "OperationID"},
})
//File name and line number display hook
logger.AddHook(newFileHook())
//Send logs to elasticsearch hook
if config.Config.Log.ElasticSearchSwitch {
logger.AddHook(newEsHook(moduleName))
}
//Log file segmentation hook
hook := NewLfsHook(time.Duration(config.Config.Log.RotationTime)*time.Hour, config.Config.Log.RemainRotationCount, moduleName)
logger.AddHook(hook)
return &Logger{
logger,
os.Getpid(),
}
}
func NewLfsHook(rotationTime time.Duration, maxRemainNum uint, moduleName string) logrus.Hook {
lfsHook := lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: initRotateLogs(rotationTime, maxRemainNum, "debug", moduleName),
logrus.InfoLevel: initRotateLogs(rotationTime, maxRemainNum, "info", moduleName),
logrus.WarnLevel: initRotateLogs(rotationTime, maxRemainNum, "warn", moduleName),
logrus.ErrorLevel: initRotateLogs(rotationTime, maxRemainNum, "error", moduleName),
}, &nested.Formatter{
TimestampFormat: "2006-01-02 15:04:05.000",
HideKeys: false,
FieldsOrder: []string{"PID", "FilePath", "OperationID"},
})
return lfsHook
}
func initRotateLogs(rotationTime time.Duration, maxRemainNum uint, level string, moduleName string) *rotatelogs.RotateLogs {
if moduleName != "" {
moduleName = moduleName + "."
}
writer, err := rotatelogs.New(
config.Config.Log.StorageLocation+moduleName+level+"."+"%Y-%m-%d",
rotatelogs.WithRotationTime(rotationTime),
rotatelogs.WithRotationCount(maxRemainNum),
)
if err != nil {
panic(err)
} else {
return writer
}
}
//Deprecated
func Info(token, OperationID, format string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"PID": logger.Pid,
"OperationID": OperationID,
}).Infof(format, args...)
}
//Deprecated
func Error(token, OperationID, format string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"PID": logger.Pid,
"OperationID": OperationID,
}).Errorf(format, args...)
}
//Deprecated
func Debug(token, OperationID, format string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"PID": logger.Pid,
"OperationID": OperationID,
}).Debugf(format, args...)
}
//Deprecated
func Warning(token, OperationID, format string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"PID": logger.Pid,
"OperationID": OperationID,
}).Warningf(format, args...)
}
//Deprecated
func InfoByArgs(format string, args ...interface{}) {
logger.WithFields(logrus.Fields{}).Infof(format, args)
}
//Deprecated
func ErrorByArgs(format string, args ...interface{}) {
logger.WithFields(logrus.Fields{}).Errorf(format, args...)
}
//Print log information in k, v format,
//kv is best to appear in pairs. tipInfo is the log prompt information for printing,
//and kv is the key and value for printing.
//Deprecated
func InfoByKv(tipInfo, OperationID string, args ...interface{}) {
fields := make(logrus.Fields)
argsHandle(OperationID, fields, args)
logger.WithFields(fields).Info(tipInfo)
}
//Deprecated
func ErrorByKv(tipInfo, OperationID string, args ...interface{}) {
fields := make(logrus.Fields)
argsHandle(OperationID, fields, args)
logger.WithFields(fields).Error(tipInfo)
}
//Deprecated
func DebugByKv(tipInfo, OperationID string, args ...interface{}) {
fields := make(logrus.Fields)
argsHandle(OperationID, fields, args)
logger.WithFields(fields).Debug(tipInfo)
}
//Deprecated
func WarnByKv(tipInfo, OperationID string, args ...interface{}) {
fields := make(logrus.Fields)
argsHandle(OperationID, fields, args)
logger.WithFields(fields).Warn(tipInfo)
}
//internal method
func argsHandle(OperationID string, fields logrus.Fields, args []interface{}) {
for i := 0; i < len(args); i += 2 {
if i+1 < len(args) {
fields[fmt.Sprintf("%v", args[i])] = args[i+1]
} else {
fields[fmt.Sprintf("%v", args[i])] = ""
}
}
fields["OperationID"] = OperationID
fields["PID"] = logger.Pid
}
func NewInfo(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Infoln(args)
}
func NewError(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Errorln(args)
}
func NewDebug(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Debugln(args)
}
func NewWarn(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Warnln(args)
}
|
package k8sml
import (
"reflect"
"strings"
)
type ContainerNetworkInterface struct {
ID string `yaml:"id"`
Kubernetes *Kubernetes
}
func (cni *ContainerNetworkInterface) GetID() string {
return cni.ID
}
func (cni *ContainerNetworkInterface) GetVariableValue(variable string) interface{} {
e := reflect.ValueOf(cni).Elem()
var value interface{}
for i := 0; i < e.NumField(); i++ {
if strings.ToLower(e.Type().Field(i).Name) == strings.ToLower(variable) {
value = e.Field(i).Interface()
return value
}
}
return nil
}
|
package main
import (
"fmt"
"time"
ByteArkSignerSDK "github.com/byteark/byteark-sdk-go"
)
func main() {
// Create signer options
signerOptions := ByteArkSignerSDK.SignerOptions{
AccessID: "fleet-1320",
AccessSecret: "2bpqxHOMUxVmkzA1",
}
// Create signer
createSignerError := ByteArkSignerSDK.CreateSigner(signerOptions)
// Error by CreateSigner should be check before signing process begin
if createSignerError != nil {
panic(createSignerError)
}
// Create sign options
signOptions := ByteArkSignerSDK.SignOptions{
"path_prefix": "/live/",
}
// Sign given url
signedURL, signError := ByteArkSignerSDK.Sign(
"https://example.cdn.byteark.com/path/to/file.png",
1514764800,
signOptions,
)
if signError != nil {
fmt.Printf("SignedURL: %s\n", signedURL)
} else {
panic(signError)
}
// Verify signedURL
pass, verifyError := ByteArkSignerSDK.Verify(
signedURL,
int(time.Now().Unix()),
)
if pass {
fmt.Println("Verify signedURL pass.")
} else {
panic(verifyError)
}
}
|
/*-
* Copyright 2015 Grammarly, 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.
*/
// Main rocker-compose executable
// type rocker-compose --help for more info
package main
import (
"compose"
"compose/ansible"
"compose/config"
"fmt"
"os"
"path"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
"github.com/fsouza/go-dockerclient"
"github.com/grammarly/rocker/src/rocker/dockerclient"
"github.com/grammarly/rocker/src/rocker/template"
)
var (
// Version that is passed on compile time through -ldflags
Version = "built locally"
// GitCommit that is passed on compile time through -ldflags
GitCommit = "none"
// GitBranch that is passed on compile time through -ldflags
GitBranch = "none"
// BuildTime that is passed on compile time through -ldflags
BuildTime = "none"
)
func init() {
log.SetOutput(os.Stdout)
log.SetLevel(log.InfoLevel)
}
func main() {
app := cli.NewApp()
app.Name = "rocker-compose"
app.Version = fmt.Sprintf("%s - %.7s (%s) %s", Version, GitCommit, GitBranch, BuildTime)
app.Usage = "Tool for docker orchestration"
app.Authors = []cli.Author{
{"Yura Bogdanov", "yuriy.bogdanov@grammarly.com"},
{"Stas Levental", "stas.levental@grammarly.com"},
}
composeFlags := []cli.Flag{
cli.StringFlag{
Name: "file, f",
Value: "compose.yml",
Usage: "Path to configuration file which should be run, if `-` is given as a value, then STDIN will be used",
},
cli.StringSliceFlag{
Name: "var",
Value: &cli.StringSlice{},
Usage: "Set variables to pass to build tasks, value is like \"key=value\"",
},
cli.BoolFlag{
Name: "dry, d",
Usage: "Don't execute any run/stop operations on target docker",
},
cli.BoolFlag{
Name: "print",
Usage: "just print the rendered compose config and exit",
},
}
app.Flags = append([]cli.Flag{
cli.BoolFlag{
Name: "verbose, vv",
},
cli.StringFlag{
Name: "log, l",
},
cli.BoolFlag{
Name: "json",
},
cli.StringFlag{
Name: "auth, a",
Value: "",
Usage: "Docker auth, username and password in user:password format",
},
}, dockerclient.GlobalCliParams()...)
app.Commands = []cli.Command{
{
Name: "run",
Usage: "execute manifest",
Action: runCommand,
Flags: append([]cli.Flag{
cli.BoolFlag{
Name: "force",
Usage: "Force recreation of current configuration",
},
cli.BoolFlag{
Name: "attach",
Usage: "Stream stdout of all containers to log",
},
cli.BoolFlag{
Name: "pull",
Usage: "Do pull images before running",
},
cli.DurationFlag{
Name: "wait",
Value: 1 * time.Second,
Usage: "Wait and check exit codes of launched containers",
},
cli.BoolFlag{
Name: "ansible",
Usage: "output json in ansible format for easy parsing",
},
}, composeFlags...),
},
{
Name: "pull",
Usage: "pull images specified in the manifest",
Action: pullCommand,
Flags: append([]cli.Flag{
cli.BoolFlag{
Name: "ansible",
Usage: "output json in ansible format for easy parsing",
},
}, composeFlags...),
},
{
Name: "rm",
Usage: "stop and remove any containers specified in the manifest",
Action: rmCommand,
Flags: composeFlags,
},
{
Name: "clean",
Usage: "cleanup old tags for images specified in the manifest",
Action: cleanCommand,
Flags: append([]cli.Flag{
cli.IntFlag{
Name: "keep, k",
Value: 5,
Usage: "number of last images to keep",
},
cli.BoolFlag{
Name: "ansible",
Usage: "output json in ansible format for easy parsing",
},
}, composeFlags...),
},
{
Name: "recover",
Usage: "recover containers from machine reboot or docker daemon restart",
Action: recoverCommand,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "dry, d",
Usage: "Don't execute any run/stop operations on target docker",
},
cli.DurationFlag{
Name: "wait",
Value: 1 * time.Second,
Usage: "Wait and check exit codes of launched containers",
},
},
},
dockerclient.InfoCommandSpec(),
}
app.CommandNotFound = func(ctx *cli.Context, command string) {
fmt.Printf("Command not found: %v\n", command)
os.Exit(1)
}
if err := app.Run(os.Args); err != nil {
fmt.Printf(err.Error())
os.Exit(1)
}
}
func runCommand(ctx *cli.Context) {
ansibleResp := initAnsubleResp(ctx)
// TODO: here we duplicate fatalf in both run(), pull() and clean()
// maybe refactor to make it cleaner
fatalf := func(err error) {
if ansibleResp != nil {
ansibleResp.Error(err).WriteTo(os.Stdout)
}
log.Fatal(err)
}
initLogs(ctx)
dockerCli := initDockerClient(ctx)
config := initComposeConfig(ctx, dockerCli)
auth := initAuthConfig(ctx)
compose, err := compose.New(&compose.Config{
Manifest: config,
Docker: dockerCli,
Force: ctx.Bool("force"),
DryRun: ctx.Bool("dry"),
Attach: ctx.Bool("attach"),
Wait: ctx.Duration("wait"),
Pull: ctx.Bool("pull"),
Auth: auth,
})
if err != nil {
fatalf(err)
}
// in case of --force given, first remove all existing containers
if ctx.Bool("force") {
if err := doRemove(ctx, config, dockerCli, auth); err != nil {
fatalf(err)
}
}
if err := compose.RunAction(); err != nil {
fatalf(err)
}
if ansibleResp != nil {
// ansibleResp.Success("done hehe").WriteTo(os.Stdout)
compose.WritePlan(ansibleResp).WriteTo(os.Stdout)
}
}
func pullCommand(ctx *cli.Context) {
ansibleResp := initAnsubleResp(ctx)
fatalf := func(err error) {
if ansibleResp != nil {
ansibleResp.Error(err).WriteTo(os.Stdout)
}
log.Fatal(err)
}
initLogs(ctx)
dockerCli := initDockerClient(ctx)
config := initComposeConfig(ctx, dockerCli)
auth := initAuthConfig(ctx)
compose, err := compose.New(&compose.Config{
Manifest: config,
Docker: dockerCli,
DryRun: ctx.Bool("dry"),
Auth: auth,
})
if err != nil {
fatalf(err)
}
if err := compose.PullAction(); err != nil {
fatalf(err)
}
if ansibleResp != nil {
// ansibleResp.Success("done hehe").WriteTo(os.Stdout)
compose.WritePlan(ansibleResp).WriteTo(os.Stdout)
}
}
func rmCommand(ctx *cli.Context) {
initLogs(ctx)
dockerCli := initDockerClient(ctx)
config := initComposeConfig(ctx, dockerCli)
auth := initAuthConfig(ctx)
if err := doRemove(ctx, config, dockerCli, auth); err != nil {
log.Fatal(err)
}
}
func cleanCommand(ctx *cli.Context) {
ansibleResp := initAnsubleResp(ctx)
fatalf := func(err error) {
if ansibleResp != nil {
ansibleResp.Error(err).WriteTo(os.Stdout)
}
log.Fatal(err)
}
initLogs(ctx)
dockerCli := initDockerClient(ctx)
config := initComposeConfig(ctx, dockerCli)
auth := initAuthConfig(ctx)
compose, err := compose.New(&compose.Config{
Manifest: config,
Docker: dockerCli,
DryRun: ctx.Bool("dry"),
Remove: true,
Auth: auth,
KeepImages: ctx.Int("keep"),
})
if err != nil {
fatalf(err)
}
if err := compose.CleanAction(); err != nil {
fatalf(err)
}
if ansibleResp != nil {
// ansibleResp.Success("done hehe").WriteTo(os.Stdout)
compose.WritePlan(ansibleResp).WriteTo(os.Stdout)
}
}
func recoverCommand(ctx *cli.Context) {
initLogs(ctx)
dockerCli := initDockerClient(ctx)
auth := initAuthConfig(ctx)
compose, err := compose.New(&compose.Config{
Docker: dockerCli,
DryRun: ctx.Bool("dry"),
Wait: ctx.Duration("wait"),
Recover: true,
Auth: auth,
})
if err != nil {
log.Fatal(err)
}
if err := compose.RecoverAction(); err != nil {
log.Fatal(err)
}
}
func initLogs(ctx *cli.Context) {
if ctx.GlobalBool("verbose") {
log.SetLevel(log.DebugLevel)
}
if ctx.GlobalBool("json") {
log.SetFormatter(&log.JSONFormatter{})
}
logFilename, err := toAbsolutePath(ctx.GlobalString("log"), false)
if err != nil {
log.Debugf("Initializing log: Skipped, because Log %s", err)
return
}
logFile, err := os.OpenFile(logFilename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
if err != nil {
log.Warnf("Initializing log: Cannot initialize log file %s due to error %s", logFilename, err)
return
}
log.SetOutput(logFile)
if path.Ext(logFilename) == ".json" {
log.SetFormatter(&log.JSONFormatter{})
}
log.Debugf("Initializing log: Successfuly started loggin to '%s'", logFilename)
}
func initComposeConfig(ctx *cli.Context, dockerCli *docker.Client) *config.Config {
file := ctx.String("file")
if file == "" {
log.Fatalf("Manifest file is empty")
os.Exit(1)
}
var (
manifest *config.Config
err error
bridgeIP *string
print = ctx.Bool("print")
)
vars, err := template.VarsFromStrings(ctx.StringSlice("var"))
if err != nil {
log.Fatal(err)
os.Exit(1)
}
// TODO: find better place for providing this helper
funcs := map[string]interface{}{
// lazy get bridge ip
"bridgeIp": func() (ip string, err error) {
if bridgeIP == nil {
ip, err = compose.GetBridgeIP(dockerCli)
if err != nil {
return "", err
}
bridgeIP = &ip
}
return *bridgeIP, nil
},
}
if file == "-" {
if !print {
log.Infof("Reading manifest from STDIN")
}
manifest, err = config.ReadConfig(file, os.Stdin, vars, funcs, print)
} else {
if !print {
log.Infof("Reading manifest: %s", file)
}
manifest, err = config.NewFromFile(file, vars, funcs, print)
}
if err != nil {
log.Fatal(err)
}
return manifest
}
func initDockerClient(ctx *cli.Context) *docker.Client {
dockerClient, err := dockerclient.NewFromCli(ctx)
if err != nil {
log.Fatal(err)
}
return dockerClient
}
func initAuthConfig(ctx *cli.Context) *compose.AuthConfig {
auth := &compose.AuthConfig{}
authParam := globalString(ctx, "auth")
if strings.Contains(authParam, ":") {
userPass := strings.Split(authParam, ":")
auth.Username = userPass[0]
auth.Password = userPass[1]
}
return auth
}
func initAnsubleResp(ctx *cli.Context) (ansibleResp *ansible.Response) {
if ctx.Bool("ansible") {
ansibleResp = &ansible.Response{}
if !ctx.GlobalIsSet("log") {
ansibleResp.Error(fmt.Errorf("--log param should be provided for ansible mode")).WriteTo(os.Stdout)
os.Exit(1)
}
}
return
}
func doRemove(ctx *cli.Context, config *config.Config, dockerCli *docker.Client, auth *compose.AuthConfig) error {
compose, err := compose.New(&compose.Config{
Manifest: config,
Docker: dockerCli,
DryRun: ctx.Bool("dry"),
Remove: true,
Auth: auth,
})
if err != nil {
return err
}
return compose.RunAction()
}
func toAbsolutePath(filePath string, shouldExist bool) (string, error) {
if filePath == "" {
return filePath, fmt.Errorf("File path is not provided")
}
if !path.IsAbs(filePath) {
wd, err := os.Getwd()
if err != nil {
log.Errorf("Cannot get absolute path to %s due to error %s", filePath, err)
return filePath, err
}
filePath = path.Join(wd, filePath)
}
if _, err := os.Stat(filePath); os.IsNotExist(err) && shouldExist {
return filePath, fmt.Errorf("No such file or directory: %s", filePath)
}
return filePath, nil
}
// globalString fixes string arguments enclosed with double quotes
// 'docker-machine config' gives such arguments
func globalString(c *cli.Context, name string) string {
str := c.GlobalString(name)
if len(str) >= 2 && str[0] == '\u0022' && str[len(str)-1] == '\u0022' {
str = str[1 : len(str)-1]
}
return str
}
|
package msg
const (
ListStr = "获取列表"
DelStr = "删除"
GetStr = "获取"
CreateStr = "创建"
SuccessStr = "成功"
ErrorStr = "失败"
StateStr = "状态"
Had = "已存在"
NoHad = "不存在"
MastHasOneStr = "至少要有一个"
IdCardNumErr = "身份证不合法"
)
// 获取操作提示
func GetTodoResMsg(str string, error bool) string {
if error {
return str + ErrorStr
}
return str + SuccessStr
}
|
package strings
import (
"text/template"
)
var FuncMap = template.FuncMap {
"add": Add,
"dateFormat": DateFormat,
"findRe": FindRe,
"findSubRe": FindSubRe,
"floatToInt": FloatToInt,
"inchesToFeet": InchesToFeet,
"lower": ToLower,
"minify": MinifyCode,
"markdown": Markdown,
"marshal": Marshal,
"matchRe": MatchRe,
"replace": Replace,
"replaceRe": ReplaceRe,
"subtract": Subtract,
"trim": Trim,
"unescape": Unescape,
"upper": ToUpper,
}
|
package run
import (
"time"
floc "gopkg.in/workanator/go-floc.v1"
)
/*
Wait waits until the condition is met. The function falls into sleep with the
duration given between condition checks. The function does not run any job
actually and just repeatedly checks predicate return value. When the predicate
returns true the function finishes.
Summary:
- Run jobs in goroutines : N/A
- Wait all jobs finish : N/A
- Run order : N/A
Diagram:
NO
+------(SLEEP)------+
| |
V | YES
----(CONDITION MET?)--+----->
*/
func Wait(predicate floc.Predicate, duration time.Duration) floc.Job {
return func(flow floc.Flow, state floc.State, update floc.Update) {
for !predicate(state) && !flow.IsFinished() {
time.Sleep(duration)
}
}
}
|
package DbBase
import (
"xwork/Extend/Cache"
_ "xwork/Extend/Cache/Memcache"
"os"
"github.com/sirupsen/logrus"
)
func InitCache() {
ca := Cache.NewCache("default")
if ca == nil {
logrus.Error("cache: server connection fail name default")
os.Exit(0)
}
}
|
// Example Documentation: https://objectrocket.com/docs/redis_go_examples.html
// Driver Documentation: https://github.com/garyburd/redigo
// TODO: Test this with SSL. Reformat example so it is more consistent with others (i.e. ping instead of adding and removing stuff from DB)
package main
import "github.com/garyburd/redigo/redis"
import "fmt"
func main() {
//Connect
options := DialOptions {
}
c, err := redis.Dial("tcp", "bf36cdba2cc244d5b145f71c6ce4ae72.publb.rackspaceclouddb.com:6380")
if err != nil {
panic(err)
}
defer c.Close()
//Authenticate
c.Do("AUTH", "CskHfrMmPGvdNxPBFKu4rQfhPvDK33brEJca")
//Set two keys
// c.Do("SET", "best_car_ever", "Tesla Model S")
// c.Do("SET", "worst_car_ever", "Geo Metro")
//
// //Get a key
// best_car_ever, err := redis.String(c.Do("GET", "best_car_ever"))
// if err != nil {
// fmt.Println("best_car_ever not found")
// } else {
// //Print our key if it exists
// fmt.Println("best_car_ever exists: " + best_car_ever)
// }
//
// //Delete a key
// c.Do("DEL", "worst_car_ever")
//
// //Try to retrieve the key we just deleted
// worst_car_ever, err := redis.String(c.Do("GET", "worst_car_ever"))
// if err != nil {
// fmt.Println("worst_car_ever not found", err)
// } else {
// //Print our key if it exists
// fmt.Println(worst_car_ever)
// }
}
|
package cli
import (
"context"
"os"
"os/signal"
)
func withTrapCancel(ctx context.Context, ss ...os.Signal) (context.Context, context.CancelFunc) {
ret, cancel := context.WithCancel(ctx)
ch := make(chan os.Signal, len(ss))
go func() {
defer signal.Stop(ch)
<-ch
cancel()
}()
signal.Notify(ch, ss...)
return ret, cancel
}
func trapSeq(n int, ss []os.Signal, fn func(os.Signal)) {
var (
ch = make(chan os.Signal, len(ss))
cnt = make(map[os.Signal]int)
)
go func() {
defer signal.Stop(ch)
for sig := range ch {
m := cnt[sig] + 1
if m != n {
cnt[sig] = m
} else {
cnt[sig] = 0
fn(sig)
}
}
}()
signal.Notify(ch, ss...)
}
|
package kuu
import (
"testing"
)
// TestRandCode
func TestRandCode(t *testing.T) {
t.Log(RandCode(4))
t.Log(RandCode(6))
t.Log(RandCode())
t.Log(RandCode(10))
}
|
package config
const(
RpcServiceName = "com.salpadding.srv"
)
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 main
import (
"encoding/json"
"fmt"
"strconv"
// "strings"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
// ============================================================================================================================
// write() - genric write variable into ledger
//
// Shows Off PutState() - writting a key/value into the ledger
//
// Inputs - Array of strings
// 0 , 1
// key , value
// "abc" , "test"
// ============================================================================================================================
func write(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var key, value string
var err error
fmt.Println("starting write")
if len(args) != 2 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 2. key of the variable and value to set"))
}
// input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
key = args[0] //rename for funsies
value = args[1]
err = stub.PutState(key, []byte(value)) //write the variable into the ledger
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end write")
return shim.Success(formatSuccess("NA","NA",nil))
}
func swappingStation_init(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting swappingStation_init")
if len(args) != 9 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 9"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
var swappingStation SwappingStation
swappingStation.Id_swappingStation = args[0]
swappingStation.Password = args[1]
swappingStation.SwappingStationName = args[2]
swappingStation.GeoCoordinates = args[3]
swappingStation.Address = args[4]
swappingStation.LicenseNumber = args[5]
swappingStation.EmailId = args[6]
swappingStation.ContactNumber = args[7]
swappingStation.Company = args[8]
swappingStation.DocType = "swappingStation"
fmt.Println(swappingStation)
//check if swappingStation already exists
_, err = get_swappingStation(stub, swappingStation.Id_swappingStation)
if err == nil {
fmt.Println("This swappingStation already exists - " + swappingStation.Id_swappingStation)
return shim.Error(formatError("NA","NA","This swappingStation already exists - " + swappingStation.Id_swappingStation))
}
//Store the swappingStation in ledger
swappingStationAsBytes, _ := json.Marshal(swappingStation)
err = stub.PutState(swappingStation.Id_swappingStation, swappingStationAsBytes)
if err !=nil {
fmt.Println("Could not store swappingStation")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end init swappingStation ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func swappingStation_payToWallet(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting swappingStation_payToWallet")
if len(args) != 2 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 2"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_swappingStation := args[0]
charge,_ := strconv.ParseInt(args[1],10,0)
swappingStation,err := get_swappingStation(stub,id_swappingStation)
if err != nil {
fmt.Println("SwappingStation not found in Blockchain - " + id_swappingStation)
return shim.Error(formatError("NA","NA",err.Error()))
}
swappingStation.Id_swappingStation = id_swappingStation
swappingStation.Wallet += charge
//Store the swappingStation in ledger
swappingStationAsBytes, _ := json.Marshal(swappingStation)
err = stub.PutState(swappingStation.Id_swappingStation, swappingStationAsBytes)
if err !=nil {
fmt.Println("Could not store swappingStation")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end payToWallet swappingStation ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func lender_init(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting lender_init")
if len(args) != 7 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 7"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
var lender Lender
lender.Id_lender = args[0]
lender.Password = args[1]
lender.LenderName = args[2]
lender.Address = args[3]
lender.AadharNumber = args[4]
lender.EmailId = args[5]
lender.MobileNumber = args[6]
lender.DocType = "lender"
fmt.Println(lender)
//check if user already exists
_, err = get_lender(stub, lender.Id_lender)
if err == nil {
fmt.Println("This lender already exists - " + lender.Id_lender)
return shim.Error(formatError("NA","NA","This lender already exists - " + lender.Id_lender))
}
//Store the lender in ledger
lenderAsBytes, _ := json.Marshal(lender)
err = stub.PutState(lender.Id_lender, lenderAsBytes)
if err !=nil {
fmt.Println("Could not store lender")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end init lender ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func lender_payToWallet(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting lender_payToWallet")
if len(args) != 2 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 2"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_lender := args[0]
charge,_ := strconv.ParseInt(args[1],10,0)
lender,err := get_lender(stub,id_lender)
if err != nil {
fmt.Println("SwappingStation not found in Blockchain - " + id_lender)
return shim.Error(formatError("NA","NA",err.Error()))
}
lender.Id_lender = id_lender
lender.Wallet += charge
//Store the lender in ledger
lenderAsBytes, _ := json.Marshal(lender)
err = stub.PutState(lender.Id_lender, lenderAsBytes)
if err !=nil {
fmt.Println("Could not store lender")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end payToWallet lender ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func lender_payFromWallet(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting lender_payFromWallet")
if len(args) != 2 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 2"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_lender := args[0]
charge,_ := strconv.ParseInt(args[1],10,0)
lender,err := get_lender(stub,id_lender)
if err != nil {
fmt.Println("SwappingStation not found in Blockchain - " + id_lender)
return shim.Error(formatError("NA","NA",err.Error()))
}
lender.Id_lender = id_lender
lender.Wallet -= charge
//Store the lender in ledger
lenderAsBytes, _ := json.Marshal(lender)
err = stub.PutState(lender.Id_lender, lenderAsBytes)
if err !=nil {
fmt.Println("Could not store lender")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end payFromWallet lender ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func battery_init(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting battery_init")
if len(args) != 10 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 10"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
var battery Battery
battery.Id_battery = args[0]
battery.ModelNumber = args[1]
SoC_uint64, _ := strconv.ParseUint(args[2],10,0)
battery.SoC = uint8(SoC_uint64)
SoH_uint64, _ := strconv.ParseUint(args[3], 10, 0)
battery.SoH = uint8(SoH_uint64)
EnergyContent_float64, _ := strconv.ParseFloat(args[4],0)
battery.EnergyContent = float32(EnergyContent_float64)
Cdc_uint64, _ := strconv.ParseUint(args[5],10,0)
battery.Cdc = uint16(Cdc_uint64)
battery.Owner = args[6]
battery.User = args[7]
battery.ManufacturerId = args[8]
battery.ManufactureDate = args[9]
battery.Status = "Available"
battery.DocType = "battery"
fmt.Println(battery)
//Check if battery already exists
_, err = get_battery(stub, battery.Id_battery)
if err == nil {
fmt.Println("This battery already exists - " + battery.Id_battery)
return shim.Error(formatError("NA","NA","This battery already exists - " + battery.Id_battery))
}
//Store the battery in ledger
batteryAsBytes, _ := json.Marshal(battery)
err = stub.PutState(battery.Id_battery, batteryAsBytes)
if err !=nil {
fmt.Println("Could not store battery")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end init battery ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func battery_transferBSS2Lnd(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting battery_transferBSS2Lnd")
if len(args) != 6 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 6"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_battery := args[0]
battery ,err := get_battery(stub,id_battery)
if err != nil {
fmt.Println("battery not found in Blockchain - " + id_battery)
return shim.Error(formatError("NA","NA",err.Error()))
}
if battery.Status == "In_Use" {
return shim.Error(formatError("NA","NA","Battery already in use - " + id_battery))
}
SoC_uint64, _ := strconv.ParseUint(args[1],10,0)
battery.SoC = uint8(SoC_uint64)
SoH_uint64, _ := strconv.ParseUint(args[2], 10, 0)
battery.SoH = uint8(SoH_uint64)
EnergyContent_float64, _ := strconv.ParseFloat(args[3],0)
battery.EnergyContent = float32(EnergyContent_float64)
Cdc_uint64, _ := strconv.ParseUint(args[4],10,0)
battery.Cdc = uint16(Cdc_uint64)
battery.User = args[5]
battery.Status = "In_Use"
//Store the battery in ledger
batteryAsBytes, _ := json.Marshal(battery)
err = stub.PutState(battery.Id_battery, batteryAsBytes)
if err !=nil {
fmt.Println("Could not store battery")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end transferBSS2Lnd battery ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func battery_transferLnd2BSS(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting battery_transferLnd2BSS")
if len(args) != 6 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 6"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_battery := args[0]
battery ,err := get_battery(stub,id_battery)
if err != nil {
fmt.Println("battery not found in Blockchain - " + id_battery)
return shim.Error(formatError("NA","NA",err.Error()))
}
if battery.Status == "In_Service" {
return shim.Error(formatError("NA","NA","Battery already in service- " + id_battery))
}
SoC_uint64, _ := strconv.ParseUint(args[1],10,0)
battery.SoC = uint8(SoC_uint64)
SoH_uint64, _ := strconv.ParseUint(args[2], 10, 0)
battery.SoH = uint8(SoH_uint64)
EnergyContent_float64, _ := strconv.ParseFloat(args[3],0)
battery.EnergyContent = float32(EnergyContent_float64)
Cdc_uint64, _ := strconv.ParseUint(args[4],10,0)
battery.Cdc = uint16(Cdc_uint64)
battery.User = args[5]
battery.Status = "In_Service"
//Store the battery in ledger
batteryAsBytes, _ := json.Marshal(battery)
err = stub.PutState(battery.Id_battery, batteryAsBytes)
if err !=nil {
fmt.Println("Could not store battery")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end transferLnd2BSS battery ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func battery_returnFromService(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting battery_returnFromService")
if len(args) != 6 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 6"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_battery := args[0]
battery ,err := get_battery(stub,id_battery)
if err != nil {
fmt.Println("battery not found in Blockchain - " + id_battery)
return shim.Error(formatError("NA","NA",err.Error()))
}
if battery.Status == "Available" {
return shim.Error(formatError("NA","NA","Battery already returned from service- " + id_battery))
}
SoC_uint64, _ := strconv.ParseUint(args[1],10,0)
battery.SoC = uint8(SoC_uint64)
SoH_uint64, _ := strconv.ParseUint(args[2], 10, 0)
battery.SoH = uint8(SoH_uint64)
EnergyContent_float64, _ := strconv.ParseFloat(args[3],0)
battery.EnergyContent = float32(EnergyContent_float64)
Cdc_uint64, _ := strconv.ParseUint(args[4],10,0)
battery.Cdc = uint16(Cdc_uint64)
battery.User = args[5]
battery.Status = "Available"
//Store the battery in ledger
batteryAsBytes, _ := json.Marshal(battery)
err = stub.PutState(battery.Id_battery, batteryAsBytes)
if err !=nil {
fmt.Println("Could not store battery")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end returnFromService battery ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func battery_markStolen(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting battery_markStolen")
if len(args) != 1 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 1"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_battery := args[0]
battery ,err := get_battery(stub,id_battery)
if err != nil {
fmt.Println("battery not found in Blockchain - " + id_battery)
return shim.Error(formatError("NA","NA",err.Error()))
}
if battery.Status == "Stolen" {
return shim.Error(formatError("NA","NA","Battery already marked stolen - " + id_battery))
}
battery.Status = "Stolen"
//Store the battery in ledger
batteryAsBytes, _ := json.Marshal(battery)
err = stub.PutState(battery.Id_battery, batteryAsBytes)
if err !=nil {
fmt.Println("Could not store battery")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end markStolen battery ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func battery_markError(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting battery_markError")
if len(args) != 1 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 1"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_battery := args[0]
battery ,err := get_battery(stub,id_battery)
if err != nil {
fmt.Println("battery not found in Blockchain - " + id_battery)
return shim.Error(formatError("NA","NA",err.Error()))
}
if battery.Status == "Error" {
return shim.Error(formatError("NA","NA","Battery already marked error - " + id_battery))
}
battery.Status = "Error"
//Store the battery in ledger
batteryAsBytes, _ := json.Marshal(battery)
err = stub.PutState(battery.Id_battery, batteryAsBytes)
if err !=nil {
fmt.Println("Could not store battery")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end markError battery ")
return shim.Success(formatSuccess("NA","NA",nil))
}
func battery_markExpired(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var err error
fmt.Println("starting battery_markExpired")
if len(args) != 1 {
return shim.Error(formatError("NA","NA","Incorrect number of arguments. Expecting 1"))
}
//input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(formatError("NA","NA",err.Error()))
}
id_battery := args[0]
battery ,err := get_battery(stub,id_battery)
if err != nil {
fmt.Println("battery not found in Blockchain - " + id_battery)
return shim.Error(formatError("NA","NA",err.Error()))
}
if battery.Status == "Expired" {
return shim.Error(formatError("NA","NA","Battery already marked expired - " + id_battery))
}
battery.Status = "Expired"
//Store the battery in ledger
batteryAsBytes, _ := json.Marshal(battery)
err = stub.PutState(battery.Id_battery, batteryAsBytes)
if err !=nil {
fmt.Println("Could not store battery")
return shim.Error(formatError("NA","NA",err.Error()))
}
fmt.Println("- end markExpired battery ")
return shim.Success(formatSuccess("NA","NA",nil))
}
|
package imagehelper
import (
"image"
_ "image/jpeg"
_ "image/png"
"os"
)
func GetImageDimension(srcPath string) (width int, height int, err error) {
src, err := os.Open(srcPath)
if err != nil {
return 0, 0, err
}
defer src.Close()
image, _, err := image.DecodeConfig(src)
if err != nil {
return 0, 0, err
}
return image.Width, image.Height, nil
}
|
// Copyright 2020. Akamai Technologies, 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 (
"encoding/json"
"fmt"
"os"
"github.com/spf13/cobra"
)
// listCmd represents the list command
var userDiagnosticsListCmd = &cobra.Command{
Use: userDiagnosticsListUse,
Aliases: []string{"ls"},
Short: userDiagnosticsListShortDescription,
Long: userDiagnosticsListLongDescription,
Run: func(cmd *cobra.Command, args []string) {
resp, byt := doHTTPRequest("GET", "/diagnostic-tools/v2/end-user-links?"+clientTypeKey+"="+clientTypeValue, nil)
if resp.StatusCode == 200 {
var responseStruct Wrapper
var responseStructJson EndUserDiagnosticLinkJson
err := json.Unmarshal(*byt, &responseStruct)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if jsonString {
responseStructJson.ReportedTime = getReportedTime()
responseStructJson.EndUserDiagnosticLinks = responseStruct.EndUserDiagnosticLinks
resJson, _ := json.MarshalIndent(responseStructJson, "", " ")
fmt.Println(string(resJson))
return
}
printListUserDiagnosticData(responseStruct.EndUserDiagnosticLinks)
} else {
printResponseError(byt)
}
},
}
func init() {
userDiagnosticsCmd.AddCommand(userDiagnosticsListCmd)
}
|
package translator
import (
"github.com/stretchr/testify/require"
"testing"
)
func TestTranslateEnglishToKlingon(t *testing.T) {
tests := []struct{
input string
output string
}{
{"Nyota Uhura", "0xF8DB 0xF8E8 0xF8DD 0xF8E3 0xF8D0 0x0020 0xF8E5 0xF8D6 0xF8E5 0xF8E1 0xF8D0"},
{"Data", "0xF8D3 0xF8D0 0xF8E3 0xF8D0"},
{"Picard", ""}, // c cannot translate to klingon
{"Spock", ""}, // c and k cannot translate to klingon
{"Worf", ""}, // f cannot translate to klingon
}
for _, test := range tests {
klingon, _ := TranslateEnglishToKlingon(test.input)
require.Equal(t, test.output, klingon, test)
}
}
|
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2019 Dell, 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 translib
import (
"errors"
"strings"
log "github.com/golang/glog"
"github.com/openconfig/ygot/ygot"
"github.com/openconfig/ygot/ytypes"
"github.com/openconfig/ygot/util"
"reflect"
"github.com/Azure/sonic-mgmt-common/translib/db"
"github.com/Azure/sonic-mgmt-common/translib/ocbinds"
"github.com/Azure/sonic-mgmt-common/translib/tlerr"
"github.com/Azure/sonic-mgmt-common/translib/transformer"
"github.com/Azure/sonic-mgmt-common/translib/utils"
"sync"
)
var ()
type CommonApp struct {
pathInfo *PathInfo
body []byte
ygotRoot *ygot.GoStruct
ygotTarget *interface{}
skipOrdTableChk bool
cmnAppTableMap map[int]map[db.DBNum]map[string]map[string]db.Value
cmnAppYangDefValMap map[string]map[string]db.Value
cmnAppYangAuxMap map[string]map[string]db.Value
appOptions
}
var cmnAppInfo = appInfo{appType: reflect.TypeOf(CommonApp{}),
ygotRootType: nil,
isNative: false,
tablesToWatch: nil}
func init() {
register_model_path := []string{"/sonic-", "*"} // register yang model path(s) to be supported via common app
for _, mdl_pth := range register_model_path {
err := register(mdl_pth, &cmnAppInfo)
if err != nil {
log.Fatal("Register Common app module with App Interface failed with error=", err, "for path=", mdl_pth)
}
}
mdlCpblt := transformer.AddModelCpbltInfo()
if mdlCpblt == nil {
log.Warning("Failure in fetching model capabilities data.")
} else {
for yngMdlNm, mdlDt := range(mdlCpblt) {
err := addModel(&ModelData{Name: yngMdlNm, Org: mdlDt.Org, Ver: mdlDt.Ver})
if err != nil {
log.Warningf("Adding model data for module %v to appinterface failed with error=%v", yngMdlNm, err)
}
}
}
}
func (app *CommonApp) initialize(data appData) {
log.Info("initialize:path =", data.path)
pathInfo := NewPathInfo(data.path)
*app = CommonApp{pathInfo: pathInfo, body: data.payload, ygotRoot: data.ygotRoot, ygotTarget: data.ygotTarget, skipOrdTableChk: false}
app.appOptions = data.appOptions
}
func (app *CommonApp) translateCreate(d *db.DB) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
log.Info("translateCreate:path =", app.pathInfo.Path)
keys, err = app.translateCRUDCommon(d, CREATE)
return keys, err
}
func (app *CommonApp) translateUpdate(d *db.DB) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
log.Info("translateUpdate:path =", app.pathInfo.Path)
keys, err = app.translateCRUDCommon(d, UPDATE)
return keys, err
}
func (app *CommonApp) translateReplace(d *db.DB) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
log.Info("translateReplace:path =", app.pathInfo.Path)
keys, err = app.translateCRUDCommon(d, REPLACE)
return keys, err
}
func (app *CommonApp) translateDelete(d *db.DB) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
log.Info("translateDelete:path =", app.pathInfo.Path)
keys, err = app.translateCRUDCommon(d, DELETE)
return keys, err
}
func (app *CommonApp) translateGet(dbs [db.MaxDB]*db.DB) error {
var err error
log.Info("translateGet:path =", app.pathInfo.Path)
return err
}
func (app *CommonApp) translateSubscribe(req translateSubRequest) (translateSubResponse, error) {
return emptySubscribeResponse(req.path)
}
func (app *CommonApp) processSubscribe(req processSubRequest) (processSubResponse, error) {
return processSubResponse{}, tlerr.New("not implemented")
}
func (app *CommonApp) translateAction(dbs [db.MaxDB]*db.DB) error {
var err error
log.Info("translateAction:path =", app.pathInfo.Path, app.body)
return err
}
func (app *CommonApp) processCreate(d *db.DB) (SetResponse, error) {
var err error
var resp SetResponse
log.Info("processCreate:path =", app.pathInfo.Path)
targetType := reflect.TypeOf(*app.ygotTarget)
log.Infof("processCreate: Target object is a <%s> of Type: %s", targetType.Kind().String(), targetType.Elem().Name())
if err = app.processCommon(d, CREATE); err != nil {
log.Warning(err)
resp = SetResponse{ErrSrc: AppErr}
}
return resp, err
}
func (app *CommonApp) processUpdate(d *db.DB) (SetResponse, error) {
var err error
var resp SetResponse
log.Info("processUpdate:path =", app.pathInfo.Path)
if err = app.processCommon(d, UPDATE); err != nil {
log.Warning(err)
resp = SetResponse{ErrSrc: AppErr}
}
return resp, err
}
func (app *CommonApp) processReplace(d *db.DB) (SetResponse, error) {
var err error
var resp SetResponse
log.Info("processReplace:path =", app.pathInfo.Path)
if err = app.processCommon(d, REPLACE); err != nil {
log.Warning(err)
resp = SetResponse{ErrSrc: AppErr}
}
return resp, err
}
func (app *CommonApp) processDelete(d *db.DB) (SetResponse, error) {
var err error
var resp SetResponse
log.Infof("processDelete:path = %s, deleteEmptyEntry = %v", app.pathInfo.Path, app.deleteEmptyEntry)
if err = app.processCommon(d, DELETE); err != nil {
log.Warning(err)
resp = SetResponse{ErrSrc: AppErr}
}
return resp, err
}
func (app *CommonApp) processGet(dbs [db.MaxDB]*db.DB) (GetResponse, error) {
var err error
var payload []byte
var resPayload []byte
log.Info("processGet:path =", app.pathInfo.Path)
txCache := new(sync.Map)
for {
origXfmrYgotRoot, _ := ygot.DeepCopy((*app.ygotRoot).(ygot.GoStruct))
isEmptyPayload := false
appYgotStruct := (*app.ygotRoot).(ygot.GoStruct)
payload, isEmptyPayload, err = transformer.GetAndXlateFromDB(app.pathInfo.Path, &appYgotStruct, dbs, txCache)
if err != nil {
log.Warning("transformer.GetAndXlateFromDB() returned : ", err)
resPayload = payload
break
}
if strings.HasPrefix(app.pathInfo.Path, "/sonic") && isEmptyPayload {
log.Info("transformer.GetAndXlateFromDB() returned EmptyPayload")
resPayload = payload
break
}
targetObj, tgtObjCastOk := (*app.ygotTarget).(ygot.GoStruct)
if !tgtObjCastOk {
/*For ygotTarget populated by tranlib, for query on leaf level and list(without instance) level,
casting to GoStruct fails so use the parent node of ygotTarget to Unmarshall the payload into*/
log.Infof("Use GetParentNode() instead of casting ygotTarget to GoStruct, uri - %v", app.pathInfo.Path)
targetUri := app.pathInfo.Path
parentTargetObj, _, getParentNodeErr := getParentNode(&targetUri, (*app.ygotRoot).(*ocbinds.Device))
if getParentNodeErr != nil {
log.Warningf("getParentNode() failure for uri %v", app.pathInfo.Path)
resPayload = payload
break
}
if parentTargetObj != nil {
targetObj, tgtObjCastOk = (*parentTargetObj).(ygot.GoStruct)
if !tgtObjCastOk {
log.Warningf("Casting of parent object returned from getParentNode() to GoStruct failed(uri - %v)", app.pathInfo.Path)
resPayload = payload
break
}
} else {
log.Warningf("getParentNode() returned a nil Object for uri %v", app.pathInfo.Path)
resPayload = payload
break
}
}
if targetObj != nil {
updateListEntriesOpt := ytypes.AllowUpdateInListMap{}
err = ocbinds.Unmarshal(payload, targetObj, &updateListEntriesOpt)
if err != nil {
log.Warning("ocbinds.Unmarshal() returned : ", err)
resPayload = payload
break
}
resYgot := (*app.ygotRoot)
if !strings.HasPrefix(app.pathInfo.Path, "/sonic") {
if isEmptyPayload {
if areEqual(appYgotStruct, origXfmrYgotRoot) {
log.Info("origXfmrYgotRoot and appYgotStruct are equal.")
// No data available in appYgotStruct.
if transformer.IsLeafNode(app.pathInfo.Path) {
//if leaf not exist in DB subtree won't fill ygotRoot, as per RFC return err
resPayload = payload
log.Info("No data found for leaf.")
err = tlerr.NotFound("Resource not found")
break
}
resPayload = payload
log.Info("No data available")
//TODO: Return not found error
//err = tlerr.NotFound("Resource not found")
break
}
resYgot = appYgotStruct
}
}
if resYgot != nil {
resPayload, err = generateGetResponsePayload(app.pathInfo.Path, resYgot.(*ocbinds.Device), app.ygotTarget)
if err != nil {
log.Warning("generateGetResponsePayload() couldn't generate payload.")
resPayload = payload
}
} else {
resPayload = payload
}
break
} else {
log.Warning("processGet. targetObj is null. Unable to Unmarshal payload")
resPayload = payload
break
}
}
return GetResponse{Payload: resPayload}, err
}
func (app *CommonApp) processAction(dbs [db.MaxDB]*db.DB) (ActionResponse, error) {
var resp ActionResponse
var err error
resp.Payload, err = transformer.CallRpcMethod(app.pathInfo.Path, app.body, dbs)
log.Info("transformer.CallRpcMethod() returned")
return resp, err
}
func (app *CommonApp) translateCRUDCommon(d *db.DB, opcode int) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
var tblsToWatch []*db.TableSpec
txCache := new(sync.Map)
log.Info("translateCRUDCommon:path =", app.pathInfo.Path)
// translate yang to db
result, defValMap, auxMap, err := transformer.XlateToDb(app.pathInfo.Path, opcode, d, (*app).ygotRoot, (*app).ygotTarget, (*app).body, txCache, &app.skipOrdTableChk)
log.Info("transformer.XlateToDb() returned result DB map - ", result, "\nDefault value Db Map - ", defValMap, "\nAux Db Map - ", auxMap)
if err != nil {
log.Warning(err)
return keys, err
}
app.cmnAppTableMap = result
app.cmnAppYangDefValMap = defValMap
app.cmnAppYangAuxMap = auxMap //used for Replace case
if len(result) == 0 {
log.Info("XlatetoDB() returned empty map")
//Note: Get around for no redis ABNF Schema for set(temporary)
//`err = errors.New("transformer.XlatetoDB() returned empty map")
return keys, err
}
moduleNm, err := transformer.GetModuleNmFromPath(app.pathInfo.Path)
if (err != nil) || (len(moduleNm) == 0) {
log.Warning("GetModuleNmFromPath() couldn't fetch module name.")
return keys, err
}
var resultTblList []string
for _, dbMap := range result { //Get dependency list for all tables in result
for _, resMap := range dbMap { //Get dependency list for all tables in result
for tblnm := range resMap { //Get dependency list for all tables in result
resultTblList = append(resultTblList, tblnm)
}
}
}
log.Info("Result Tables List", resultTblList)
// Get list of tables to watch
if len(resultTblList) > 0 {
depTbls := transformer.GetTablesToWatch(resultTblList, moduleNm)
if len(depTbls) == 0 {
log.Warningf("Couldn't get Tables to watch for module %v", moduleNm)
err = errors.New("GetTablesToWatch returned empty slice")
return keys, err
}
for _, tbl := range depTbls {
tblsToWatch = append(tblsToWatch, &db.TableSpec{Name: tbl})
}
}
log.Info("Tables to watch", tblsToWatch)
cmnAppInfo.tablesToWatch = tblsToWatch
keys, err = app.generateDbWatchKeys(d, false)
return keys, err
}
func (app *CommonApp) processCommon(d *db.DB, opcode int) error {
var err error
if len(app.cmnAppTableMap) == 0 {
return err
}
log.Info("Processing DB operation for ", app.cmnAppTableMap)
switch opcode {
case CREATE:
log.Info("CREATE case")
case UPDATE:
log.Info("UPDATE case")
case REPLACE:
log.Info("REPLACE case")
case DELETE:
log.Info("DELETE case")
}
// Handle delete first if any available
if _, ok := app.cmnAppTableMap[DELETE][db.ConfigDB]; ok {
err = app.cmnAppDelDbOpn(d, DELETE, app.cmnAppTableMap[DELETE][db.ConfigDB])
if err != nil {
log.Info("Process delete fail. cmnAppDelDbOpn error:", err)
return err
}
}
// Handle create operation next
if _, ok := app.cmnAppTableMap[CREATE][db.ConfigDB]; ok {
err = app.cmnAppCRUCommonDbOpn(d, CREATE, app.cmnAppTableMap[CREATE][db.ConfigDB])
if err != nil {
log.Info("Process create fail. cmnAppCRUCommonDbOpn error:", err)
return err
}
}
// Handle update and replace operation next
if _, ok := app.cmnAppTableMap[UPDATE][db.ConfigDB]; ok {
err = app.cmnAppCRUCommonDbOpn(d, UPDATE, app.cmnAppTableMap[UPDATE][db.ConfigDB])
if err != nil {
log.Info("Process update fail. cmnAppCRUCommonDbOpn error:", err)
return err
}
}
if _, ok := app.cmnAppTableMap[REPLACE][db.ConfigDB]; ok {
err = app.cmnAppCRUCommonDbOpn(d, REPLACE, app.cmnAppTableMap[REPLACE][db.ConfigDB])
if err != nil {
log.Info("Process replace fail. cmnAppCRUCommonDbOpn error:", err)
return err
}
}
log.Info("Returning from processCommon() - success")
return err
}
func (app *CommonApp) cmnAppCRUCommonDbOpn(d *db.DB, opcode int, dbMap map[string]map[string]db.Value) error {
var err error
var cmnAppTs *db.TableSpec
var xfmrTblLst []string
var resultTblLst []string
for tblNm := range(dbMap) {
xfmrTblLst = append(xfmrTblLst, tblNm)
}
resultTblLst, err = utils.SortAsPerTblDeps(xfmrTblLst)
if err != nil {
return err
}
/* CVL sorted order is in child first, parent later order. CRU ops from parent first order */
for idx := len(resultTblLst)-1; idx >= 0; idx-- {
tblNm := resultTblLst[idx]
log.Info("In Yang to DB map returned from transformer looking for table = ", tblNm)
if tblVal, ok := dbMap[tblNm]; ok {
cmnAppTs = &db.TableSpec{Name: tblNm}
log.Info("Found table entry in yang to DB map")
if ((tblVal == nil) || (len(tblVal) == 0)) {
log.Info("No table instances/rows found.")
continue
}
for tblKey, tblRw := range tblVal {
log.Info("Processing Table key ", tblKey)
// REDIS doesn't allow to create a table instance without any fields
if tblRw.Field == nil {
tblRw.Field = map[string]string{"NULL": "NULL"}
}
if len(tblRw.Field) == 0 {
tblRw.Field["NULL"] = "NULL"
}
if len(tblRw.Field) > 1 {
delete(tblRw.Field, "NULL")
}
existingEntry, _ := d.GetEntry(cmnAppTs, db.Key{Comp: []string{tblKey}})
switch opcode {
case CREATE:
if existingEntry.IsPopulated() {
log.Info("Create case - Entry ", tblKey, " already exists hence modifying it.")
/* Handle leaf-list merge if any leaf-list exists
A leaf-list field in redis has "@" suffix as per swsssdk convention.
*/
resTblRw := db.Value{Field: map[string]string{}}
resTblRw = checkAndProcessLeafList(existingEntry, tblRw, UPDATE, d, tblNm, tblKey)
log.Info("Processing Table row ", resTblRw)
err = d.ModEntry(cmnAppTs, db.Key{Comp: []string{tblKey}}, resTblRw)
if err != nil {
log.Warning("CREATE case - d.ModEntry() failure")
return err
}
} else {
if tblRwDefaults, defaultOk := app.cmnAppYangDefValMap[tblNm][tblKey]; defaultOk {
log.Info("Entry ", tblKey, " doesn't exist so fill defaults - ", tblRwDefaults)
for fld, val := range tblRwDefaults.Field {
tblRw.Field[fld] = val
}
}
log.Info("Processing Table row ", tblRw)
err = d.CreateEntry(cmnAppTs, db.Key{Comp: []string{tblKey}}, tblRw)
if err != nil {
log.Warning("CREATE case - d.CreateEntry() failure")
return err
}
}
case UPDATE:
if existingEntry.IsPopulated() {
log.Info("Entry already exists hence modifying it.")
/* Handle leaf-list merge if any leaf-list exists
A leaf-list field in redis has "@" suffix as per swsssdk convention.
*/
resTblRw := db.Value{Field: map[string]string{}}
resTblRw = checkAndProcessLeafList(existingEntry, tblRw, UPDATE, d, tblNm, tblKey)
err = d.ModEntry(cmnAppTs, db.Key{Comp: []string{tblKey}}, resTblRw)
if err != nil {
log.Warning("UPDATE case - d.ModEntry() failure")
return err
}
} else {
// workaround to patch operation from CLI
log.Info("Create(pathc) an entry.")
if tblRwDefaults, defaultOk := app.cmnAppYangDefValMap[tblNm][tblKey]; defaultOk {
log.Info("Entry ", tblKey, " doesn't exist so fill defaults - ", tblRwDefaults)
for fld, val := range tblRwDefaults.Field {
tblRw.Field[fld] = val
}
}
log.Info("Processing Table row ", tblRw)
err = d.CreateEntry(cmnAppTs, db.Key{Comp: []string{tblKey}}, tblRw)
if err != nil {
log.Warning("UPDATE case - d.CreateEntry() failure")
return err
}
}
case REPLACE:
if tblRwDefaults, defaultOk := app.cmnAppYangDefValMap[tblNm][tblKey]; defaultOk {
log.Info("For entry ", tblKey, ", being replaced, fill defaults - ", tblRwDefaults)
for fld, val := range tblRwDefaults.Field {
tblRw.Field[fld] = val
}
}
log.Info("Processing Table row ", tblRw)
if existingEntry.IsPopulated() {
log.Info("Entry already exists.")
auxRwOk := false
auxRw := db.Value{Field: map[string]string{}}
auxRw, auxRwOk = app.cmnAppYangAuxMap[tblNm][tblKey]
log.Info("Process Aux row ", auxRw)
isTlNd := false
if !strings.HasPrefix(app.pathInfo.Path, "/sonic") {
isTlNd, err = transformer.IsTerminalNode(app.pathInfo.Path)
log.Info("transformer.IsTerminalNode() returned - ", isTlNd, " error ", err)
if err != nil {
return err
}
}
if isTlNd && isPartialReplace(existingEntry, tblRw, auxRw) {
log.Info("Since its partial replace modifying fields - ", tblRw)
err = d.ModEntry(cmnAppTs, db.Key{Comp: []string{tblKey}}, tblRw)
if err != nil {
log.Warning("REPLACE case - d.ModEntry() failure")
return err
}
if auxRwOk {
if len(auxRw.Field) > 0 {
log.Info("Since its partial replace delete aux fields - ", auxRw)
err := d.DeleteEntryFields(cmnAppTs, db.Key{Comp: []string{tblKey}}, auxRw)
if err != nil {
log.Warning("REPLACE case - d.DeleteEntryFields() failure")
return err
}
}
}
} else {
err := d.SetEntry(cmnAppTs, db.Key{Comp: []string{tblKey}}, tblRw)
if err != nil {
log.Warning("REPLACE case - d.SetEntry() failure")
return err
}
}
} else {
log.Info("Entry doesn't exist hence create it.")
err = d.CreateEntry(cmnAppTs, db.Key{Comp: []string{tblKey}}, tblRw)
if err != nil {
log.Warning("REPLACE case - d.CreateEntry() failure")
return err
}
}
}
}
}
}
return err
}
func (app *CommonApp) cmnAppDelDbOpn(d *db.DB, opcode int, dbMap map[string]map[string]db.Value) error {
var err error
var cmnAppTs, dbTblSpec *db.TableSpec
var moduleNm string
var xfmrTblLst []string
var resultTblLst []string
var ordTblList []string
for tblNm := range(dbMap) {
xfmrTblLst = append(xfmrTblLst, tblNm)
}
resultTblLst, err = utils.SortAsPerTblDeps(xfmrTblLst)
if err != nil {
return err
}
/* Retrieve module Name */
moduleNm, err = transformer.GetModuleNmFromPath(app.pathInfo.Path)
if (err != nil) || (len(moduleNm) == 0) {
log.Warning("GetModuleNmFromPath() failed")
return err
}
log.Info("getModuleNmFromPath() returned module name = ", moduleNm)
/* resultTblLst has child first, parent later order */
for _, tblNm := range resultTblLst {
log.Info("In Yang to DB map returned from transformer looking for table = ", tblNm)
if tblVal, ok := dbMap[tblNm]; ok {
cmnAppTs = &db.TableSpec{Name: tblNm}
log.Info("Found table entry in yang to DB map")
if !app.skipOrdTableChk {
ordTblList = transformer.GetXfmrOrdTblList(tblNm)
if len(ordTblList) == 0 {
ordTblList = transformer.GetOrdTblList(tblNm, moduleNm)
}
if len(ordTblList) == 0 {
log.Warning("GetOrdTblList returned empty slice")
err = errors.New("GetOrdTblList returned empty slice. Insufficient information to process request")
return err
}
log.Infof("GetOrdTblList for table - %v, module %v returns %v", tblNm, moduleNm, ordTblList)
}
if len(tblVal) == 0 {
log.Info("DELETE case - No table instances/rows found hence delete entire table = ", tblNm)
if !app.skipOrdTableChk {
for _, ordtbl := range ordTblList {
if ordtbl == tblNm {
// Handle the child tables only till you reach the parent table entry
break
}
log.Info("Since parent table is to be deleted, first deleting child table = ", ordtbl)
dbTblSpec = &db.TableSpec{Name: ordtbl}
err = d.DeleteTable(dbTblSpec)
if err != nil {
log.Warning("DELETE case - d.DeleteTable() failure for Table = ", ordtbl)
return err
}
}
}
err = d.DeleteTable(cmnAppTs)
if err != nil {
log.Warning("DELETE case - d.DeleteTable() failure for Table = ", tblNm)
return err
}
log.Info("DELETE case - Deleted entire table = ", tblNm)
// Continue to repeat ordered deletion for all tables
continue
}
for tblKey, tblRw := range tblVal {
if len(tblRw.Field) == 0 {
log.Info("DELETE case - no fields/cols to delete hence delete the entire row.")
log.Info("First, delete child table instances that correspond to parent table instance to be deleted = ", tblKey)
if !app.skipOrdTableChk {
for _, ordtbl := range ordTblList {
if ordtbl == tblNm {
// Handle the child tables only till you reach the parent table entry
break;
}
dbTblSpec = &db.TableSpec{Name: ordtbl}
keyPattern := tblKey + "|*"
log.Info("Key pattern to be matched for deletion = ", keyPattern)
err = d.DeleteKeys(dbTblSpec, db.Key{Comp: []string{keyPattern}})
if err != nil {
log.Warning("DELETE case - d.DeleteTable() failure for Table = ", ordtbl)
return err
}
log.Info("Deleted keys matching parent table key pattern for child table = ", ordtbl)
}
}
err = d.DeleteEntry(cmnAppTs, db.Key{Comp: []string{tblKey}})
if err != nil {
log.Warning("DELETE case - d.DeleteEntry() failure")
return err
}
log.Info("Finally deleted the parent table row with key = ", tblKey)
} else {
log.Info("DELETE case - fields/cols to delete hence delete only those fields.")
existingEntry, exstErr := d.GetEntry(cmnAppTs, db.Key{Comp: []string{tblKey}})
if exstErr != nil {
log.Info("Table Entry from which the fields are to be deleted does not exist")
err = exstErr
return err
}
/* handle leaf-list merge if any leaf-list exists */
resTblRw := checkAndProcessLeafList(existingEntry, tblRw, DELETE, d, tblNm, tblKey)
log.Info("DELETE case - checkAndProcessLeafList() returned table row ", resTblRw)
if len(resTblRw.Field) > 0 {
if !app.deleteEmptyEntry {
/* add the NULL field if the last field gets deleted && deleteEmpyEntry is false */
deleteCount := 0
for field := range existingEntry.Field {
if resTblRw.Has(field) {
deleteCount++
}
}
if deleteCount == len(existingEntry.Field) {
nullTblRw := db.Value{Field: map[string]string{"NULL": "NULL"}}
log.Info("Last field gets deleted, add NULL field to keep an db entry")
err = d.ModEntry(cmnAppTs, db.Key{Comp: []string{tblKey}}, nullTblRw)
if err != nil {
log.Warning("UPDATE case - d.ModEntry() failure")
return err
}
}
}
/* deleted fields */
err := d.DeleteEntryFields(cmnAppTs, db.Key{Comp: []string{tblKey}}, resTblRw)
if err != nil {
log.Warning("DELETE case - d.DeleteEntryFields() failure")
return err
}
}
}
}
}
} /* end of ordered table list for loop */
return err
}
func (app *CommonApp) generateDbWatchKeys(d *db.DB, isDeleteOp bool) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
return keys, err
}
/*check if any field is leaf-list , if yes perform merge*/
func checkAndProcessLeafList(existingEntry db.Value, tblRw db.Value, opcode int, d *db.DB, tblNm string, tblKey string) db.Value {
dbTblSpec := &db.TableSpec{Name: tblNm}
mergeTblRw := db.Value{Field: map[string]string{}}
for field, value := range tblRw.Field {
if strings.HasSuffix(field, "@") {
exstLst := existingEntry.GetList(field)
log.Infof("Existing DB value for field %v - %v", field, exstLst)
var valueLst []string
if value != "" { //zero len string as leaf-list value is treated as delete entire leaf-list
valueLst = strings.Split(value, ",")
}
log.Infof("Incoming value for field %v - %v", field, valueLst)
if len(exstLst) != 0 {
log.Infof("Existing list is not empty for field %v", field)
for _, item := range valueLst {
if !contains(exstLst, item) {
if opcode == UPDATE {
exstLst = append(exstLst, item)
}
} else {
if opcode == DELETE {
exstLst = utils.RemoveElement(exstLst, item)
}
}
}
log.Infof("For field %v value after merging incoming with existing %v", field, exstLst)
if opcode == DELETE {
if len(valueLst) > 0 {
mergeTblRw.SetList(field, exstLst)
if len(exstLst) == 0 {
tblRw.Field[field] = ""
} else {
delete(tblRw.Field, field)
}
}
} else if opcode == UPDATE {
tblRw.SetList(field, exstLst)
}
} else { //when existing list is empty(either empty string val in field or no field at all n entry)
log.Infof("Existing list is empty for field %v", field)
if opcode == UPDATE {
if len(valueLst) > 0 {
exstLst = valueLst
tblRw.SetList(field, exstLst)
} else {
tblRw.Field[field] = ""
}
} else if opcode == DELETE {
_, fldExistsOk := existingEntry.Field[field]
if (fldExistsOk && (len(valueLst) == 0)) {
tblRw.Field[field] = ""
} else {
delete(tblRw.Field, field)
}
}
}
}
}
/* delete specific item from leaf-list */
if opcode == DELETE {
if len(mergeTblRw.Field) == 0 {
log.Infof("mergeTblRow is empty - Returning Table Row %v", tblRw)
return tblRw
}
err := d.ModEntry(dbTblSpec, db.Key{Comp: []string{tblKey}}, mergeTblRw)
if err != nil {
log.Warning("DELETE case(merge leaf-list) - d.ModEntry() failure")
}
}
log.Infof("Returning Table Row %v", tblRw)
return tblRw
}
// This function is a copy of the function areEqual in ygot.util package.
// areEqual compares a and b. If a and b are both pointers, it compares the
// values they are pointing to.
func areEqual(a, b interface{}) bool {
if util.IsValueNil(a) && util.IsValueNil(b) {
return true
}
va, vb := reflect.ValueOf(a), reflect.ValueOf(b)
if va.Kind() == reflect.Ptr && vb.Kind() == reflect.Ptr {
return reflect.DeepEqual(va.Elem().Interface(), vb.Elem().Interface())
}
return reflect.DeepEqual(a, b)
}
func isPartialReplace(exstRw db.Value, replTblRw db.Value, auxRw db.Value) bool {
/* if existing entry contains field thats not present in result,
default and auxillary map then its a partial replace
*/
partialReplace := false
for exstFld := range exstRw.Field {
if exstFld == "NULL" {
continue
}
isIncomingFld := false
if replTblRw.Has(exstFld) {
continue
}
if auxRw.Has(exstFld) {
continue
}
if !isIncomingFld {
log.Info("Entry contains field ", exstFld, " not found in result, default and aux fields hence its partial replace.")
partialReplace = true
break
}
}
log.Info("returning partialReplace - ", partialReplace)
return partialReplace
}
|
package main
/*
* @lc app=leetcode id=145 lang=golang
*
* [145] Binary Tree Postorder Traversal
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func prepend145(s []int, val int) []int {
copied := append(s, 0)
copy(copied[1:], s)
copied[0] = val
return copied
}
// Solution 2: 二叉树的后序遍历:使用栈的迭代解法, 作弊解法,逆序输出
func postorderTraversal(root *TreeNode) []int {
res := make([]int, 0)
stack := make(Stack145, 0)
if root != nil {
stack.push(root)
}
for !stack.isEmpty() {
node := stack.pop()
res = prepend145(res, node.Val)
if node.Left != nil {
stack.push(node.Left)
}
if node.Right != nil {
stack.push(node.Right)
}
}
return res
}
// Solution 1: 二叉树的后序遍历:递归解法
func postorderTraversal_RECURSIVE_SOLUTION(root *TreeNode) []int {
res := make([]int, 0)
postorder(&res, root)
return res
}
func postorder(res *[]int, root *TreeNode) {
if root == nil {
return
}
postorder(res, root.Left)
postorder(res, root.Right)
*res = append(*res, root.Val)
}
// Stack145 : a simple stack implementation
type Stack145 []*TreeNode
func (s *Stack145) isEmpty() bool { return len(*s) == 0 }
func (s *Stack145) push(t *TreeNode) { *s = append(*s, t) }
func (s *Stack145) pop() *TreeNode {
res := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return res
}
|
// Copyright 2016 Walter Schulze
//
// 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 interp_test
import (
"testing"
"github.com/katydid/katydid/relapse/interp"
"github.com/katydid/katydid/relapse/testsuite"
)
func BenchmarkSuite(b *testing.B) {
if !testsuite.BenchSuiteExists() {
b.Skip("benchsuite not available")
}
benches, err := testsuite.ReadBenchmarkSuite()
if err != nil {
b.Fatal(err)
}
for _, benchCase := range benches {
b.Run(benchCase.Name, func(b *testing.B) {
num := len(benchCase.Parsers)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := benchCase.Parsers[i%num].Reset(); err != nil {
b.Fatal(err)
}
if _, err := interp.Interpret(benchCase.Grammar, benchCase.Parsers[i%num]); err != nil {
b.Fatal(err)
}
}
})
}
}
|
package internal
import (
"errors"
)
var (
ErrUserDoesNotExist = errors.New("user does not exist")
)
|
// Package util contains utilities for use in all transport implementations
package util
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/6/3 10:31 下午
# @File : implement_queue_using_stacks.go
# @Description :
// 栈实现队列
# @Attention :
*/
package v2
// 用栈实现队列
// 关键是: 一个栈专门用于push,剩下的一个栈,专门用于pop
type MyQueue struct {
pushStack []int
popStack []int
}
/** Initialize your data structure here. */
func QueueConstructor() MyQueue {
return MyQueue{}
}
/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int) {
this.pushStack = append(this.pushStack, x)
}
/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
if len(this.popStack) == 0 {
if len(this.pushStack) == 0 {
return 0
}
for len(this.pushStack) > 0 {
p := this.pushStack[len(this.pushStack)-1]
this.pushStack = this.pushStack[:len(this.pushStack)-1]
this.popStack = append(this.popStack, p)
}
}
v := this.popStack[len(this.popStack)-1]
this.popStack = this.popStack[:len(this.popStack)-1]
return v
}
/** Get the front element. */
func (this *MyQueue) Peek() int {
if len(this.popStack) == 0 {
if len(this.pushStack) == 0 {
return 0
}
for len(this.pushStack) > 0 {
p := this.pushStack[len(this.pushStack)-1]
this.pushStack = this.pushStack[:len(this.pushStack)-1]
this.popStack = append(this.popStack, p)
}
}
return this.popStack[len(this.popStack)-1]
}
/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
return len(this.pushStack) == 0 && len(this.popStack) == 0
}
/**
* Your MyQueue object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Peek();
* param_4 := obj.Empty();
*/
|
package manage_model
import (
"ibgame/logs"
"ibgame/models/mysql"
)
const (
superstar = 1 //"当家球星"
allstar = 11 //"全明星"
scorer = 2 //"得分手"
defender = 3 //"防守者"
threer = 4 //"三分手"
maker = 5 //"组织者"
rebound = 6 //"篮板手"
sixer = 7 //"第六人"
threeD = 8 //"3d"
tibu = 9 //"替补"
banch = 10 //"板凳"
)
var typeMap = map[int]string{1: "当家球星", 2: "得分手", 3: "防守者", 4: "三分手", 5: "组织者", 6: "篮板手", 7: "第六人", 8: "3d", 9: "替补", 10: "板凳"}
var posMap = map[int]string{1: "控球后卫", 2: "得分后卫", 3: "小前锋", 4: "大前锋", 5: "中锋"}
var posEMap = map[int]string{1: "Pg", 2: "Sg", 3: "SF", 4: "PF", 5: "C"}
// Add 添加球员
func Add(p AddParam) (ret string, err error) {
var pi PlayerInfo
var pe PlayerExtro
var pw PlayerPower
pi.Name = p.Name
pi.NickName = p.NickName
pi.Position = p.Position
pi.SecondPosition = p.SecondPosition
pi.Type = p.Type
pi.Score = p.Score
pi.Rebound = p.Rebound
pi.Assist = p.Assist
pi.Steal = p.Steal
pi.Cap = p.Cap
pi.AppearNum = p.AppearNum
engine, e := mysql.GetEngine()
if e != nil {
logs.Error.Println("db :err ", e)
return "false", e
}
session := engine.NewSession()
defer session.Close()
// add Begin() before any action
session.Begin()
if _, e1 := session.InsertOne(&pi); e1 != nil {
logs.Error.Println("db :err1 ", e1)
return "false", e1
session.Rollback()
}
pe.PlayerId = pi.PlayerId
pe.DefensiveRebound = p.DefensiveRebound
pe.Faul = p.Faul
pe.InsideAttempt = p.InsideAttempt
pe.InsideMade = p.InsideMade
pe.OffensiveRebound = p.OffensiveRebound
pe.ShotAttempt = p.ShotAttempt
pe.ShotMade = p.ShotMade
pe.ThreeAttempt = p.ThreeAttempt
pe.ThreeMade = p.ThreeMade
pe.TurnOff = p.TurnOff
pw.BasePower = p.BasePower
pw.DefensiveRebound = p.DefensiveReboundPower
pw.InsideAttack = p.InsideAttack
pw.InsideDefense = p.InsideDefense
pw.OffensiveRebound = p.OffensiveReboundPower
pw.OutsideAttack = p.OutsideAttack
pw.OutsideDefense = p.OutsideDefense
pw.Pass = p.Pass
pw.PlayerId = pi.PlayerId
if _, e2 := session.InsertOne(&pe); e2 != nil {
logs.Error.Println("db :err2 ", e2)
return "false", e2
session.Rollback()
}
if _, e3 := session.InsertOne(&pw); e3 != nil {
logs.Error.Println("db :err2 ", e3)
return "false", e3
session.Rollback()
}
if err = session.Commit(); err != nil {
logs.Error.Println("db :err3 ", err)
return "false", err
}
ret = "success"
return
}
//GetPlayer 获取所有球员
func GetPlayer(limit, start int) (ret []PlayerResult, err error) {
pis := make([]PlayerInfo, 0)
pps := make([]PlayerPower, 0)
pes := make([]PlayerExtro, 0)
pids := make([]int64, 0)
pidMap := make(map[int64]PlayerInfo)
powerMap := make(map[int64]PlayerPower)
extroMap := make(map[int64]PlayerExtro)
if engine, e := mysql.GetEngine(); e == nil {
if e1 := engine.Limit(limit, start).Find(&pis); e1 != nil {
err = e1
return
} else {
for _, v := range pis {
pids = append(pids, v.PlayerId)
pidMap[v.PlayerId] = PlayerInfo{PlayerId: v.PlayerId, Name: v.Name, NickName: v.NickName, Position: v.Position, SecondPosition: v.SecondPosition, Type: v.Type, Score: v.Score, Rebound: v.Rebound, Assist: v.Assist, Steal: v.Steal, Cap: v.Cap, AppearNum: v.AppearNum}
}
if e1 := engine.Find(&pps); e1 != nil {
err = e1
return
} else {
for _, pp := range pps {
powerMap[pp.PlayerId] = PlayerPower{BasePower: pp.BasePower, OutsideAttack: pp.OutsideAttack, InsideAttack: pp.InsideAttack, OutsideDefense: pp.OutsideDefense, InsideDefense: pp.InsideDefense, OffensiveRebound: pp.OffensiveRebound, DefensiveRebound: pp.DefensiveRebound, Pass: pp.Pass}
}
}
if e1 := engine.Find(&pes); e1 != nil {
err = e1
return
} else {
for _, pe := range pes {
extroMap[pe.PlayerId] = PlayerExtro{OffensiveRebound: pe.OffensiveRebound, DefensiveRebound: pe.DefensiveRebound, ThreeAttempt: pe.ThreeAttempt, ThreeMade: pe.ThreeMade, InsideAttempt: pe.InsideAttempt, InsideMade: pe.InsideMade, TurnOff: pe.TurnOff, ShotAttempt: pe.ShotAttempt, ShotMade: pe.ShotMade, Faul: pe.Faul}
}
}
}
} else {
logs.Error.Println("db :err ", e)
return
}
for _, v := range pids {
ret = append(ret, PlayerResult{
PlayerId: pidMap[v].PlayerId,
Name: pidMap[v].Name,
NickName: pidMap[v].NickName,
Position: posEMap[pidMap[v].Position],
SecondPosition: posEMap[pidMap[v].SecondPosition],
Type: typeMap[pidMap[v].Type],
Score: pidMap[v].Score,
Rebound: pidMap[v].Rebound,
Assist: pidMap[v].Assist,
Steal: pidMap[v].Steal,
Cap: pidMap[v].Cap,
AppearNum: pidMap[v].AppearNum,
BasePower: powerMap[v].BasePower,
OutsideAttack: powerMap[v].OutsideAttack,
InsideAttack: powerMap[v].InsideAttack,
OutsideDefense: powerMap[v].OutsideDefense,
InsideDefense: powerMap[v].InsideDefense,
DefensiveReboundPower: powerMap[v].DefensiveRebound,
OffensiveReboundPower: powerMap[v].OffensiveRebound,
Pass: powerMap[v].Pass,
OffensiveRebound: extroMap[v].OffensiveRebound,
DefensiveRebound: extroMap[v].DefensiveRebound,
ShotAttempt: extroMap[v].ShotAttempt,
ShotMade: extroMap[v].ShotMade,
ThreeAttempt: extroMap[v].ThreeAttempt,
ThreeMade: extroMap[v].ThreeMade,
InsideAttempt: extroMap[v].InsideAttempt,
InsideMade: extroMap[v].InsideMade,
TurnOff: extroMap[v].TurnOff,
Faul: extroMap[v].Faul,
})
}
return
}
|
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package prealloctableid_test
import (
"fmt"
"testing"
"github.com/pingcap/tidb/br/pkg/metautil"
prealloctableid "github.com/pingcap/tidb/br/pkg/restore/prealloc_table_id"
"github.com/pingcap/tidb/parser/model"
"github.com/stretchr/testify/require"
)
type testAllocator int64
func (t *testAllocator) GetGlobalID() (int64, error) {
return int64(*t), nil
}
func (t *testAllocator) AdvanceGlobalIDs(n int) (int64, error) {
old := int64(*t)
*t = testAllocator(int64(*t) + int64(n))
return old, nil
}
func TestAllocator(t *testing.T) {
type Case struct {
tableIDs []int64
partitions map[int64][]int64
hasAllocatedTo int64
successfullyAllocated []int64
shouldAllocatedTo int64
}
cases := []Case{
{
tableIDs: []int64{1, 2, 5, 6, 7},
hasAllocatedTo: 6,
successfullyAllocated: []int64{6, 7},
shouldAllocatedTo: 8,
},
{
tableIDs: []int64{4, 6, 9, 2},
hasAllocatedTo: 1,
successfullyAllocated: []int64{2, 4, 6, 9},
shouldAllocatedTo: 10,
},
{
tableIDs: []int64{1, 2, 3, 4},
hasAllocatedTo: 5,
successfullyAllocated: []int64{},
shouldAllocatedTo: 5,
},
{
tableIDs: []int64{1, 2, 5, 6, 1 << 50, 1<<50 + 2479},
hasAllocatedTo: 3,
successfullyAllocated: []int64{5, 6},
shouldAllocatedTo: 7,
},
{
tableIDs: []int64{1, 2, 5, 6, 7},
hasAllocatedTo: 6,
successfullyAllocated: []int64{6, 7},
shouldAllocatedTo: 13,
partitions: map[int64][]int64{
7: {8, 9, 10, 11, 12},
},
},
{
tableIDs: []int64{1, 2, 5, 6, 7, 13},
hasAllocatedTo: 9,
successfullyAllocated: []int64{13},
shouldAllocatedTo: 14,
partitions: map[int64][]int64{
7: {8, 9, 10, 11, 12},
},
},
}
run := func(t *testing.T, c Case) {
tables := make([]*metautil.Table, 0, len(c.tableIDs))
for _, id := range c.tableIDs {
table := metautil.Table{
Info: &model.TableInfo{
ID: id,
Partition: &model.PartitionInfo{},
},
}
if c.partitions != nil {
for _, part := range c.partitions[id] {
table.Info.Partition.Definitions = append(table.Info.Partition.Definitions, model.PartitionDefinition{ID: part})
}
}
tables = append(tables, &table)
}
ids := prealloctableid.New(tables)
allocator := testAllocator(c.hasAllocatedTo)
require.NoError(t, ids.Alloc(&allocator))
allocated := make([]int64, 0, len(c.successfullyAllocated))
for _, t := range tables {
if ids.PreallocedFor(t.Info) {
allocated = append(allocated, t.Info.ID)
}
}
require.ElementsMatch(t, allocated, c.successfullyAllocated)
require.Equal(t, int64(allocator), c.shouldAllocatedTo)
}
for i, c := range cases {
t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) {
run(t, c)
})
}
}
|
// Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
"github.com/FScoward/paper-sync/drobox"
"github.com/spf13/cobra"
"net/http"
)
// updateCmd represents the update command
func UpdateCmd() *cobra.Command {
command := &cobra.Command{
Use: "update",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("update called")
filePath, err := cmd.Flags().GetString("file_path")
if err != nil {
cmd.Println("Error", err)
return
}
docId, err := cmd.Flags().GetString("doc_id")
if err != nil || docId == "" {
cmd.Println("Error", err)
return
}
policy, err := cmd.Flags().GetString("doc_update_policy")
if err != nil {
cmd.Println("Error", err)
return
}
revision, err := cmd.Flags().GetInt("revision")
if err != nil {
cmd.Println("Error", err)
return
}
format, err := cmd.Flags().GetString("format")
if err != nil {
cmd.Println("Error", err)
return
}
client := new(http.Client)
_, err = drobox.UpdateDoc(client, filePath, docId, policy, revision, format)
if err != nil {
cmd.Println("Error", err)
}
},
}
command.Flags().StringP("file_path", "", "", "absolute file path")
command.MarkFlagRequired("file_path")
command.Flags().StringP("doc_id", "i", "", "document id")
command.MarkFlagRequired("doc_id")
command.Flags().StringP("doc_update_policy", "p", "", "document update policy")
command.MarkFlagRequired("doc_update_policy")
command.Flags().IntP("revision", "r", 0, "revision")
command.MarkFlagRequired("revision")
command.Flags().StringP("format", "f", "markdown", "format")
return command
}
func init() {
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// updateCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// updateCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
|
package consts
//版本号
const (
VersionV3 = "/v3"
)
//host
const (
DeviceHost = "https://device.jpush.cn"
PushHost = "https://api.jpush.cn"
)
//device
const (
/**
查询设备的别名和标签
-----分割线-----
设置设备的别名与标签:
tags: 支持add, remove 或者空字符串。当tags参数为空字符串的时候,表示清空所有的 tags;
add/remove 下是增加或删除指定的 tag;
一次 add/remove tag 的上限均为 100 个,且总长度均不能超过 1000 字节。
可以多次调用 API 设置,一个注册 id tag 上限为1000个,应用 tag 总数没有限制 。
alias: 更新设备的别名属性;当别名为空串时,删除指定设备的别名;
mobile: 设备关联的手机号码
*/
DevicesURL = DeviceHost + VersionV3 + "/devices/"
AliasURL = DeviceHost + VersionV3 + "/aliases/"
TagsURL = DeviceHost + VersionV3 + "/tags/"
)
/* push url */
const (
PushCidURL = PushHost + VersionV3 + "/push/cid"
PushURL = PushHost + VersionV3 + "/push"
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.