text stringlengths 11 4.05M |
|---|
package auth
import (
"github.com/moisespsena/go-path-helpers"
"github.com/moisespsena/go-i18n-modular/i18nmod"
)
var PREFIX = path_helpers.GetCalledDir()
var I18N_GROUP = i18nmod.PkgToGroup(PREFIX) |
package controllers
import (
"net/http"
"github.com/garyburd/redigo/redis"
kredis "goapi/lib/db/redis"
klog "goapi/lib/log"
)
func Testredis(w http.ResponseWriter, r *http.Request) {
//https://godoc.org/github.com/garyburd/redigo/redis
redis_set()
redis_get()
redis_list_set()
redis_list_get()
redis_hash_set()
redis_hash_get()
redis_key_exists()
redis_set_expire()
w.Write([]byte("goapi Testredis!\n"))
}
func redis_set() {
c := kredis.GetRedis()
defer kredis.CloseRedis(c)
_, err := c.Do("set", "key1", "red")
if err != nil {
klog.Klog.Println(err)
return
}
return
}
func redis_get() {
c := kredis.GetRedis()
defer kredis.CloseRedis(c)
v, err := redis.String(c.Do("get", "key1"))
if err !=nil {
klog.Klog.Println(err)
}
klog.Klog.Println(v)
}
func redis_list_set() {
c := kredis.GetRedis()
defer kredis.CloseRedis(c)
if _, err := c.Do("del", "redlist");err != nil {
klog.Klog.Println(err)
return
}
if _, err := c.Do("lpush", "redlist", "qqq");err != nil {
klog.Klog.Println(err)
return
}
if _, err := c.Do("lpush", "redlist", "www");err != nil {
klog.Klog.Println(err)
return
}
if _, err := c.Do("lpush", "redlist", "eee");err != nil {
klog.Klog.Println(err)
return
}
return
}
func redis_list_get() {
c := kredis.GetRedis()
defer kredis.CloseRedis(c)
values, err := redis.Strings(c.Do("lrange", "redlist","0","100"))
if err !=nil {
klog.Klog.Println(err)
return
}
for _, v := range values {
klog.Klog.Println(v)
}
return
}
func redis_hash_set() {
c := kredis.GetRedis()
defer kredis.CloseRedis(c)
if _, err := c.Do("hset", "hkey1", "field1", "value1");err != nil {
klog.Klog.Println(err)
return
}
if _, err := c.Do("hset", "hkey1", "field2", "value2");err != nil {
klog.Klog.Println(err)
return
}
if _, err := c.Do("hmset", "hkey2", "field1", "value1", "field2", "value2");err != nil {
klog.Klog.Println(err)
return
}
return
}
func redis_hash_get() {
c := kredis.GetRedis()
defer kredis.CloseRedis(c)
v, err := redis.String(c.Do("hget", "hkey1", "field1"))
if err !=nil {
klog.Klog.Println(err)
}
klog.Klog.Println(v)
values, err_ := redis.StringMap(c.Do("hgetall", "hkey1"))
if err_ !=nil {
klog.Klog.Println(err_)
return
}
for k, v := range values {
klog.Klog.Println(k,v)
}
values2, err2_ := redis.StringMap(c.Do("hgetall", "hkey2"))
if err2_ !=nil {
klog.Klog.Println(err2_)
return
}
for k, v := range values2 {
klog.Klog.Println(k,v)
}
return
}
func redis_key_exists() {
c := kredis.GetRedis()
defer kredis.CloseRedis(c)
is, err := redis.Bool(c.Do("EXISTS", "xxxxxxx"))
if err !=nil {
klog.Klog.Println(err)
return
}
klog.Klog.Println(is)
return
}
func redis_set_expire() {
c := kredis.GetRedis()
defer kredis.CloseRedis(c)
if _, err := c.Do("EXPIRE", "hkey1", 24*3600);err != nil {
klog.Klog.Println(err)
return
}
return
} |
package web
import (
"context"
"fmt"
pb "github.com/autograde/aguis/ag"
)
// rebuildSubmission rebuilds the given lab assignment and submission.
func (s *AutograderService) rebuildSubmission(ctx context.Context, request *pb.LabRequest) error {
lab, err := s.db.GetAssignment(&pb.Assignment{ID: request.GetAssignmentID()})
if err != nil {
return err
}
course, err := s.db.GetCourse(lab.GetCourseID(), false)
if err != nil {
return err
}
submission, err := s.db.GetSubmission(&pb.Submission{
ID: request.GetSubmissionID(),
AssignmentID: request.GetAssignmentID(),
})
if err != nil {
return err
}
repoQuery := &pb.Repository{
OrganizationID: course.GetOrganizationID(),
UserID: submission.GetUserID(), // defaults to 0 if not set
RepoType: pb.Repository_USER,
}
if lab.IsGroupLab {
repoQuery.GroupID = submission.GetGroupID()
repoQuery.RepoType = pb.Repository_GROUP
}
repos, err := s.db.GetRepositories(repoQuery)
if err != nil {
return err
}
// TODO(vera): debugging, to be removed
s.logger.Debugf("Starting rebuild for user %d or group %d, lab %+v", submission.GetUserID(), submission.GetGroupID(), lab)
// it is possible to have duplicate records for the same user repo because there were no database constraints
// it is fixed for new records, but can be relevant for older database records
// that's why we allow len(repos) be > 1 and just use the first found record
if len(repos) < 1 {
return fmt.Errorf("failed to get user repository for the submission")
}
repo := repos[0]
s.logger.Info("Rebuilding user submission: repo url is: ", repo.GetHTMLURL())
nameTag := s.makeContainerTag(submission)
runTests(s.logger, s.db, s.runner, repo, repo.GetHTMLURL(), submission.GetCommitHash(), "ci/scripts", lab.GetID(), nameTag)
return nil
}
func (s *AutograderService) makeContainerTag(submission *pb.Submission) string {
if submission.GetGroupID() > 0 {
group, _ := s.db.GetGroup(submission.GetGroupID())
return group.GetName()
}
user, _ := s.db.GetUser(submission.GetUserID())
return user.GetLogin()
}
|
package dag
import "github.com/Qitmeer/qitmeer-lib/common/hash"
// HashList is used to sort hash list
type HashList []*hash.Hash
func (sh HashList) Len() int {
return len(sh)
}
func (sh HashList) Less(i, j int) bool {
return sh[i].String() < sh[j].String()
}
func (sh HashList) Swap(i, j int) {
sh[i], sh[j] = sh[j], sh[i]
}
func (sh HashList) Has(h *hash.Hash) bool {
for _,v:=range sh{
if v.IsEqual(h) {
return true
}
}
return false
} |
// Source : https://oj.leetcode.com/problems/zigzag-conversion/
// Author : Austin Vern Songer
// Date : 2016-03-07
/**********************************************************************************
*
* The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
* (you may want to display this pattern in a fixed font for better legibility)
*
* P A H N
* A P L S I I G
* Y I R
*
* And then read line by line: "PAHNAPLSIIGYIR"
*
* Write the code that will take a string and make this conversion given a number of rows:
*
* string convert(string text, int nRows);
*
* convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
*
*
**********************************************************************************/
package main
import (
"fmt"
"strings"
)
var x int = 0
var step int = 0
var inputArr []string
func zigzag(inputStr string, nRows int) string {
if len(inputStr) < nRows || nRows <= 0 {
return "you maybe not understand rule !!"
}
inputArr = strings.Split(inputStr, "")
tmpArr := make([]string, nRows)
for i := 0; i < len(inputArr); i++ {
if x == nRows-1 {
step = -1
}
if x == 0 {
step = 1
}
fmt.Println("row number is : ", x)
tmpArr[x] = tmpArr[x] + inputArr[i]
x += step
fmt.Println(tmpArr)
}
return ""
}
func main() {
zigzag("helloworld", 4)
}
|
package modals
import (
"net/http"
"encoding/json"
"strconv"
"github.com/gorilla/mux"
)
// Types
// Players
type Player struct {
ID int `json:"id"`
Name string `json:"name"`
Picture string `json:"picture"`
Role string `json:position`
Bio string `json:"bio"`
Info []Info `json:"info,omitempty"`
Sponsors []Sponsor `json:"sponsors,omitempty"`
Images []Image `json:"images,omitempty"`
}
type Info struct {
Label string `json:"label,omitempty"`
Value string `json:"value,omitempty"`
}
var squad []Player
// Functions
func GetSquad(w http.ResponseWriter, r *http.Request) {
// Get the team if it exists (params["team"])
// params := mux.Vars(r)
// Get the squad
json.NewEncoder(w).Encode(squad)
}
func GetPlayer(w http.ResponseWriter, r *http.Request) {
// Get the player ID (params["id"])
params := mux.Vars(r)
id, _ := strconv.ParseInt(params["id"], 10, 0)
// Search for the relevent player
for _, player := range squad {
if player.ID == int(id) {
json.NewEncoder(w).Encode(player)
}
}
} |
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Luzifer/rconfig"
"github.com/bogem/id3v2"
log "github.com/sirupsen/logrus"
)
var (
cfg struct {
LogLevel string `flag:"log-level" default:"info" description:"Set log level (debug, info, warning, error)"`
Output string `flag:"output,o" default:"-" description:"Output to write to (Filename or '-' for StdOut)"`
VersionAndExit bool `flag:"version" default:"false" description:"Print version information and exit"`
}
product = "id3index"
version = "dev"
output io.Writer
)
func init() {
if err := rconfig.ParseAndValidate(&cfg); err != nil {
log.Fatalf("Error parsing CLI arguments: %s", err)
}
if l, err := log.ParseLevel(cfg.LogLevel); err == nil {
log.SetLevel(l)
} else {
log.Fatalf("Invalid log level: %s", err)
}
if cfg.VersionAndExit {
fmt.Printf("%s %s\n", product, version)
os.Exit(0)
}
}
func main() {
directory := "."
if len(rconfig.Args()) > 1 {
directory = rconfig.Args()[1]
}
output = os.Stdout
if cfg.Output != "-" {
f, err := os.Create(cfg.Output)
if err != nil {
log.Fatalf("Could not open output file %q: %s", cfg.Output, err)
}
defer f.Close()
output = f
}
log.Infof("Starting file scan of directory %q", directory)
fmt.Fprintln(output, "File path,Artist,Title,Album,Error")
if err := filepath.Walk(directory, walk); err != nil {
log.Fatalf("Experienced error while scanning directory: %s", err)
}
log.Infof("File scan finished.")
}
func walk(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !strings.HasSuffix(path, ".mp3") {
return nil
}
var errorMsg string
mp3File, err := id3v2.Open(path, id3v2.Options{Parse: true})
switch {
case err == nil:
case strings.HasPrefix(err.Error(), ""):
errorMsg = err.Error()
default:
return err
}
defer mp3File.Close()
fmt.Fprintf(output, "\"%s\"\n", strings.Join([]string{
path,
mp3File.Artist(),
mp3File.Title(),
mp3File.Album(),
errorMsg,
}, "\",\""))
return nil
}
|
package main
import (
"io"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/openshift/installer/pkg/version"
)
type fileHook struct {
file io.Writer
formatter logrus.Formatter
level logrus.Level
truncateAtNewLine bool
}
func newFileHook(file io.Writer, level logrus.Level, formatter logrus.Formatter) *fileHook {
return &fileHook{
file: file,
formatter: formatter,
level: level,
}
}
func newFileHookWithNewlineTruncate(file io.Writer, level logrus.Level, formatter logrus.Formatter) *fileHook {
f := newFileHook(file, level, formatter)
f.truncateAtNewLine = true
return f
}
func (h fileHook) Levels() []logrus.Level {
var levels []logrus.Level
for _, level := range logrus.AllLevels {
if level <= h.level {
levels = append(levels, level)
}
}
return levels
}
func (h *fileHook) Fire(entry *logrus.Entry) error {
// logrus reuses the same entry for each invocation of hooks.
// so we need to make sure we leave them message field as we received.
orig := entry.Message
defer func() { entry.Message = orig }()
msgs := []string{orig}
if h.truncateAtNewLine {
msgs = strings.Split(orig, "\n")
}
for _, msg := range msgs {
// this makes it easier to call format on entry
// easy without creating a new one for each split message.
entry.Message = msg
line, err := h.formatter.Format(entry)
if err != nil {
return err
}
if _, err := h.file.Write(line); err != nil {
return err
}
}
return nil
}
func setupFileHook(baseDir string) func() {
if err := os.MkdirAll(baseDir, 0755); err != nil {
logrus.Fatal(errors.Wrap(err, "failed to create base directory for logs"))
}
logfile, err := os.OpenFile(filepath.Join(baseDir, ".openshift_install.log"), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
logrus.Fatal(errors.Wrap(err, "failed to open log file"))
}
originalHooks := logrus.LevelHooks{}
for k, v := range logrus.StandardLogger().Hooks {
originalHooks[k] = v
}
logrus.AddHook(newFileHook(logfile, logrus.TraceLevel, &logrus.TextFormatter{
DisableColors: true,
DisableTimestamp: false,
FullTimestamp: true,
DisableLevelTruncation: false,
}))
versionString, err := version.String()
if err != nil {
logrus.Fatal(err)
}
logrus.Debugf(versionString)
if version.Commit != "" {
logrus.Debugf("Built from commit %s", version.Commit)
}
return func() {
logfile.Close()
logrus.StandardLogger().ReplaceHooks(originalHooks)
}
}
|
package cfmysql_test
import (
"code.cloudfoundry.org/cli/cf/errors"
"code.cloudfoundry.org/cli/plugin"
"code.cloudfoundry.org/cli/plugin/models"
"code.cloudfoundry.org/cli/plugin/pluginfakes"
. "github.com/andreasf/cf-mysql-plugin/cfmysql"
"github.com/andreasf/cf-mysql-plugin/cfmysql/cfmysqlfakes"
"github.com/andreasf/cf-mysql-plugin/cfmysql/models"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"time"
)
var _ = Describe("CfService", func() {
var apiClient *cfmysqlfakes.FakeApiClient
var service CfService
var cliConnection *pluginfakes.FakeCliConnection
var sshRunner *cfmysqlfakes.FakeSshRunner
var portWaiter *cfmysqlfakes.FakePortWaiter
var mockHttp *cfmysqlfakes.FakeHttpWrapper
var mockRand *cfmysqlfakes.FakeRandWrapper
var appList []plugin_models.GetAppsModel
var serviceKey models.ServiceKey
var expectedMysqlService MysqlService
var logWriter *gbytes.Buffer
BeforeEach(func() {
cliConnection = new(pluginfakes.FakeCliConnection)
cliConnection.GetCurrentSpaceReturns(plugin_models.Space{
SpaceFields: plugin_models.SpaceFields{
Guid: "space-guid-a",
Name: "space is the place",
},
}, nil)
apiClient = new(cfmysqlfakes.FakeApiClient)
sshRunner = new(cfmysqlfakes.FakeSshRunner)
portWaiter = new(cfmysqlfakes.FakePortWaiter)
mockHttp = new(cfmysqlfakes.FakeHttpWrapper)
mockRand = new(cfmysqlfakes.FakeRandWrapper)
logWriter = gbytes.NewBuffer()
service = NewCfService(apiClient, sshRunner, portWaiter, mockHttp, mockRand, logWriter)
appList = []plugin_models.GetAppsModel{
{
Name: "app-name-1",
},
{
Name: "app-name-2",
},
}
serviceKey = models.ServiceKey{
ServiceInstanceGuid: "service-instance-guid",
Uri: "uri",
DbName: "db-name",
Hostname: "hostname",
Port: "2342",
Username: "username",
Password: "password",
CaCert: "ca-cert",
}
expectedMysqlService = MysqlService{
Name: "service-instance-name",
Hostname: "hostname",
Port: "2342",
DbName: "db-name",
Username: "username",
Password: "password",
CaCert: "ca-cert",
}
})
Context("GetStartedApps", func() {
It("delegates the call to ApiClient", func() {
expectedApps := []plugin_models.GetAppsModel{
{
Name: "foo",
},
{
Name: "bar",
},
}
expectedErr := errors.New("baz")
apiClient.GetStartedAppsReturns(expectedApps, expectedErr)
startedApps, err := service.GetStartedApps(cliConnection)
Expect(startedApps).To(Equal(expectedApps))
Expect(err).To(Equal(expectedErr))
Expect(apiClient.GetStartedAppsCallCount()).To(Equal(1))
Expect(apiClient.GetStartedAppsArgsForCall(0)).To(Equal(cliConnection))
})
})
Context("OpenSshTunnel", func() {
mysqlService := MysqlService{
Name: "database-a",
Hostname: "database-a.host",
Port: "3306",
DbName: "dbname-a",
Username: "username-a",
Password: "password-a",
}
openSshTunnelCalled := make(chan bool, 0)
Context("When opening the tunnel", func() {
notifyWhenGoroutineCalled := func(cliConnection plugin.CliConnection, toService MysqlService, throughApp string, localPort int) {
openSshTunnelCalled <- true
}
It("Runs the SSH runner in a goroutine", func() {
cliConnection := new(pluginfakes.FakeCliConnection)
sshRunner := new(cfmysqlfakes.FakeSshRunner)
portWaiter := new(cfmysqlfakes.FakePortWaiter)
mockRand := new(cfmysqlfakes.FakeRandWrapper)
logWriter := gbytes.NewBuffer()
mockRand.IntnReturns(1)
service := NewCfService(apiClient, sshRunner, portWaiter, mockHttp, mockRand, logWriter)
sshRunner.OpenSshTunnelStub = notifyWhenGoroutineCalled
service.OpenSshTunnel(cliConnection, mysqlService, appList, 4242)
select {
case <-openSshTunnelCalled:
break
case <-time.After(1 * time.Second):
Fail("timed out waiting for OpenSSH tunnel to be called")
}
Expect(sshRunner.OpenSshTunnelCallCount()).To(Equal(1))
calledCliConnection, calledService, calledAppName, calledPort := sshRunner.OpenSshTunnelArgsForCall(0)
Expect(mockRand.IntnCallCount()).To(Equal(1))
Expect(mockRand.IntnArgsForCall(0)).To(Equal(2))
Expect(calledCliConnection).To(Equal(cliConnection))
Expect(calledService).To(Equal(mysqlService))
Expect(calledAppName).To(Equal("app-name-2"))
Expect(calledPort).To(Equal(4242))
})
It("Blocks until the tunnel is open", func() {
cliConnection.CliCommandWithoutTerminalOutputStub = nil
service.OpenSshTunnel(cliConnection, mysqlService, appList, 4242)
Expect(portWaiter.WaitUntilOpenCallCount()).To(Equal(1))
Expect(portWaiter.WaitUntilOpenArgsForCall(0)).To(Equal(4242))
})
})
})
Context("GetService", func() {
var instance models.ServiceInstance
BeforeEach(func() {
instance = models.ServiceInstance{
Name: "service-instance-name",
Guid: "service-instance-guid",
SpaceGuid: "space-guid",
}
})
Context("When the service instance is not found", func() {
It("Returns an error", func() {
apiClient.GetServiceReturns(models.ServiceInstance{}, errors.New("PC LOAD LETTER"))
mysqlService, err := service.GetService(cliConnection, "service-name")
Expect(mysqlService).To(Equal(MysqlService{}))
Expect(err).To(Equal(errors.New("unable to retrieve metadata for service service-name: PC LOAD LETTER")))
Expect(cliConnection.GetCurrentSpaceCallCount()).To(Equal(1))
calledConnection, calledSpaceGuid, calledName := apiClient.GetServiceArgsForCall(0)
Expect(calledConnection).To(Equal(cliConnection))
Expect(calledSpaceGuid).To(Equal("space-guid-a"))
Expect(calledName).To(Equal("service-name"))
})
})
Context("When service and key are found", func() {
It("Returns credentials", func() {
apiClient.GetServiceReturns(instance, nil)
apiClient.GetServiceKeyReturns(serviceKey, true, nil)
mysqlService, err := service.GetService(cliConnection, "service-instance-name")
Expect(err).To(BeNil())
Expect(mysqlService).To(Equal(expectedMysqlService))
calledConnection, calledSpaceGuid, calledName := apiClient.GetServiceArgsForCall(0)
Expect(calledConnection).To(Equal(cliConnection))
Expect(calledSpaceGuid).To(Equal("space-guid-a"))
Expect(calledName).To(Equal("service-instance-name"))
calledConnection, calledInstanceGuid, calledKeyName := apiClient.GetServiceKeyArgsForCall(0)
Expect(calledConnection).To(Equal(cliConnection))
Expect(calledInstanceGuid).To(Equal(instance.Guid))
Expect(calledKeyName).To(Equal("cf-mysql"))
})
})
Context("When the service key does not yet exist", func() {
It("Creates the key and returns credentials", func() {
apiClient.GetServiceReturns(instance, nil)
apiClient.GetServiceKeyReturns(models.ServiceKey{}, false, nil)
apiClient.CreateServiceKeyReturns(serviceKey, nil)
mysqlService, err := service.GetService(cliConnection, "service-instance-name")
Expect(err).To(BeNil())
Expect(mysqlService).To(Equal(expectedMysqlService))
calledConnection, calledSpaceGuid, calledName := apiClient.GetServiceArgsForCall(0)
Expect(calledConnection).To(Equal(cliConnection))
Expect(calledSpaceGuid).To(Equal("space-guid-a"))
Expect(calledName).To(Equal("service-instance-name"))
calledConnection, calledInstanceGuid, calledKeyName := apiClient.CreateServiceKeyArgsForCall(0)
Expect(calledConnection).To(Equal(cliConnection))
Expect(calledInstanceGuid).To(Equal(instance.Guid))
Expect(calledKeyName).To(Equal("cf-mysql"))
Expect(logWriter).To(gbytes.Say("Creating new service key cf-mysql for service-instance-name...\n"))
})
})
Context("When the key cannot be created", func() {
It("Returns an error", func() {
apiClient.GetServiceReturns(instance, nil)
apiClient.GetServiceKeyReturns(models.ServiceKey{}, false, nil)
apiClient.CreateServiceKeyReturns(models.ServiceKey{}, errors.New("PC LOAD LETTER"))
mysqlService, err := service.GetService(cliConnection, "service-instance-name")
Expect(err).To(Equal(errors.New("unable to create service key: PC LOAD LETTER")))
Expect(mysqlService).To(Equal(MysqlService{}))
calledConnection, calledSpaceGuid, calledName := apiClient.GetServiceArgsForCall(0)
Expect(calledConnection).To(Equal(cliConnection))
Expect(calledSpaceGuid).To(Equal("space-guid-a"))
Expect(calledName).To(Equal("service-instance-name"))
calledConnection, calledInstanceGuid, calledKeyName := apiClient.CreateServiceKeyArgsForCall(0)
Expect(calledConnection).To(Equal(cliConnection))
Expect(calledInstanceGuid).To(Equal(instance.Guid))
Expect(calledKeyName).To(Equal("cf-mysql"))
})
})
Context("When the key cannot be retrieved", func() {
It("Returns an error", func() {
apiClient.GetServiceReturns(instance, nil)
apiClient.GetServiceKeyReturns(models.ServiceKey{}, false, errors.New("PC LOAD LETTER"))
mysqlService, err := service.GetService(cliConnection, "service-instance-name")
Expect(err).To(Equal(errors.New("unable to retrieve service key: PC LOAD LETTER")))
Expect(mysqlService).To(Equal(MysqlService{}))
calledConnection, calledSpaceGuid, calledName := apiClient.GetServiceArgsForCall(0)
Expect(calledConnection).To(Equal(cliConnection))
Expect(calledSpaceGuid).To(Equal("space-guid-a"))
Expect(calledName).To(Equal("service-instance-name"))
})
})
Context("When the current space cannot be retrieved", func() {
It("Returns an error", func() {
cliConnection.GetCurrentSpaceReturns(plugin_models.Space{}, errors.New("PC LOAD LETTER"))
mysqlService, err := service.GetService(cliConnection, "service-instance-name")
Expect(err).To(Equal(errors.New("unable to retrieve current space: PC LOAD LETTER")))
Expect(mysqlService).To(Equal(MysqlService{}))
Expect(cliConnection.GetCurrentSpaceCallCount()).To(Equal(1))
})
})
})
})
|
package main
import "fmt"
// Anonymous function - is a type of function without any specific name to it
var (
area = func(l, b int) int {
return l * b
}
)
// User defined function
type Susheel func(int) int
func sum(x, y int) int {
return x + y
}
// Higher order function
// Function as an argument and return function
func partialfunc(x int) func(y int) int {
return func(y int) int {
return sum(x, y)
}
}
// return function from function
func multipleFuncs(x int) func(y int) func(z int) int {
return func(y int) func(z int) int {
return func(z int) int {
return x + y + z
}
}
}
// Call by value
func valuetype(a, b int) (int, int) {
return b, a
}
// Call be reference
func reftype(a, b *int) {
*b, *a = *a, *b
}
func main() {
a, b := 50, 100
valuetype(a, b)
fmt.Println(a, b)
reftype(&a, &b)
fmt.Println(a, b)
// Passing arguments to an anonymous function
answer := func(l, b int) int {
return l * b
}(a, b)
fmt.Println(answer)
//Closure Function in Golang
// These are a special case of anonymous function that accesses variables
// defined outside the body of the function
var add int
for i := 0; i < 10; i++ {
func() {
add += i
}()
}
fmt.Printf("\n Addition: %d\n", add)
// Higher order functions
// An higher order function is a function that operate on the
// other functions and taking them as arguments or by returning them
funVar := partialfunc(10)
fmt.Println("Sum of Two numbers:: ", funVar(5))
// Returning multiple functions from other functions
//Skip
fmt.Println(multipleFuncs(10)(20)(30))
// User defined functions
x := 100
answer1 := func(int) Susheel {
return func(y int) int {
return x + b + y
}
}(x)
fmt.Println("Answer:: ", answer1(1))
}
|
package file
import (
"bufio"
"log"
"os"
"strconv"
"strings"
"errors"
"github.com/ryanchew3/flexera-coding-challenge/internal/model"
)
// ReadFile reads in the input file and groups user machines by userids
func ReadFile(s string) (map[int64][]*model.Computer, error) {
out := make(map[int64][]*model.Computer)
file, err := os.Open(s)
if err != nil {
log.Print("failed to open file")
return nil, errors.New("failed to open file")
}
scanner := bufio.NewScanner(file)
scanner.Scan()
for scanner.Scan() {
var text = scanner.Text()
var tokens = strings.Split(text, ",")
key, e := strconv.ParseInt(tokens[1], 10, 64)
if e != nil {
return nil, e
}
id, e := strconv.ParseInt(tokens[0], 10, 64)
if e != nil {
return nil, e
}
appId, e := strconv.ParseInt(tokens[2], 10, 64)
if e != nil {
return nil, e
}
val := &model.Computer{
Id: id,
AppId: appId,
Type: tokens[3],
}
_, ok := out[key]
if !ok {
out[key] = []*model.Computer{val}
} else {
out[key] = append(out[key], val)
}
}
return out, nil
}
|
package main
import (
"context"
"fmt"
"time"
)
type otherContext struct {
context.Context
}
func work(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Printf("%s get msg to cancel\n", name)
return
default:
fmt.Printf("%s is running \n", name)
time.Sleep(1 * time.Second)
}
}
}
func workWithValue(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Printf("%s get msg to cancel\n", name)
return
default:
value := ctx.Value("key").(string)
fmt.Printf("%s is running value=%s \n", name, value)
time.Sleep(1 * time.Second)
}
}
}
func main() {
// 使用context.Background()构建一个WithCancel类型的上下文
ctxa, cancel := context.WithCancel(context.Background())
go work(ctxa, "work a")
// 使用WithDeadline包装前面的上下文,具有超时通知
tm := time.Now().Add(3 * time.Second)
ctxb, _ := context.WithDeadline(ctxa, tm)
go work(ctxb, "work b")
// 使用WithValue包装前面的上下文,能够传递数据
oc := otherContext{ctxb}
ctxc := context.WithValue(oc, "key", "andes, pass from main")
go workWithValue(ctxc, "work c")
time.Sleep(10 * time.Second)
cancel()
time.Sleep(5 * time.Second)
fmt.Println("main stop")
}
|
package main
import (
"fmt"
"sync"
"time"
)
var mutex sync.Mutex
func main() {
map1 :=make(map[int] string)
for i:=1;i<=10;i++{
go func(i int) {
mutex.Lock()
map1[i] =fmt.Sprint("数据",i)
mutex.Unlock()
}(i)
}
time.Sleep(2*time.Second)
fmt.Println(map1)
}
|
package decrypt
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"fmt"
"math/big"
"github.com/allvisss/ECC_service/common/model"
"github.com/allvisss/ECC_service/common/response"
"github.com/fomichev/secp256k1"
)
func DecryptService(ciphertext string, priv model.PrivateKey) (int, interface{}) {
plaintext, err := Decrypt(&priv, []byte(ciphertext))
if err != nil {
return response.ServiceUnavailableMsg("Can not decrypt")
}
return response.NewOKResponse(plaintext)
}
// Decrypt decrypts a passed message with a receiver private key, returns plaintext or decryption error
func Decrypt(privkey *model.PrivateKey, msg []byte) ([]byte, error) {
// Message cannot be less than length of public key (65) + nonce (16) + tag (16)
if len(msg) <= (1 + 32 + 32 + 16 + 16) {
return nil, fmt.Errorf("invalid length of message")
}
// Ephemeral sender public key
ethPubkey := &model.PublicKey{
Curve: secp256k1.SECP256K1(),
X: new(big.Int).SetBytes(msg[1:33]),
Y: new(big.Int).SetBytes(msg[33:65]),
}
// Shift message
msg = msg[65:]
// Derive shared secret
ss, err := ethPubkey.Decapsulate(privkey)
if err != nil {
return nil, err
}
// AES decryption part
//nonce := msg[:16]
tag := msg[16:32]
// Create Golang-accepted ciphertext
ciphertext := bytes.Join([][]byte{msg[32:], tag}, nil)
block, err := aes.NewCipher(ss)
if err != nil {
return nil, fmt.Errorf("cannot create new aes block: %w", err)
}
gcm, err := cipher.NewGCMWithNonceSize(block, 16)
if err != nil {
return nil, fmt.Errorf("cannot create gcm cipher: %w", err)
}
plaintext, err := gcm.Open(nil, nil, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("cannot decrypt ciphertext: %w", err)
}
return plaintext, nil
}
|
package clouddatastore
import (
"context"
"fmt"
"github.com/qnib/metahub/pkg/storage"
"cloud.google.com/go/datastore"
)
// NewService returns a new storage.Service for GCP Cloud Datastore
func NewService() storage.Service {
return &service{}
}
type service struct {
}
func (s *service) newClient(ctx context.Context) (*datastore.Client, error) {
return datastore.NewClient(ctx, "")
}
func (s *service) MachineTypeService(ctx context.Context) (storage.MachineTypeService, error) {
datastoreClient, err := s.newClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to create client: %v", err)
}
return &machineTypeService{
ctx: ctx,
client: datastoreClient,
}, nil
}
func (s *service) AccessTokenService(ctx context.Context) (storage.AccessTokenService, error) {
datastoreClient, err := s.newClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to create client: %v", err)
}
return &accessTokenService{
ctx: ctx,
client: datastoreClient,
}, nil
}
func (s *service) AccountService(ctx context.Context) (storage.AccountService, error) {
datastoreClient, err := s.newClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to create client: %v", err)
}
return &accountService{
ctx: ctx,
client: datastoreClient,
}, nil
}
|
package eventmanager
import (
"context"
cluster "github.com/bsm/sarama-cluster"
"github.com/lovoo/goka"
"github.com/lovoo/goka/kafka"
"log"
"microservices_template_golang/payment_storage/src/models"
"os"
"os/signal"
"syscall"
)
type EventProcessor struct {
processor *goka.Processor
}
func (e *EventProcessor) InitSimpleProcessor(brokers []string, group goka.Group, groupCallback func(ctx goka.Context, msg interface{}),
topic goka.Stream, pc, cc *cluster.Config) {
p, err := goka.NewProcessor(brokers,
goka.DefineGroup(group,
goka.Input(topic, new(models.ProcessedPaymentCodec), groupCallback),
),
goka.WithProducerBuilder(kafka.ProducerBuilderWithConfig(pc)), // our config, mostly default
goka.WithConsumerBuilder(kafka.ConsumerBuilderWithConfig(cc)), // our config, mostly default
)
if err != nil {
log.Fatalf("error creating processor: %v", err)
}
e.processor = p
}
func (e *EventProcessor) InitDefaultProcessor(brokers []string, group goka.Group, topic goka.Stream, cb func(ctx goka.Context, msg interface{})){
pc := NewConfig()
cc := NewConfig()
e.InitSimpleProcessor(brokers, group, cb, topic, pc, cc)
}
func (e *EventProcessor) Run(){
ctx, cancel := context.WithCancel(context.Background())
done := make(chan bool)
go func() {
defer close(done)
if err := e.processor.Run(ctx); err != nil {
log.Fatalf("error running processor: %v", err)
}
}()
wait := make(chan os.Signal, 1)
signal.Notify(wait, syscall.SIGINT, syscall.SIGTERM)
<-wait // wait for SIGINT/SIGTERM
cancel() // gracefully stop processor
<-done
}
|
package manager
/*
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang/glog"
// "sub_account_service/finance/config"
// "sub_account_service/finance/db"
"sub_account_service/finance/lib"
_ "sub_account_service/finance/memory" //引用memory包初始化函数
// "sub_account_service/finance/models"
// "sub_account_service/finance/protocol"
// "sub_account_service/finance/session"
third "sub_account_service/finance/third_part_pay"
// "sub_account_service/finance/utils"
)
func RefundTrade(ctx *gin.Context) {
tradeNo := ctx.Query("trade_no")
if tradeNo == "" {
ctx.JSON(http.StatusOK, lib.Result.Fail(-1, "trade number is empty"))
}
if err := third.CustomerRefundTrade(tradeNo); err != nil {
glog.Errorln("customer refund trade error", err)
ctx.JSON(http.StatusOK, lib.Result.Fail(-1, fmt.Sprintf("customer refund trade error: %v", err)))
}
ctx.JSON(http.StatusOK, lib.Result.Success("success", nil))
}
*/
|
package combinators
import (
"log"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
func TestExpectRune(t *testing.T) {
var r interface{}
var err error
parser := Expect('a')
r, _ = ParseRuneReader(parser, strings.NewReader("a"))
assert.Equal(t, "a", r)
r, _ = ParseRuneReader(parser, strings.NewReader("aaa"))
assert.Equal(t, "a", r)
_, err = ParseRuneReader(parser, strings.NewReader(""))
assert.EqualError(t, err, `Stream ended, expected "a"`)
_, err = ParseRuneReader(parser, strings.NewReader("b"))
assert.EqualError(t, err, `Expected "a"`)
_, err = ParseRuneReader(parser, strings.NewReader("bbb"))
assert.EqualError(t, err, `Expected "a"`)
}
func TestExpectAny(t *testing.T) {
var r interface{}
var err error
parser := ExpectAny([]rune("abc"))
r, _ = ParseRuneReader(parser, strings.NewReader("a"))
assert.Equal(t, "a", r)
r, _ = ParseRuneReader(parser, strings.NewReader("b"))
assert.Equal(t, "b", r)
r, _ = ParseRuneReader(parser, strings.NewReader("c"))
assert.Equal(t, "c", r)
_, err = ParseRuneReader(parser, strings.NewReader(""))
assert.EqualError(t, err, `Stream ended, expected one of a, b, c`)
_, err = ParseRuneReader(parser, strings.NewReader("d"))
assert.EqualError(t, err, `Expected one of a, b, c`)
}
func TestSeq(t *testing.T) {
parser1 := SeqOf(Expect('a'), Expect('a'))
{
r, _ := ParseRuneReader(parser1, strings.NewReader("aa"))
assert.EqualValues(t, []interface{}{"a", "a"}, r)
}
{
r, _ := ParseRuneReader(parser1, strings.NewReader("aaa"))
assert.EqualValues(t, []interface{}{"a", "a"}, r)
}
{
_, err := ParseRuneReader(parser1, strings.NewReader("a"))
assert.EqualError(t, err, `Stream ended, expected "a"`)
}
{
_, err := ParseRuneReader(parser1, strings.NewReader("ababab"))
assert.EqualError(t, err, `Expected "a"`)
}
}
func TestAny(t *testing.T) {
parser1 := AnyOf(Expect('a'), Expect('b'))
{
r, _ := ParseRuneReader(parser1, strings.NewReader("aa"))
assert.Equal(t, "a", r)
}
{
r, _ := ParseRuneReader(parser1, strings.NewReader("bb"))
assert.Equal(t, "b", r)
}
{
_, err := ParseRuneReader(parser1, strings.NewReader(""))
assert.EqualError(t, err, "All cases failed:\n - Stream ended, expected \"a\"\n - Stream ended, expected \"b\"")
}
{
_, err := ParseRuneReader(parser1, strings.NewReader("ccc"))
assert.EqualError(t, err, "All cases failed:\n - Expected \"a\"\n - Expected \"b\"")
}
}
func TestDigit(t *testing.T) {
{
digit := AnyOf(Expect('0'), Expect('1'), Expect('2'), Expect('3'), Expect('4'), Expect('5'), Expect('6'), Expect('7'), Expect('8'), Expect('9'))
r, _ := ParseRuneReader(digit, strings.NewReader("5"))
assert.Equal(t, "5", r)
}
}
func TestDigits(t *testing.T) {
digit := ExpectAny([]rune("0123456789"))
digits := OneOrMore(digit)
{
r, _ := ParseRuneReader(digits, strings.NewReader("1"))
assert.EqualValues(t, []interface{}{"1"}, r)
}
{
r, _ := ParseRuneReader(digits, strings.NewReader("15"))
assert.EqualValues(t, []interface{}{"1", "5"}, r)
}
{
r, _ := ParseRuneReader(digits, strings.NewReader("15Kb"))
assert.EqualValues(t, []interface{}{"1", "5"}, r)
}
{
r, _ := ParseRuneReader(digits, strings.NewReader("123456789000kg"))
assert.EqualValues(t, []interface{}{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "0", "0"}, r)
}
{
_, err := ParseRuneReader(digits, strings.NewReader("abcabc"))
assert.EqualError(t, err, "Expected one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9")
}
}
func TestStrings(t *testing.T) {
word := ExpectString([]rune("symbol"))
{
r, _ := ParseRuneReader(word, strings.NewReader("symbol"))
assert.Equal(t, "symbol", r)
}
{
r, _ := ParseRuneReader(word, strings.NewReader("symbol1111111"))
assert.Equal(t, "symbol", r)
}
{
_, err := ParseRuneReader(word, strings.NewReader("symb0l"))
assert.EqualError(t, err, `Expected "o"`)
}
}
func TestMultipleStrings(t *testing.T) {
word1 := ExpectString([]rune("foo"))
word2 := ExpectString([]rune("symbol"))
word3 := ExpectString([]rune("word"))
parser := AnyOf(word1, word2, word3)
{
r, _ := ParseRuneReader(parser, strings.NewReader("foo"))
assert.Equal(t, "foo", r)
}
{
r, _ := ParseRuneReader(parser, strings.NewReader("symbol"))
assert.Equal(t, "symbol", r)
}
{
r, _ := ParseRuneReader(parser, strings.NewReader("word"))
assert.Equal(t, "word", r)
}
}
func TestMultipleStrings2(t *testing.T) {
// Before, scanner.buffer was just a []rune and not a pointer, this caused
// backtracking to not work and for example this test matched "f" instead
// of "foo". Now all the "scanner" instances have the buffer all in
// common so this is no longer a problem (and might also be more memory
// efficient)
word1 := ExpectString([]rune("fooer"))
word2 := ExpectString([]rune("foo"))
word3 := ExpectString([]rune("f"))
parser := AnyOf(word1, word2, word3)
{
r, _ := ParseRuneReader(parser, strings.NewReader("foooer"))
assert.Equal(t, "foo", r)
}
}
func TestCommon(t *testing.T) {
{
r, _ := ParseRuneReader(Integer, strings.NewReader("7"))
assert.Equal(t, "7", r)
}
{
r, _ := ParseRuneReader(Integer, strings.NewReader("123"))
assert.Equal(t, "123", r)
}
{
r, _ := ParseRuneReader(Integer, strings.NewReader("0123"))
assert.Equal(t, "0", r)
}
{
r, _ := ParseRuneReader(Decimal, strings.NewReader("3.14"))
assert.Equal(t, "3.14", r)
}
{
r, _ := ParseRuneReader(Decimal, strings.NewReader("0.681"))
assert.Equal(t, "0.681", r)
}
{
r, _ := ParseRuneReader(Decimal, strings.NewReader("123.456"))
assert.Equal(t, "123.456", r)
}
{
r, _ := ParseRuneReader(Decimal, strings.NewReader("+123.456"))
assert.Equal(t, "+123.456", r)
}
{
r, _ := ParseRuneReader(Decimal, strings.NewReader("-123.456"))
assert.Equal(t, "-123.456", r)
}
{
r, _ := ParseRuneReader(Decimal2, strings.NewReader("-123.456"))
assert.Equal(t, "-123.456", r)
}
}
func BenchmarkDecimal0(b *testing.B) {
var r interface{}
for n := 0; n < b.N; n++ {
r, _ = ParseRuneReader(Decimal, strings.NewReader("1.0"))
}
b.Log(r)
}
func BenchmarkDecimal1(b *testing.B) {
var r interface{}
for n := 0; n < b.N; n++ {
r, _ = ParseRuneReader(Decimal, strings.NewReader("-123.456"))
}
b.Log(r)
}
func BenchmarkDecimal2(b *testing.B) {
var r interface{}
for n := 0; n < b.N; n++ {
r, _ = ParseRuneReader(Decimal2, strings.NewReader("-123.456"))
}
b.Log(r)
}
// func ExampleRestarableOneOrMore() {
// parser := RestarableOneOrMore(
// StringifyResult(
// SeqOf(
// OneOrMore(ExpectAny([]rune("ab"))),
// SeqIgnore(AnyOf(Expect('_'), EOF)),
// ),
// ),
// Expect('_'),
// )
// r, err := ParseRuneReader(parser, strings.NewReader("aaaa_aaaaa_aaacccc_aaaaa_bbbbb"))
// if err != nil {
// log.Fatal(err)
// }
// // json, err := json.Marshal(r)
// // if err != nil {
// // log.Fatal(err)
// // }
// log.Printf("%+v", r)
// // Output: ["aaaa", "aaaaa", &Partial{"aaa"}, "aaaaa", "aa"]
// }
|
package site
import (
"net/http"
"net/http/httputil"
"net/url"
"os"
"time"
"github.com/Sirupsen/logrus"
"github.com/bryanl/dolb/server"
"github.com/gorilla/mux"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/digitalocean"
)
type Site struct {
Mux http.Handler
IDGen func() string
}
func New(config *server.Config) *Site {
clientID := config.OauthClientID
clientSecret := config.OauthClientSecret
gothic.CompleteUserAuth = completeUserAuth
goth.UseProviders(
digitalocean.New(clientID, clientSecret, config.OauthCallback, "read write"),
)
router := mux.NewRouter()
loggingRouter := loggingMiddleware(config.IDGen, router)
s := &Site{Mux: loggingRouter}
// auth
router.HandleFunc("/auth/digitalocean", beginGoth).Methods("GET")
oauthCallBack := &OauthCallback{DBSession: config.DBSession}
router.Handle("/auth/{provider}/callback", oauthCallBack).Methods("GET")
// TODO clean this up for prod mode
//homeHandler := &HomeHandler{bh: bh}
//router.Handle("/", homeHandler).Methods("GET")
// define this last
//assetDir := "/Users/bryan/Development/go/src/github.com/bryanl/dolb/site/assets/"
//baseAssetDir := "/Users/bryan/Development/go/src/github.com/bryanl/dolb/site"
//bowerCompDir := baseAssetDir + "/bower_components"
//bowerFs := http.StripPrefix("/bower_components", http.FileServer(http.Dir(bowerCompDir)))
//router.PathPrefix("/bower_components/{_dummy:.*}").Handler(bowerFs)
//appDir := baseAssetDir + "/app"
//fs := http.StripPrefix("/", http.FileServer(http.Dir(appDir)))
//router.PathPrefix("/{_dummy:.*}").Handler(fs)
u, _ := url.Parse("http://localhost:9000")
rp := httputil.NewSingleHostReverseProxy(u)
router.Handle("/{_dummy:.*}", rp)
return s
}
func loggingMiddleware(idGen func() string, h http.Handler) http.Handler {
return loggingHandler{handler: h, idGen: idGen}
}
type loggingHandler struct {
handler http.Handler
idGen func() string
}
func (h loggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
now := time.Now()
u := h.idGen()
logger := logrus.WithFields(logrus.Fields{
"request-id": u,
})
loggedWriter := &loggedResponse{w: w}
h.handler.ServeHTTP(loggedWriter, req)
if os.Getenv("QUIET_LOG") == "1" && loggedWriter.status <= 400 {
return
}
totalTime := time.Now().Sub(now)
logger.WithFields(logrus.Fields{
"action": "site request",
"method": req.Method,
"url": req.URL.String(),
"remote_addr": req.RemoteAddr,
"header-user_agent": req.Header.Get("User-Agent"),
"status": loggedWriter.status,
"request-elapased": totalTime / 1000000,
}).Info("site request")
}
type loggedResponse struct {
w http.ResponseWriter
status int
}
func (w *loggedResponse) Flush() {
if wf, ok := w.w.(http.Flusher); ok {
wf.Flush()
}
}
func (w *loggedResponse) Header() http.Header { return w.w.Header() }
func (w *loggedResponse) Write(d []byte) (int, error) { return w.w.Write(d) }
func (w *loggedResponse) WriteHeader(status int) {
w.status = status
w.w.WriteHeader(status)
}
|
package controllers
import (
"fmt"
"log"
"net/http"
"strconv"
"muto/context"
"muto/models"
"muto/views"
"github.com/gorilla/mux"
)
const (
IndexGalleries = "index_galleries"
ShowGallery = "show_gallery"
EditGallery = "edit_gallery"
// Bit Shift
maxMultipartMem = 1 << 20 // 1 megabyte
)
func NewGalleries(gs models.GalleryService, is models.ImageService, r *mux.Router) *Galleries {
return &Galleries{
New: views.NewView("materialize", "galleries/new"),
ShowView: views.NewView("materialize", "galleries/show"),
EditView: views.NewView("materialize", "galleries/edit"),
IndexView: views.NewView("materialize", "galleries/index"),
gs: gs,
is: is,
r: r,
}
}
type Galleries struct {
New *views.View
ShowView *views.View
EditView *views.View
IndexView *views.View
gs models.GalleryService
is models.ImageService
r *mux.Router
}
type GalleryForm struct {
Title string `schema:"title"`
}
// POST /galleries
func (g *Galleries) Index(w http.ResponseWriter, r *http.Request) {
account := context.Account(r.Context())
galleries, err := g.gs.ByAccountID(account.ID)
if err != nil {
log.Println(err)
http.Error(w, "Something went wrong.", http.StatusInternalServerError)
return
}
var vd views.Data
vd.Yield = galleries
g.IndexView.Render(w, r, vd)
}
// GET /galleries/:id
func (g *Galleries) Show(w http.ResponseWriter, r *http.Request) {
gallery, err := g.galleryByID(w, r)
if err != nil {
// The galleryByID method will already render the
// error for us, so we just need to return here.
return
}
var vd views.Data
vd.Yield = gallery
g.ShowView.Render(w, r, vd)
}
// GET /galleries/:id/edit
func (g *Galleries) Edit(w http.ResponseWriter, r *http.Request) {
gallery, err := g.galleryByID(w, r)
if err != nil {
// The galleryByID method will already render the error for us,
// so we just need to return here.
return
}
// An account needs to be logged in to access this page,
// so we can assume that the RequireAccount middleware has run
// and set the account for us in the request context.
account := context.Account(r.Context())
if gallery.AccountID != account.ID {
http.Error(w, "You do not have permission to edit this gallery",
http.StatusForbidden)
return
}
var vd views.Data
vd.Yield = gallery
g.EditView.Render(w, r, vd)
}
// POST /galleries/:id/images
func (g *Galleries) ImageUpload(w http.ResponseWriter, r *http.Request) {
gallery, err := g.galleryByID(w, r)
if err != nil {
return
}
account := context.Account(r.Context())
if gallery.AccountID != account.ID {
http.Error(w, "Gallery not found", http.StatusNotFound)
return
}
var vd views.Data
vd.Yield = gallery
err = r.ParseMultipartForm(maxMultipartMem)
if err != nil {
vd.SetAlert(err)
g.EditView.Render(w, r, vd)
return
}
// Iterate over uploaded files to process them.
files := r.MultipartForm.File["images"]
for _, f := range files {
// Open the uploaded file with existing code
file, err := f.Open()
if err != nil {
vd.SetAlert(err)
g.EditView.Render(w, r, vd)
return
}
defer file.Close()
// Call the ImageService's Create method.
// Create the image
err = g.is.Create(gallery.ID, file, f.Filename)
if err != nil {
vd.SetAlert(err)
g.EditView.Render(w, r, vd)
return
}
}
url, err := g.r.Get(EditGallery).URL("id",
fmt.Sprintf("%v", gallery.ID))
if err != nil {
http.Redirect(w, r, "/galleries", http.StatusFound)
return
}
http.Redirect(w, r, url.Path, http.StatusFound)
}
// POST /galleries/:id/images/:filename/delete
func (g *Galleries) ImageDelete(w http.ResponseWriter, r *http.Request) {
// Look up gallery by it's ID.
gallery, err := g.galleryByID(w, r)
if err != nil {
return
}
// Verify current account has permission to edit gallery.
account := context.Account(r.Context())
if gallery.AccountID != account.ID {
http.Error(w, "You do not have permission to edit "+
"this gallery or image", http.StatusForbidden)
return
}
// Get the filename from the path.
filename := mux.Vars(r)["filename"]
// Build the Image model.
i := models.Image{
Filename: filename,
GalleryID: gallery.ID,
}
// Try to delete the image.
err = g.is.Delete(&i)
if err != nil {
// Render the edit page with any errors.
var vd views.Data
vd.Yield = gallery
vd.SetAlert(err)
g.EditView.Render(w, r, vd)
return
}
// If all goes well, redirect to the edit gallery page.
url, err := g.r.Get(EditGallery).URL("id", fmt.Sprintf("%v", gallery.ID))
if err != nil {
log.Println(err)
http.Redirect(w, r, "/galleries", http.StatusFound)
return
}
http.Redirect(w, r, url.Path, http.StatusFound)
}
// POST /galleries/new
func (g *Galleries) Create(w http.ResponseWriter, r *http.Request) {
var vd views.Data
var form GalleryForm
if err := parseForm(r, &form); err != nil {
vd.SetAlert(err)
g.New.Render(w, r, vd)
return
}
account := context.Account(r.Context())
gallery := models.Gallery{
Title: form.Title,
AccountID: account.ID,
}
if err := g.gs.Create(&gallery); err != nil {
vd.SetAlert(err)
g.New.Render(w, r, vd)
return
}
// Generate a URL using the router and the names ShowGallery route.
url, err := g.r.Get(EditGallery).URL("id", strconv.Itoa(int(gallery.ID)))
// Check for errors creating the URL.
if err != nil {
log.Println(err)
http.Redirect(w, r, "/galleries", http.StatusNotFound)
return
}
// If no errors, use the URL and redirect
// to the path portion of that URL.
// We do not need the entire URL in case
// application is hosted on custom domain (i.e. "www.muto.world").
http.Redirect(w, r, url.Path, http.StatusFound)
}
// POST /galleries/update
func (g *Galleries) Update(w http.ResponseWriter, r *http.Request) {
gallery, err := g.galleryByID(w, r)
if err != nil {
return
}
account := context.Account(r.Context())
if gallery.AccountID != account.ID {
http.Error(w, "Gallery not found", http.StatusNotFound)
return
}
var vd views.Data
vd.Yield = gallery
var form GalleryForm
if err := parseForm(r, &form); err != nil {
// If there is an error we are going
// to render the EditView again
// but with an Alert message.
vd.SetAlert(err)
g.EditView.Render(w, r, vd)
return
}
gallery.Title = form.Title
err = g.gs.Update(gallery)
// If there is an error our alert will be an error. Otherwise
// we will still render an alert, but instead it will be
// a success message.
if err != nil {
vd.SetAlert(err)
} else {
vd.Alert = &views.Alert{
Level: views.AlertLvlSuccess,
Message: "Gallery updated successfully",
}
}
// Error or not, we are going to render the EditView with
// our updated information.
g.EditView.Render(w, r, vd)
}
// POST /gallery/:id/delete
func (g *Galleries) Delete(w http.ResponseWriter, r *http.Request) {
// Lookup the gallery using galleryByID
gallery, err := g.galleryByID(w, r)
if err != nil {
return
}
// Retrieve the account and verify they have permission
// to delete this gallery. Use RequireMiddleware
// on any routes mapped to this method.
account := context.Account(r.Context())
if gallery.AccountID != account.ID {
http.Error(w, "Permisson Denied! You do not have access to this gallery.", http.StatusForbidden)
return
}
var vd views.Data
err = g.gs.Delete(gallery.ID)
if err != nil {
// If an error occurs, set an alert and
// render the edit page with the error.
// Set the Yield to gallery so that
// the EditView is rendered correctly.
vd.SetAlert(err)
vd.Yield = gallery
g.EditView.Render(w, r, vd)
return
}
url, err := g.r.Get(IndexGalleries).URL()
if err != nil {
http.Redirect(w, r, "/", http.StatusFound)
return
}
http.Redirect(w, r, url.Path, http.StatusFound)
}
// galleryByID will parse the "id" variable from the
// request path using gorilla/mux and then use that ID to
// retrieve the gallery from the GalleryService
//
// galleryByID will return an error if one occurs, but it
// will also render the error with an http.Error function
// call, so you do not need to.
func (g *Galleries) galleryByID(w http.ResponseWriter,
r *http.Request) (*models.Gallery, error) {
// First we get the vars like we saw earlier. We do this
// so we can get variables from our path, like the "id"
// variable.
vars := mux.Vars(r)
// Next we need to get the "id" variable from our vars.
idStr := vars["id"]
// Our idStr is a string, so we use the Atoi function
// provided by the strconv package to convert it into an
// integer. This function can also return an error, so we
// need to check for errors and render an error.
id, err := strconv.Atoi(idStr)
if err != nil {
// If there is an error we will return the StatusNotFound
// status code, as the page requested is for an invalid
// gallery ID, which means the page doesn't exist.
log.Println(err)
http.Error(w, "Invalid gallery ID", http.StatusNotFound)
return nil, err
}
gallery, err := g.gs.ByID(uint(id))
if err != nil {
switch err {
case models.ErrNotFound:
http.Error(w, "Gallery not found", http.StatusNotFound)
default:
log.Println(err)
http.Error(w, "Hmmm..Something went wrong.",
http.StatusInternalServerError)
}
return nil, err
}
images, _ := g.is.ByGalleryID(gallery.ID)
gallery.Images = images
return gallery, nil
}
// Lookup galleryByCatergory
// Lookup galleryByTag
// Lookup galleryByDateCreated
|
package todoist
import (
"context"
"errors"
"fmt"
"github.com/fatih/color"
"net/http"
"net/url"
"strings"
)
type Project struct {
Entity
Name string `json:"name"`
Color int `json:"color"`
Indent int `json:"indent"`
ItemOrder int `json:"item_order"`
Collapsed int `json:"collapsed"`
Shared bool `json:"shared"`
IsArchived int `json:"is_archived"`
InboxProject bool `json:"inbox_project"`
TeamInbox bool `json:"team_inbox"`
}
func (p Project) String() string {
return strings.Repeat(" ", p.Indent-1) + "#" + p.Name
}
func (p Project) ColorString() string {
var attr color.Attribute
switch p.Color {
case 20, 21:
attr = color.FgHiBlack
case 1, 8, 14:
attr = color.FgHiRed
case 0, 15, 16:
attr = color.FgHiGreen
case 2, 3, 9:
attr = color.FgHiYellow
case 17, 18, 19:
attr = color.FgHiBlue
case 6, 12, 13:
attr = color.FgHiMagenta
case 4, 10, 11:
attr = color.FgHiCyan
case 5, 7:
default:
attr = color.FgWhite
}
return color.New(attr).Sprint(p.String())
}
type ProjectClient struct {
*Client
cache *projectCache
}
func (c *ProjectClient) Add(project Project) (*Project, error) {
if len(project.Name) == 0 {
return nil, errors.New("New project requires a name")
}
project.ID = GenerateTempID()
c.cache.store(project)
command := Command{
Type: "project_add",
Args: project,
UUID: GenerateUUID(),
TempID: project.ID,
}
c.queue = append(c.queue, command)
return &project, nil
}
func (c *ProjectClient) Update(project Project) (*Project, error) {
if !IsValidID(project.ID) {
return nil, fmt.Errorf("Invalid id: %s", project.ID)
}
command := Command{
Type: "project_update",
Args: project,
UUID: GenerateUUID(),
}
c.queue = append(c.queue, command)
return &project, nil
}
func (c *ProjectClient) Delete(ids []ID) error {
command := Command{
Type: "project_delete",
UUID: GenerateUUID(),
Args: map[string][]ID{
"ids": ids,
},
}
c.queue = append(c.queue, command)
return nil
}
func (c *ProjectClient) Archive(ids []ID) error {
command := Command{
Type: "project_archive",
UUID: GenerateUUID(),
Args: map[string][]ID{
"ids": ids,
},
}
c.queue = append(c.queue, command)
return nil
}
func (c *ProjectClient) Unarchive(ids []ID) error {
command := Command{
Type: "project_unarchive",
UUID: GenerateUUID(),
Args: map[string][]ID{
"ids": ids,
},
}
c.queue = append(c.queue, command)
return nil
}
type ProjectGetResponse struct {
Project Project
Notes []Note
}
func (c *ProjectClient) Get(ctx context.Context, id ID) (*ProjectGetResponse, error) {
values := url.Values{"project_id": {id.String()}}
req, err := c.newRequest(ctx, http.MethodGet, "projects/get", values)
if err != nil {
return nil, err
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
var out ProjectGetResponse
err = decodeBody(res, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type ProjectGetDataResponse struct {
Project Project
Items []Item
}
func (c *ProjectClient) GetData(ctx context.Context, id ID) (*ProjectGetDataResponse, error) {
values := url.Values{"project_id": {id.String()}}
req, err := c.newRequest(ctx, http.MethodGet, "projects/get_data", values)
if err != nil {
return nil, err
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
var out ProjectGetDataResponse
err = decodeBody(res, &out)
if err != nil {
return nil, err
}
return &out, nil
}
func (c *ProjectClient) GetArchived(ctx context.Context) (*[]Project, error) {
values := url.Values{}
req, err := c.newRequest(ctx, http.MethodGet, "projects/get_archived", values)
if err != nil {
return nil, err
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
var out []Project
err = decodeBody(res, &out)
if err != nil {
return nil, err
}
return &out, nil
}
func (c *ProjectClient) GetAll() []Project {
return c.cache.getAll()
}
func (c *ProjectClient) Resolve(id ID) *Project {
return c.cache.resolve(id)
}
func (c ProjectClient) FindByName(substr string) []Project {
if r := []rune(substr); len(r) > 0 && string(r[0]) == "#" {
substr = string(r[1:])
}
var res []Project
for _, p := range c.GetAll() {
if strings.Contains(p.Name, substr) {
res = append(res, p)
}
}
return res
}
func (c ProjectClient) FindOneByName(substr string) *Project {
projects := c.FindByName(substr)
for _, project := range projects {
if project.Name == substr {
return &project
}
}
if len(projects) > 0 {
return &projects[0]
}
return nil
}
type projectCache struct {
cache *[]Project
}
func (c *projectCache) getAll() []Project {
return *c.cache
}
func (c *projectCache) resolve(id ID) *Project {
for _, project := range *c.cache {
if project.ID == id {
return &project
}
}
return nil
}
func (c *projectCache) store(project Project) {
var res []Project
isNew := true
for _, p := range *c.cache {
if p.Equal(project) {
if !project.IsDeleted {
res = append(res, project)
}
isNew = false
} else {
res = append(res, p)
}
}
if isNew && !project.IsDeleted.Bool() {
res = append(res, project)
}
c.cache = &res
}
func (c *projectCache) remove(project Project) {
var res []Project
for _, p := range *c.cache {
if !p.Equal(project) {
res = append(res, p)
}
}
c.cache = &res
}
|
package redis
import (
"context"
"encoding/json"
"errors"
"github.com/go-redis/redis/v8"
"reflect"
"time"
)
func (c *client) GetPipelines(targets []interface{}) error {
ctx := context.TODO()
uids, err := c.rc.LRange(ctx, PIPELINES_KEY, 0, -1).Result()
if err != nil {
return wrapErr(err)
}
pipeRes := []*redis.StringCmd{}
pipe := c.rc.TxPipeline()
for _, uuid := range uids {
pipeRes = append(pipeRes, pipe.Get(ctx, pipelineKey(uuid)))
}
_, err = pipe.Exec(ctx)
if err != nil {
return wrapErr(err)
}
t := reflect.TypeOf(targets).Elem()
for _, pr := range pipeRes {
val := reflect.Zero(t).Interface()
err := json.Unmarshal([]byte(pr.Val()), &val)
if err != nil {
return err
}
targets = append(targets, val)
}
return nil
}
func (c *client) GetPipeline(uid string, target interface{}) error {
ctx := context.TODO()
if reflect.ValueOf(target).IsNil() {
return errors.New("target cannot be nil pointer")
}
res, err := c.rc.Get(ctx, pipelineKey(uid)).Result()
if err != nil {
return wrapErr(err)
}
return json.Unmarshal([]byte(res), target)
}
// save pipeline and extend the existing lease
func (c *client) SavePipeline(uid string, data interface{}) (*PipelineLease, error) {
ctx := context.TODO()
// check lease first, reject request if lease does not exist
mLease, err := c.rc.Get(ctx, leaseKey(uid)).Result()
if err != nil {
if err != redis.Nil {
return nil, err
} else {
return nil, LeaseNotFound
}
}
lease := &PipelineLease{}
err = json.Unmarshal([]byte(mLease), lease)
if err != nil {
return nil, err
}
//
if lease.Expires.Before(time.Now()) {
return nil, LeaseExpired
}
// extend lease duration
lease.Expires = time.Now().Add(LEASE_DURATION)
marshaled, err := json.Marshal(data)
if err != nil {
return nil, err
}
extendedLease, err := json.Marshal(lease)
if err != nil {
return nil, err
}
pipe := c.rc.TxPipeline()
pipe.Set(ctx, pipelineKey(uid), marshaled, 0)
pipe.Set(ctx, leaseKey(uid), extendedLease, LEASE_DURATION)
_, err = pipe.Exec(ctx)
return lease, wrapErr(err)
}
func (c *client) CreatePipeline(uid, owner string, data interface{}) (*PipelineLease, error) {
ctx := context.TODO()
marshaled, err := json.Marshal(data)
if err != nil {
return nil, err
}
// prepare lease
lease, mLease, err := newLease(owner, uid)
if err != nil {
return nil, err
}
pipe := c.rc.TxPipeline()
pipe.LPush(ctx, PIPELINES_KEY, uid)
pipe.Set(ctx, pipelineKey(uid), marshaled, 0)
pipe.Set(ctx, leaseKey(uid), mLease, LEASE_DURATION)
_, err = pipe.Exec(ctx)
return lease, wrapErr(err)
}
|
//Algorithm for Sieve of Eratosthenes
package main
import (
"fmt"
)
//This program only works for primes smaller or equal to 10e7
func Sieve(upperBound int64) []int64 {
_SieveSize := upperBound + 10
//Creates set to mark wich numbers are primes and wich are not
//true: not primes, false: primes
//this to favor default initialization of arrays in go
var bs [10000010]bool
//creates a slice to save the primes it finds
primes := make([]int64, 0, 1000)
bs[0] = true
bs[1] = true
//looping over the numbers set
for i := int64(0); i <= _SieveSize; i++ {
//if one number is found that is unmarked as a compund number, mark all its multiples
if !bs[i] {
for j := i * i; j <= _SieveSize; j += i {
bs[j] = true
}
//Add the prime you just find to the slice of primes
primes = append(primes, i)
}
}
return primes
}
/*func main() {
//prints first N primes into console
N := 100
primes := Sieve(N)
fmt.Println(primes)
}*/
|
package handler
import (
"bytes"
"html/template"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/GoGroup/Movie-and-events/model"
"github.com/GoGroup/Movie-and-events/rtoken"
"github.com/GoGroup/Movie-and-events/event/repository"
"github.com/GoGroup/Movie-and-events/event/service"
schrep "github.com/GoGroup/Movie-and-events/schedule/repository"
schser "github.com/GoGroup/Movie-and-events/schedule/service"
cinrep "github.com/GoGroup/Movie-and-events/cinema/repository"
cinser "github.com/GoGroup/Movie-and-events/cinema/service"
hallrepo "github.com/GoGroup/Movie-and-events/hall/repository"
hallser "github.com/GoGroup/Movie-and-events/hall/service"
)
func TestNewAdminSchedulePost(t *testing.T) {
tmpl := template.Must(template.ParseGlob("../../../view/template/*"))
schrepo := schrep.NewMockScheduleRepo(nil)
schserv := schser.NewScheduleService(schrepo)
hrep := hallrepo.NewMockHallRepo(nil)
hser := hallser.NewHallService(hrep)
cinr := cinrep.NewMockCinemaRepo(nil)
cins := cinser.NewCinemaService(cinr)
adminSchHandler := NewAdminHandler(tmpl, cins, hser, schserv, nil, nil, nil)
mux := http.NewServeMux()
mux.HandleFunc("/admin/cinemas/schedule/new/", adminSchHandler.NewAdminSchedule)
ts := httptest.NewTLSServer(mux)
defer ts.Close()
tc := ts.Client()
sURL := ts.URL
form := url.Values{}
csrfSignKey := []byte(rtoken.GenerateRandomID(32))
form.Add("mid", string(model.ScheduleMock.MoviemID))
form.Add("time", string(model.ScheduleMock.StartingTime))
form.Add("day", string(model.ScheduleMock.Day))
form.Add("3or2d", string(model.ScheduleMock.Dimension))
CSFRToken, _ := rtoken.GenerateCSRFToken(csrfSignKey)
form.Add(csrfHKey, CSFRToken)
resp, err := tc.PostForm(sURL+"/admin/cinemas/schedule/new/1", form)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("want %d, got %d", http.StatusOK, resp.StatusCode)
}
defer resp.Body.Close()
if err != nil {
t.Fatal(err)
}
}
func TestAdminEventNew(t *testing.T) {
tmpl := template.Must(template.ParseGlob("../../../view/template/*"))
eventRepo := repository.NewMockEventRepo(nil)
eventServ := service.NewEventService(eventRepo)
adminEvHandler := NewAdminHandler(tmpl, nil, nil, nil, nil, eventServ, nil)
mux := http.NewServeMux()
mux.HandleFunc("/admin/cinemas/events/new/", adminEvHandler.AdminEventsNew)
ts := httptest.NewTLSServer(mux)
defer ts.Close()
tc := ts.Client()
URL := ts.URL
csrfSignKey := []byte(rtoken.GenerateRandomID(32))
form := url.Values{}
form.Add("name", model.EvenMock.Name)
form.Add("description", model.EvenMock.Description)
form.Add("time", model.EvenMock.Time)
form.Add("image", model.EvenMock.Image)
form.Add("location", model.EvenMock.Location)
CSFRToken, _ := rtoken.GenerateCSRFToken(csrfSignKey)
form.Add(csrfHKey, CSFRToken)
resp, err := tc.PostForm(URL+"/admin/cinemas/events/new/", form)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("want %d, got %d", http.StatusOK, resp.StatusCode)
}
defer resp.Body.Close()
}
func TestAdminScheduleDelete(t *testing.T) {
tmpl := template.Must(template.ParseGlob("../../../view/template/*"))
schrepo := schrep.NewMockScheduleRepo(nil)
schserv := schser.NewScheduleService(schrepo)
hrep := hallrepo.NewMockHallRepo(nil)
hser := hallser.NewHallService(hrep)
cinr := cinrep.NewMockCinemaRepo(nil)
cins := cinser.NewCinemaService(cinr)
adminSchHandler := NewAdminHandler(tmpl, cins, hser, schserv, nil, nil, nil)
mux := http.NewServeMux()
mux.HandleFunc("/admin/cinemas/schedule/delete/", adminSchHandler.AdminScheduleDelete)
ts := httptest.NewTLSServer(mux)
defer ts.Close()
tc := ts.Client()
URL := ts.URL
resp, err := tc.Get(URL + "/admin/cinemas/schedule/delete/1/1")
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("want %d, got %d", http.StatusOK, resp.StatusCode)
}
defer resp.Body.Close()
//body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
}
func TestAdminEvent(t *testing.T) {
tmpl := template.Must(template.ParseGlob("../../../view/template/*"))
eventRepo := repository.NewMockEventRepo(nil)
eventServ := service.NewEventService(eventRepo)
adminEvHandler := NewAdminHandler(tmpl, nil, nil, nil, nil, eventServ, nil)
mux := http.NewServeMux()
mux.HandleFunc("/admin/events/", adminEvHandler.AdminEventList)
ts := httptest.NewTLSServer(mux)
defer ts.Close()
tc := ts.Client()
URL := ts.URL
resp, err := tc.Get(URL + "/admin/events/")
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("want %d, got %d", http.StatusOK, resp.StatusCode)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if !bytes.Contains(body, []byte("MockName 1")) {
t.Errorf("want body to contain %q", body)
}
}
func TestAdminEventDelete(t *testing.T) {
tmpl := template.Must(template.ParseGlob("../../../view/template/*"))
eventRepo := repository.NewMockEventRepo(nil)
eventServ := service.NewEventService(eventRepo)
adminEvHandler := NewAdminHandler(tmpl, nil, nil, nil, nil, eventServ, nil)
mux := http.NewServeMux()
mux.HandleFunc("/admin/events/delete/", adminEvHandler.AdminDeleteEvents)
ts := httptest.NewTLSServer(mux)
defer ts.Close()
tc := ts.Client()
URL := ts.URL
resp, err := tc.Get(URL + "/admin/events/delete/1")
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("want %d, got %d", http.StatusOK, resp.StatusCode)
}
defer resp.Body.Close()
//body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
}
func TestAdminEventUpdate(t *testing.T) {
tmpl := template.Must(template.ParseGlob("../../../view/template/*"))
eventRepo := repository.NewMockEventRepo(nil)
eventServ := service.NewEventService(eventRepo)
adminEvHandler := NewAdminHandler(tmpl, nil, nil, nil, nil, eventServ, nil)
mux := http.NewServeMux()
mux.HandleFunc("/admin/events/update/", adminEvHandler.AdminEventUpdateList)
ts := httptest.NewTLSServer(mux)
defer ts.Close()
tc := ts.Client()
URL := ts.URL
csrfSignKey := []byte(rtoken.GenerateRandomID(32))
form := url.Values{}
form.Add("name", model.EvenMock.Name)
form.Add("description", model.EvenMock.Description)
form.Add("time", model.EvenMock.Time)
form.Add("image", model.EvenMock.Image)
form.Add("location", model.EvenMock.Location)
CSFRToken, _ := rtoken.GenerateCSRFToken(csrfSignKey)
form.Add(csrfHKey, CSFRToken)
resp, err := tc.PostForm(URL+"/admin/events/update/1", form)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("want %d, got %d", http.StatusOK, resp.StatusCode)
}
defer resp.Body.Close()
}
|
package domain
import "encoding/gob"
// 登录用户
// 由 signon, profile, account 三张表组成
type Account struct {
UserName string
Password string
Email string
FirstName string
LastName string
Status string
Address1 string
Address2 string
City string
State string
Zip string
Country string
Phone string
FavouriteCategoryId string
LanguagePreference string
ListOption bool
BannerOption bool
BannerName string
}
func init() {
gob.Register(&Account{})
}
|
package codeGeneration
import (
. "ast"
. "backend/filewriter"
"fmt"
"strconv"
)
// CodeGenerator: Using a constructor that provides an address of the place holder
// for the list of assembly instructions for the program (And the AST with the symbol table),
// the code generator can use the "GenerateCode" function to fill the assembly list
// instrs with the assembly produced by traversing the tree
type CodeGenerator struct {
root *Program // Root of the AST
instrs *ARMList // List of assembly instructions for the program
msgInstrs *ARMList // List of assembly instructions to create msg labels
symTable *SymbolTable // Used to map variable identifiers to their types
funcSymTables []*SymbolTable // Used to map function variable indentifier to ther types
classes []*Class // List of classes defined within the program
functionList []*Function // List of functions defined within the program
funcInstrs *ARMList // List of assembly instructions that define functions and their labels
progFuncInstrs *ARMList // List of assembly instructions that define program generated functions e.g. p_print_string
progFuncNames *[]string // List of program defined function names. Used to avoid program redefinitions
globalStack *scopeData // Stack data for the global scope
currStack *scopeData // Stack data for the current scope
msgMap map[string]string // Maps string values to their msg labels
messages []string // A slice of all messages used within the program
currentLabelIndex int // The index of the current generic label (used in control flow functions)
functionDefs []Ident // A list of function identifiers that have been defined
}
// Constructor for the code generator.
func ConstructCodeGenerator(cRoot *Program, cInstrs *ARMList, cSymTable *SymbolTable) CodeGenerator {
cg := CodeGenerator{root: cRoot, instrs: cInstrs, msgInstrs: new(ARMList),
funcInstrs: new(ARMList), progFuncInstrs: new(ARMList), progFuncNames: new([]string),
symTable: cSymTable, globalStack: &scopeData{identMsgLabelMap: make(map[Ident]string)}}
// The program starts off with the current scope as the global scope
cg.currStack = cg.globalStack
cg.msgMap = make(map[string]string)
return cg
}
// Evaluates the evaluation using the code generator
func (cg *CodeGenerator) eval(e Evaluation) Type {
var eType Type
if cg.currStack.isFunc {
context1 := &Context{cg.root.FunctionList, cg.getFuncSymTable(), cg.classes}
eType, _ = e.Eval(context1)
// eType, _ = e.Eval(cg.root.FunctionList, cg.getFuncSymTable())
} else {
context2 := &Context{cg.root.FunctionList, cg.symTable, cg.classes}
eType, _ = e.Eval(context2)
}
return eType
}
// Provides information about the stack in relation to a specific scope
type scopeData struct {
currP int // the current position of the pointer to the stack
size int // size of the variable stack scope space in bytes
parentScope *scopeData // Address of the parent scope
isFunc bool // true iff the scope data is used for a function scope
paramList *[]Param // List of parameters for a function if the scope is a function scope
isMethod bool // true iff the scope data is used for a class method scope
fieldList *[]Field // List of fields for a class object if the scope is a class scope
identMsgLabelMap map[Ident]string // Map of string idents within this scope to their message labels
extraOffset int // Extra offset used when stack is used to store intermediate values
}
// Creates new scope data for a new scope.
func (cg *CodeGenerator) setNewScope(varSpaceSize int) {
if varSpaceSize > 0 {
appendAssembly(cg.currInstrs(), "SUB sp, sp, #"+strconv.Itoa(varSpaceSize), 1, 1)
}
newScope := &scopeData{}
newScope.currP = varSpaceSize
newScope.size = varSpaceSize
newScope.parentScope = cg.currStack
newScope.isFunc = cg.currStack.isFunc
newScope.identMsgLabelMap = make(map[Ident]string)
if newScope.isFunc {
newScope.paramList = cg.currStack.paramList
}
cg.currStack = newScope
if cg.currStack.isFunc {
cg.funcSymTables[len(cg.funcSymTables)-1] = cg.funcSymTables[len(cg.funcSymTables)-1].GetFrontChild()
} else {
cg.symTable = cg.symTable.GetFrontChild()
}
}
// returns current function symbol table
func (cg *CodeGenerator) getFuncSymTable() *SymbolTable {
if len(cg.funcSymTables) == 0 {
return nil
}
return cg.funcSymTables[len(cg.funcSymTables)-1]
}
// Creates new scope data for a new function scope. Sets isFunc to true which
// set the code generator into function mode (So statements evaluate for functions not main)
func (cg *CodeGenerator) setNewFuncScope(varSpaceSize int, paramList *[]Param, funcSymTable *SymbolTable) {
newScope := &scopeData{}
newScope.currP = varSpaceSize
newScope.size = varSpaceSize
newScope.parentScope = cg.currStack
newScope.isFunc = true
newScope.paramList = paramList
newScope.identMsgLabelMap = make(map[Ident]string)
cg.currStack = newScope
cg.funcSymTables = append(cg.funcSymTables, funcSymTable)
}
// Creates new scope data for a new function scope. Sets isFunc to true which
// set the code generator into function mode (So statements evaluate for functions not main)
func (cg *CodeGenerator) setNewMethodScope(varSpaceSize int, paramList *[]Param, funcSymTable *SymbolTable, fieldList *[]Field) {
newScope := &scopeData{}
newScope.currP = varSpaceSize
newScope.size = varSpaceSize
newScope.parentScope = cg.currStack
newScope.isFunc = true
newScope.paramList = paramList
newScope.identMsgLabelMap = make(map[Ident]string)
newScope.isMethod = true
newScope.fieldList = fieldList
cg.currStack = newScope
cg.funcSymTables = append(cg.funcSymTables, funcSymTable)
}
// Removes current scope and replaces it with the parent scope
func (cg *CodeGenerator) removeCurrScope() {
// add sp, sp, #n to remove variable space
if cg.currStack.size > 0 {
appendAssembly(cg.currInstrs(), "ADD sp, sp, #"+strconv.Itoa(cg.currStack.size), 1, 1)
}
cg.currStack = cg.currStack.parentScope
if cg.currStack.isFunc {
cg.funcSymTables[len(cg.funcSymTables)-1] = cg.funcSymTables[len(cg.funcSymTables)-1].Parent
} else {
cg.symTable = cg.symTable.Parent
}
if cg.currStack.isFunc {
if cg.getFuncSymTable() != nil {
cg.getFuncSymTable().RemoveChild()
}
} else {
if cg.symTable != nil {
cg.symTable.RemoveChild()
}
}
}
// Removes current function scope
func (cg *CodeGenerator) removeFuncScope() {
cg.currStack = cg.currStack.parentScope
cg.funcSymTables = cg.funcSymTables[:len(cg.funcSymTables)]
}
// Used to add extra offset to the current scope when intermediate values are stored on the stack
func (cg *CodeGenerator) addExtraOffset(n int) {
cg.currStack.extraOffset += n
}
// Used to sub extra offset to the current scope when intermediate values are stored on the stack
func (cg *CodeGenerator) subExtraOffset(n int) {
cg.currStack.extraOffset -= n
}
// Returns cg.funcInstrs iff the current scope is a function scope. cg.instrs otherwise
func (cg *CodeGenerator) currInstrs() *ARMList {
if cg.currStack.isFunc {
return cg.funcInstrs
} else {
return cg.instrs
}
}
// Returns cg.funcSymbolTable iff the current scope is a function scope. cg.symbolTable otherwise
func (cg *CodeGenerator) currSymTable() *SymbolTable {
if cg.currStack.isFunc {
return cg.getFuncSymTable()
} else {
return cg.symTable
}
}
// Decreases current pointer to the stack by n
// Returns new currP as a string (Does not have to be used)
func (cg *CodeGenerator) subCurrP(n int) string {
cg.currStack.currP = cg.currStack.currP - n
return strconv.Itoa(cg.currStack.currP)
}
// Using the ARMList pointer provided in the constructor,
// this function will fill the slice with an array of assembly instructions
// based on the provided AST
func (cg *CodeGenerator) GenerateCode() {
cg.cgVisitProgram(cg.root)
cg.buildFullInstr()
}
// Using all the code generators ARMList, instrs is modified to include
// all ARMList instructions in the correct order
func (cg *CodeGenerator) buildFullInstr() {
*cg.instrs = append(*cg.funcInstrs, (*cg.instrs)...)
*cg.instrs = append(*cg.msgInstrs, (*cg.instrs)...)
*cg.instrs = append(*cg.instrs, *cg.progFuncInstrs...)
}
// Returns a msg label value for the strValue using msgMap
// If strValue is not contained in the map then it will be added to the map
// with a new msg label value (which will be returned)
// e.g. =msg_0
func (cg *CodeGenerator) getMsgLabel(ident Ident, strValue string) string {
/*msgLabel, contained := cg.msgMap[strValue]
if contained {
return "=" + msgLabel
}
cg.msgMap[strValue] = "msg_" + strconv.Itoa(len(cg.msgMap))
addMsgLabel(cg.msgInstrs, cg.msgMap[strValue], strValue)
*/
// For string constants
if ident == "" {
for i, message := range cg.messages {
if strValue == message {
return "=msg_" + strconv.Itoa(i)
}
}
newIndex := len(cg.messages)
cg.messages = append(cg.messages, strValue)
newLabel := "msg_" + strconv.Itoa(newIndex)
addMsgLabel(cg.msgInstrs, newLabel, strValue)
return "=" + newLabel
}
// If the ident hasnt been previously defined in a msg
if !strIdentPrevDefined(ident, cg.currStack) {
newIndex := len(cg.messages)
cg.messages = append(cg.messages, strValue)
newLabel := "msg_" + strconv.Itoa(newIndex)
addMsgLabel(cg.msgInstrs, newLabel, strValue)
cg.currStack.identMsgLabelMap[ident] = newLabel
return "=" + newLabel
}
// Find the idents label using all scopes
label := findLabel(ident, cg.currStack)
return "=" + label
}
// Adds the function name to cg.progFuncNames iff it isnt already in the list
// Returns true iff funcName is already in the list
func (cg *CodeGenerator) AddCheckProgName(progName string) bool {
for _, s := range *cg.progFuncNames {
if s == progName {
// if progName has already been defined return true
return true
}
}
// else add progName to the list
*cg.progFuncNames = append(*cg.progFuncNames, progName)
return false
}
// Using symbol tables, a offset to the sp is returned so the ident value can
// be executed
func (cg *CodeGenerator) getIdentOffset(ident Ident) (int, Type) {
return cg.findIdentOffset(ident, cg.currSymTable(), cg.currStack, 0)
}
// Checks if the ident is in the given symbol table. If not the parents are searched
// The function assumes an offset will be found eventually (semantically correct)
func (cg *CodeGenerator) findIdentOffset(ident Ident, symTable *SymbolTable,
scope *scopeData, accOffset int) (int, Type) {
if symTable == nil {
fmt.Println("ERROR: incorrect symbol table")
return 0, Int
}
if scope.isFunc && isParamInList(ident, scope.paramList) {
offset, typ := getParamOffset(ident, scope.paramList)
offset = -offset
return offset + scope.extraOffset + ADDRESS_SIZE + funcVarSize(scope), typ //-scope.currP
}
/*fmt.Println("Ident: ", ident, " table: ", symTable, " accOffset: ", accOffset)
fmt.Println("Scope: ", scope)
fmt.Println("Defined?:", symTable.IsOffsetDefined(ident), "\n")*/
if !symTable.IsOffsetDefined(ident) {
return cg.findIdentOffset(ident, symTable.Parent, scope.parentScope, accOffset+scope.size+scope.extraOffset)
}
return symTable.GetOffset(string(ident)) + accOffset + scope.extraOffset, symTable.GetTypeOfIdent(ident)
}
func (cg *CodeGenerator) getNewLabel() string {
newLabel := "L" + strconv.Itoa(cg.currentLabelIndex)
cg.currentLabelIndex++
return newLabel
}
func (cg *CodeGenerator) isFunctionDefined(ident Ident) bool {
for _, def := range cg.functionDefs {
if string(ident) == string(def) {
return true
}
}
return false
}
func (cg *CodeGenerator) addFunctionDef(ident Ident) {
cg.functionDefs = append(cg.functionDefs, ident)
}
// Returns total variable size of a list of evaluations
func (cg *CodeGenerator) evalSize(es []Evaluation) int {
total := 0
var eType Type
for _, e := range es {
eType = cg.eval(e)
total += sizeOf(eType)
}
return total
}
// Returns class with the given class identifier
func (cg *CodeGenerator) getClass(classIdent ClassType) *Class {
for _, class := range cg.classes {
if classIdent == class.Ident {
return class
}
}
return nil
}
// Returns the offset to a object on the stack. Can only be used when within a method scope
func (cg *CodeGenerator) getObjectOffset() int {
return ADDRESS_SIZE + paramListSize(*cg.currStack.paramList)
}
|
package sync
import "sync"
var waitGroupPool = sync.Pool{
New: func() interface{} {
return new(sync.WaitGroup)
},
}
func AcquireWaitGroup() *sync.WaitGroup {
return waitGroupPool.Get().(*sync.WaitGroup) // nolint:forcetypeassert
}
func ReleaseWaitGroup(wg *sync.WaitGroup) {
waitGroupPool.Put(wg)
}
|
// Copyright Jetstack Ltd. See LICENSE for details.
package cmd
import (
"github.com/spf13/cobra"
)
// initCmd represents the init command
var renewtokenCmd = &cobra.Command{
Use: "renew-token",
Short: "Renew token on vault server.",
Run: func(cmd *cobra.Command, args []string) {
i, err := newInstanceToken(cmd)
if err != nil {
Must(err)
}
if err := i.TokenRenewRun(); err != nil {
Must(err)
}
},
}
func init() {
instanceTokenFlags(renewtokenCmd)
RootCmd.AddCommand(renewtokenCmd)
}
|
package gadb
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v4/hrp/internal/builtin"
"github.com/httprunner/httprunner/v4/hrp/internal/code"
)
type DeviceFileInfo struct {
Name string
Mode os.FileMode
Size uint32
LastModified time.Time
}
func (info DeviceFileInfo) IsDir() bool {
return (info.Mode & (1 << 14)) == (1 << 14)
}
const DefaultFileMode = os.FileMode(0o664)
type DeviceState string
const (
StateUnknown DeviceState = "UNKNOWN"
StateOnline DeviceState = "online"
StateOffline DeviceState = "offline"
StateDisconnected DeviceState = "disconnected"
)
var deviceStateStrings = map[string]DeviceState{
"": StateDisconnected,
"offline": StateOffline,
"device": StateOnline,
}
func deviceStateConv(k string) (deviceState DeviceState) {
var ok bool
if deviceState, ok = deviceStateStrings[k]; !ok {
return StateUnknown
}
return
}
type DeviceForward struct {
Serial string
Local string
Remote string
Reverse bool
// LocalProtocol string
// RemoteProtocol string
}
type Device struct {
adbClient Client
serial string
attrs map[string]string
feat Features
}
func (d *Device) HasFeature(name Feature) bool {
feats, err := d.GetFeatures()
if err != nil || len(feats) == 0 {
return false
}
return feats.HasFeature(name)
}
func (d *Device) GetFeatures() (features Features, err error) {
if len(d.feat) > 0 {
return d.feat, nil
}
return d.features()
}
func (d *Device) features() (features Features, err error) {
res, err := d.executeCommand("host:features")
if err != nil {
return nil, err
}
if len(res) > 4 {
// stip hash
res = res[4:]
}
fs := strings.Split(string(res), ",")
features = make(Features, len(fs))
for _, f := range fs {
features[Feature(f)] = struct{}{}
}
d.feat = features
return features, nil
}
func (d *Device) Product() string {
return d.attrs["product"]
}
func (d *Device) Model() string {
return d.attrs["model"]
}
func (d *Device) Usb() string {
return d.attrs["usb"]
}
func (d *Device) transportId() string {
return d.attrs["transport_id"]
}
func (d *Device) DeviceInfo() map[string]string {
return d.attrs
}
func (d *Device) Serial() string {
// resp, err := d.adbClient.executeCommand(fmt.Sprintf("host-serial:%s:get-serialno", d.serial))
return d.serial
}
func (d *Device) IsUsb() bool {
return d.Usb() != ""
}
func (d *Device) State() (DeviceState, error) {
resp, err := d.adbClient.executeCommand(fmt.Sprintf("host-serial:%s:get-state", d.serial))
return deviceStateConv(resp), err
}
func (d *Device) DevicePath() (string, error) {
resp, err := d.adbClient.executeCommand(fmt.Sprintf("host-serial:%s:get-devpath", d.serial))
return resp, err
}
func (d *Device) Forward(localPort int, remoteInterface interface{}, noRebind ...bool) (err error) {
command := ""
var remote string
local := fmt.Sprintf("tcp:%d", localPort)
switch r := remoteInterface.(type) {
// for unix sockets
case string:
remote = r
case int:
remote = fmt.Sprintf("tcp:%d", r)
}
if len(noRebind) != 0 && noRebind[0] {
command = fmt.Sprintf("host-serial:%s:forward:norebind:%s;%s", d.serial, local, remote)
} else {
command = fmt.Sprintf("host-serial:%s:forward:%s;%s", d.serial, local, remote)
}
_, err = d.adbClient.executeCommand(command, true)
return
}
func (d *Device) ForwardList() (deviceForwardList []DeviceForward, err error) {
var forwardList []DeviceForward
if forwardList, err = d.adbClient.ForwardList(); err != nil {
return nil, err
}
deviceForwardList = make([]DeviceForward, 0, len(deviceForwardList))
for i := range forwardList {
if forwardList[i].Serial == d.serial {
deviceForwardList = append(deviceForwardList, forwardList[i])
}
}
// resp, err := d.adbClient.executeCommand(fmt.Sprintf("host-serial:%s:list-forward", d.serial))
return
}
func (d *Device) ForwardKill(localPort int) (err error) {
local := fmt.Sprintf("tcp:%d", localPort)
_, err = d.adbClient.executeCommand(fmt.Sprintf("host-serial:%s:killforward:%s", d.serial, local), true)
return
}
func (d *Device) ReverseForward(localPort int, remoteInterface interface{}, noRebind ...bool) (err error) {
var command string
var remote string
local := fmt.Sprintf("tcp:%d", localPort)
switch r := remoteInterface.(type) {
// for unix sockets
case string:
remote = r
case int:
remote = fmt.Sprintf("tcp:%d", r)
}
if len(noRebind) != 0 && noRebind[0] {
command = fmt.Sprintf("reverse:forward:norebind:%s;%s", remote, local)
} else {
command = fmt.Sprintf("reverse:forward:%s;%s", remote, local)
}
_, err = d.executeCommand(command, true)
return
}
func (d *Device) ReverseForwardList() (deviceForwardList []DeviceForward, err error) {
res, err := d.executeCommand("reverse:list-forward")
if err != nil {
return nil, err
}
resStr := string(res)
lines := strings.Split(resStr, "\n")
for _, line := range lines {
groups := strings.Split(line, " ")
if len(groups) == 3 {
deviceForwardList = append(deviceForwardList, DeviceForward{
Reverse: true,
Serial: d.serial,
Remote: groups[1],
Local: groups[2],
})
}
}
return
}
func (d *Device) ReverseForwardKill(remoteInterface interface{}) error {
remote := ""
switch r := remoteInterface.(type) {
case string:
remote = r
case int:
remote = fmt.Sprintf("tcp:%d", r)
}
_, err := d.executeCommand(fmt.Sprintf("reverse:killforward:%s", remote), true)
return err
}
func (d *Device) ReverseForwardKillAll() error {
_, err := d.executeCommand("reverse:killforward-all")
return err
}
func (d *Device) RunShellCommand(cmd string, args ...string) (string, error) {
raw, err := d.RunShellCommandWithBytes(cmd, args...)
if err != nil {
if errors.Is(err, code.AndroidDeviceConnectionError) {
return "", err
}
return "", errors.Wrap(code.AndroidShellExecError, err.Error())
}
return string(raw), nil
}
func (d *Device) RunShellCommandWithBytes(cmd string, args ...string) ([]byte, error) {
if d.HasFeature(FeatShellV2) {
return d.RunShellCommandV2WithBytes(cmd, args...)
}
if len(args) > 0 {
cmd = fmt.Sprintf("%s %s", cmd, strings.Join(args, " "))
}
if strings.TrimSpace(cmd) == "" {
return nil, errors.New("adb shell: command cannot be empty")
}
log.Debug().Str("cmd",
fmt.Sprintf("adb -s %s shell %s", d.serial, cmd)).
Msg("run adb command")
raw, err := d.executeCommand(fmt.Sprintf("shell:%s", cmd))
return raw, err
}
func (d *Device) RunShellCommandV2(cmd string, args ...string) (string, error) {
raw, err := d.RunShellCommandV2WithBytes(cmd, args...)
return string(raw), err
}
// RunShellCommandV2WithBytes shell v2, 支持后台运行而不会阻断
func (d *Device) RunShellCommandV2WithBytes(cmd string, args ...string) ([]byte, error) {
if len(args) > 0 {
cmd = fmt.Sprintf("%s %s", cmd, strings.Join(args, " "))
}
if strings.TrimSpace(cmd) == "" {
return nil, errors.New("adb shell: command cannot be empty")
}
log.Debug().Str("cmd",
fmt.Sprintf("adb -s %s shell %s", d.serial, cmd)).
Msg("run adb command in v2")
raw, err := d.executeCommand(fmt.Sprintf("shell,v2,raw:%s", cmd))
if err != nil {
return raw, err
}
return d.parseV2CommandWithBytes(raw)
}
func (d *Device) parseV2CommandWithBytes(input []byte) (res []byte, err error) {
if len(input) == 0 {
return input, nil
}
reader := bytes.NewReader(input)
sizeBuf := make([]byte, 4)
var (
resBuf []byte
exitCode int
)
loop:
for {
msgCode, err := reader.ReadByte()
if err != nil {
return input, err
}
switch msgCode {
case 0x01, 0x02: // STDOUT, STDERR
_, err = io.ReadFull(reader, sizeBuf)
if err != nil {
return input, err
}
size := binary.LittleEndian.Uint32(sizeBuf)
if cap(resBuf) < int(size) {
resBuf = make([]byte, int(size))
}
_, err = io.ReadFull(reader, resBuf[:size])
if err != nil {
return input, err
}
res = append(res, resBuf[:size]...)
case 0x03: // EXIT
_, err = io.ReadFull(reader, sizeBuf)
if err != nil {
return input, err
}
size := binary.LittleEndian.Uint32(sizeBuf)
if cap(resBuf) < int(size) {
resBuf = make([]byte, int(size))
}
ec, err := reader.ReadByte()
if err != nil {
return input, err
}
exitCode = int(ec)
break loop
default:
return input, nil
}
}
if exitCode != 0 {
return nil, errors.New(string(res))
}
return res, nil
}
func (d *Device) EnableAdbOverTCP(port ...int) (err error) {
if len(port) == 0 {
port = []int{AdbDaemonPort}
}
log.Info().Str("cmd",
fmt.Sprintf("adb -s %s tcpip %d", d.serial, port[0])).
Msg("enable adb over tcp")
_, err = d.executeCommand(fmt.Sprintf("tcpip:%d", port[0]), true)
return
}
func (d *Device) createDeviceTransport() (tp transport, err error) {
if tp, err = newTransport(fmt.Sprintf("%s:%d", d.adbClient.host, d.adbClient.port)); err != nil {
return transport{}, err
}
if err = tp.Send(fmt.Sprintf("host:transport:%s", d.serial)); err != nil {
return transport{}, err
}
err = tp.VerifyResponse()
return
}
func (d *Device) executeCommand(command string, onlyVerifyResponse ...bool) (raw []byte, err error) {
if len(onlyVerifyResponse) == 0 {
onlyVerifyResponse = []bool{false}
}
var tp transport
if tp, err = d.createDeviceTransport(); err != nil {
return nil, err
}
defer func() { _ = tp.Close() }()
if err = tp.Send(command); err != nil {
return nil, err
}
if err = tp.VerifyResponse(); err != nil {
return nil, err
}
if onlyVerifyResponse[0] {
return
}
raw, err = tp.ReadBytesAll()
return
}
func (d *Device) List(remotePath string) (devFileInfos []DeviceFileInfo, err error) {
var tp transport
if tp, err = d.createDeviceTransport(); err != nil {
return nil, err
}
defer func() { _ = tp.Close() }()
var sync syncTransport
if sync, err = tp.CreateSyncTransport(); err != nil {
return nil, err
}
defer func() { _ = sync.Close() }()
if err = sync.Send("LIST", remotePath); err != nil {
return nil, err
}
devFileInfos = make([]DeviceFileInfo, 0)
var entry DeviceFileInfo
for entry, err = sync.ReadDirectoryEntry(); err == nil; entry, err = sync.ReadDirectoryEntry() {
if entry == (DeviceFileInfo{}) {
break
}
devFileInfos = append(devFileInfos, entry)
}
return
}
func (d *Device) PushFile(local *os.File, remotePath string, modification ...time.Time) (err error) {
if len(modification) == 0 {
var stat os.FileInfo
if stat, err = local.Stat(); err != nil {
return err
}
modification = []time.Time{stat.ModTime()}
}
return d.Push(local, remotePath, modification[0], DefaultFileMode)
}
func (d *Device) Push(source io.Reader, remotePath string, modification time.Time, mode ...os.FileMode) (err error) {
if len(mode) == 0 {
mode = []os.FileMode{DefaultFileMode}
}
var tp transport
if tp, err = d.createDeviceTransport(); err != nil {
return err
}
defer func() { _ = tp.Close() }()
var sync syncTransport
if sync, err = tp.CreateSyncTransport(); err != nil {
return err
}
defer func() { _ = sync.Close() }()
data := fmt.Sprintf("%s,%d", remotePath, mode[0])
if err = sync.Send("SEND", data); err != nil {
return err
}
if err = sync.SendStream(source); err != nil {
return
}
if err = sync.SendStatus("DONE", uint32(modification.Unix())); err != nil {
return
}
if err = sync.VerifyStatus(); err != nil {
return
}
return
}
func (d *Device) Pull(remotePath string, dest io.Writer) (err error) {
var tp transport
if tp, err = d.createDeviceTransport(); err != nil {
return err
}
defer func() { _ = tp.Close() }()
var sync syncTransport
if sync, err = tp.CreateSyncTransport(); err != nil {
return err
}
defer func() { _ = sync.Close() }()
if err = sync.Send("RECV", remotePath); err != nil {
return err
}
err = sync.WriteStream(dest)
return
}
func (d *Device) installViaABBExec(apk io.ReadSeeker) (raw []byte, err error) {
var (
tp transport
filesize int64
)
filesize, err = apk.Seek(0, io.SeekEnd)
if err != nil {
return nil, err
}
if tp, err = d.createDeviceTransport(); err != nil {
return nil, err
}
defer func() { _ = tp.Close() }()
if err = tp.Send(fmt.Sprintf("abb_exec:package\x00install\x00-t\x00-S\x00%d", filesize)); err != nil {
return nil, err
}
if err = tp.VerifyResponse(); err != nil {
return nil, err
}
_, err = apk.Seek(0, io.SeekStart)
if err != nil {
return nil, err
}
_, err = io.Copy(tp.Conn(), apk)
if err != nil {
return nil, err
}
raw, err = tp.ReadBytesAll()
return
}
func (d *Device) InstallAPK(apk io.ReadSeeker) (string, error) {
haserr := func(ret string) bool {
return strings.Contains(ret, "Failure")
}
if d.HasFeature(FeatAbbExec) {
raw, err := d.installViaABBExec(apk)
if err != nil {
return "", fmt.Errorf("error installing: %v", err)
}
if haserr(string(raw)) {
return "", errors.New(string(raw))
}
return string(raw), err
}
remote := fmt.Sprintf("/data/local/tmp/%s.apk", builtin.GenNameWithTimestamp("gadb_remote_%d"))
err := d.Push(apk, remote, time.Now())
if err != nil {
return "", fmt.Errorf("error pushing: %v", err)
}
res, err := d.RunShellCommand("pm", "install", "-f", remote)
if err != nil {
return "", errors.Wrap(err, "install apk failed")
}
if haserr(res) {
return "", errors.New(res)
}
return res, nil
}
func (d *Device) Uninstall(packageName string, keepData ...bool) (string, error) {
if len(keepData) == 0 {
keepData = []bool{false}
}
packageName = strings.ReplaceAll(packageName, " ", "")
if len(packageName) == 0 {
return "", fmt.Errorf("invalid package name")
}
args := []string{"uninstall"}
if keepData[0] {
args = append(args, "-k")
}
args = append(args, packageName)
return d.RunShellCommandV2("pm", args...)
}
func (d *Device) ScreenCap() ([]byte, error) {
if d.HasFeature(FeatShellV2) {
return d.RunShellCommandV2WithBytes("screencap", "-p")
}
// for shell v1, screenshot buffer maybe truncated
// thus we firstly save it to local file and then pull it
tempPath := fmt.Sprintf("/data/local/tmp/screenshot_%d.png",
time.Now().Unix())
_, err := d.RunShellCommandWithBytes("screencap", "-p", tempPath)
if err != nil {
return nil, err
}
buffer := bytes.NewBuffer(nil)
err = d.Pull(tempPath, buffer)
return buffer.Bytes(), err
}
|
package gcp
import (
"context"
"github.com/pkg/errors"
storage "google.golang.org/api/storage/v1"
)
func (o *ClusterUninstaller) listBucketObjects(ctx context.Context, bucket cloudResource) ([]cloudResource, error) {
o.Logger.Debugf("Listing objects for storage bucket %s", bucket.name)
ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
defer cancel()
result := []cloudResource{}
req := o.storageSvc.Objects.List(bucket.name).Fields("items(name),nextPageToken")
err := req.Pages(ctx, func(objects *storage.Objects) error {
for _, object := range objects.Items {
o.Logger.Debugf("Found storage object %s/%s", bucket.name, object.Name)
result = append(result, cloudResource{
key: object.Name,
name: object.Name,
typeName: "bucketobject",
})
}
return nil
})
if err != nil {
return nil, errors.Wrapf(err, "failed to fetch objects for bucket %s", bucket.name)
}
return result, nil
}
func (o *ClusterUninstaller) deleteBucketObject(ctx context.Context, bucket cloudResource, item cloudResource) error {
o.Logger.Debugf("Deleting storate object %s/%s", bucket.name, item.name)
ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
defer cancel()
err := o.storageSvc.Objects.Delete(bucket.name, item.name).Context(ctx).Do()
if err != nil && !isNoOp(err) {
return errors.Wrapf(err, "failed to delete bucket object %s/%s", bucket.name, item.name)
}
o.deletePendingItems(item.typeName, []cloudResource{item})
o.Logger.Infof("Deleted bucket object %s", item.name)
return nil
}
|
package crypto
import (
amino "github.com/bcbchain/bclib/tendermint/go-amino"
)
var cdc = amino.NewCodec()
func init() {
// NOTE: It's important that there be no conflicts here,
// as that would change the canonical representations,
// and therefore change the address.
// TODO: Add feature to go-amino to ensure that there
// are no conflicts.
RegisterAmino(cdc)
}
func RegisterAmino(cdc *amino.Codec) {
cdc.RegisterInterface((*PubKey)(nil), nil)
cdc.RegisterConcrete(PubKeyEd25519{},
"tendermint/PubKeyEd25519", nil)
cdc.RegisterConcrete(PubKeySecp256k1{},
"tendermint/PubKeySecp256k1", nil)
cdc.RegisterInterface((*PrivKey)(nil), nil)
cdc.RegisterConcrete(PrivKeyEd25519{},
"tendermint/PrivKeyEd25519", nil)
cdc.RegisterConcrete(PrivKeySecp256k1{},
"tendermint/PrivKeySecp256k1", nil)
cdc.RegisterInterface((*Signature)(nil), nil)
cdc.RegisterConcrete(SignatureEd25519{},
"tendermint/SignatureKeyEd25519", nil)
cdc.RegisterConcrete(SignatureSecp256k1{},
"tendermint/SignatureKeySecp256k1", nil)
}
|
package cmd
import (
"github.com/Files-com/files-cli/lib"
"github.com/spf13/cobra"
files_sdk "github.com/Files-com/files-sdk-go"
"fmt"
"os"
group_user "github.com/Files-com/files-sdk-go/groupuser"
)
var (
GroupUsers = &cobra.Command{
Use: "group-users [command]",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {},
}
)
func GroupUsersInit() {
var fieldsList string
paramsGroupUserList := files_sdk.GroupUserListParams{}
var MaxPagesList int
cmdList := &cobra.Command{
Use: "list",
Short: "list",
Long: `list`,
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
params := paramsGroupUserList
params.MaxPages = MaxPagesList
it, err := group_user.List(params)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lib.JsonMarshalIter(it, fieldsList)
},
}
cmdList.Flags().Int64VarP(¶msGroupUserList.UserId, "user-id", "u", 0, "User ID. If provided, will return group_users of this user.")
cmdList.Flags().StringVarP(¶msGroupUserList.Cursor, "cursor", "c", "", "Used for pagination. Send a cursor value to resume an existing list from the point at which you left off. Get a cursor from an existing list via the X-Files-Cursor-Next header.")
cmdList.Flags().IntVarP(¶msGroupUserList.PerPage, "per-page", "p", 0, "Number of records to show per page. (Max: 10,000, 1,000 or less is recommended).")
cmdList.Flags().Int64VarP(¶msGroupUserList.GroupId, "group-id", "g", 0, "Group ID. If provided, will return group_users of this group.")
cmdList.Flags().IntVarP(&MaxPagesList, "max-pages", "m", 1, "When per-page is set max-pages limits the total number of pages requested")
cmdList.Flags().StringVarP(&fieldsList, "fields", "", "", "comma separated list of field names to include in response")
GroupUsers.AddCommand(cmdList)
var fieldsUpdate string
paramsGroupUserUpdate := files_sdk.GroupUserUpdateParams{}
cmdUpdate := &cobra.Command{
Use: "update",
Run: func(cmd *cobra.Command, args []string) {
result, err := group_user.Update(paramsGroupUserUpdate)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lib.JsonMarshal(result, fieldsUpdate)
},
}
cmdUpdate.Flags().Int64VarP(¶msGroupUserUpdate.Id, "id", "i", 0, "Group User ID.")
cmdUpdate.Flags().Int64VarP(¶msGroupUserUpdate.GroupId, "group-id", "g", 0, "Group ID to add user to.")
cmdUpdate.Flags().Int64VarP(¶msGroupUserUpdate.UserId, "user-id", "u", 0, "User ID to add to group.")
cmdUpdate.Flags().StringVarP(&fieldsUpdate, "fields", "", "", "comma separated list of field names")
GroupUsers.AddCommand(cmdUpdate)
var fieldsDelete string
paramsGroupUserDelete := files_sdk.GroupUserDeleteParams{}
cmdDelete := &cobra.Command{
Use: "delete",
Run: func(cmd *cobra.Command, args []string) {
result, err := group_user.Delete(paramsGroupUserDelete)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lib.JsonMarshal(result, fieldsDelete)
},
}
cmdDelete.Flags().Int64VarP(¶msGroupUserDelete.Id, "id", "i", 0, "Group User ID.")
cmdDelete.Flags().Int64VarP(¶msGroupUserDelete.GroupId, "group-id", "g", 0, "Group ID from which to remove user.")
cmdDelete.Flags().Int64VarP(¶msGroupUserDelete.UserId, "user-id", "u", 0, "User ID to remove from group.")
cmdDelete.Flags().StringVarP(&fieldsDelete, "fields", "", "", "comma separated list of field names")
GroupUsers.AddCommand(cmdDelete)
}
|
// Copyright 2021 The Prometheus 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.
//go:build darwin || linux
// +build darwin linux
// Package ecscollector implements a Prometheus collector for Amazon ECS
// metrics available at the ECS metadata server.
package ecscollector
import (
"log"
"github.com/tklauser/go-sysconf"
)
func init() {
tick, err := sysconf.Sysconf(sysconf.SC_CLK_TCK)
if err != nil {
log.Printf("Can't get _SC_CLK_TCK; using 100 instead: %v\n", err)
return
}
log.Printf("sysconf(_SC_CLK_TCK) = %d", tick)
clockTick = tick
}
|
package main
//思路:二叉树递归,同时用快慢指针寻找中点
func sortedListToBST(head *ListNode) *TreeNode {
if head == nil {
return nil
}
return genBST(head, nil)
}
func genBST(head *ListNode, tail *ListNode) *TreeNode {
if head == tail { //递归结束
return nil
}
slow := head
fast := head
for fast != tail && fast.Next != tail {
slow = slow.Next
fast = fast.Next.Next
}
//slow到达中心点
root := &TreeNode{}
root.Val = slow.Val
root.Left = genBST(head, slow)
root.Right = genBST(slow.Next, tail)
return root
}
|
package lua
import (
"time"
lua "github.com/yuin/gopher-lua"
)
func preloadTime(state *lua.LState) int {
mod := state.NewTable()
state.SetFuncs(mod, map[string]lua.LGFunction{
"sleep": timeSleep,
})
state.Push(mod)
return 1
}
func timeSleep(state *lua.LState) int {
ms := state.CheckNumber(1)
time.Sleep(time.Duration(ms) * time.Millisecond)
return 0
}
|
package rsync
import (
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cpusoft/goutil/belogs"
"github.com/cpusoft/goutil/conf"
"github.com/cpusoft/goutil/httpclient"
"github.com/cpusoft/goutil/jsonutil"
"github.com/cpusoft/goutil/osutil"
"github.com/cpusoft/goutil/randutil"
"github.com/cpusoft/goutil/rsyncutil"
model "rpstir2-model"
)
func rsyncByUrl(rsyncModelChan RsyncModelChan) {
defer func() {
belogs.Debug("RsyncByUrl():defer rpQueue.RsyncingParsingCount:", atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
if atomic.LoadInt64(&rpQueue.RsyncingParsingCount) == 0 {
belogs.Debug("RsyncByUrl(): call RsyncParseEndChan{}, RsyncingParsingCount is 0")
rpQueue.RsyncParseEndChan <- RsyncParseEndChan{}
}
}()
// start rsync and check err
// if have error, should set RsyncingParsingCount -1
start := time.Now()
// CurRsyncingCount should +1 and then -1
atomic.AddInt64(&rpQueue.CurRsyncingCount, 1)
belogs.Debug("RsyncByUrl(): before rsync, rsyncModelChan:", rsyncModelChan, " CurRsyncingCount:", atomic.LoadInt64(&rpQueue.CurRsyncingCount))
rsyncutil.SetTimeout(24)
defer rsyncutil.ResetAllTimeout()
rsyncDestPath, _, err := rsyncutil.RsyncQuiet(rsyncModelChan.Url, rsyncModelChan.Dest)
atomic.AddInt64(&rpQueue.CurRsyncingCount, -1)
belogs.Debug("RsyncByUrl(): rsync rsyncModelChan:", rsyncModelChan, " CurRsyncingCount:", atomic.LoadInt64(&rpQueue.CurRsyncingCount),
" rsyncDestPath:", rsyncDestPath)
if err != nil {
rpQueue.RsyncResult.FailUrls.Store(rsyncModelChan.Url, err.Error())
belogs.Error("RsyncByUrl():RsyncQuiet fail, rsyncModelChan.Url:", rsyncModelChan.Url, " err:", err, " time(s):", time.Since(start))
belogs.Debug("RsyncByUrl():RsyncQuiet fail, before RsyncingParsingCount-1:", atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
atomic.AddInt64(&rpQueue.RsyncingParsingCount, -1)
belogs.Debug("RsyncByUrl():RsyncQuiet fail, after RsyncingParsingCount-1:", atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
return
}
belogs.Debug("RsyncByUrl(): rsync.Rsync url:", rsyncModelChan.Url, " rsyncDestPath:", rsyncDestPath)
parseModelChan := ParseModelChan{FilePathName: rsyncDestPath}
belogs.Debug("RsyncByUrl():before parseModelChan:", parseModelChan, " len(rpQueue.ParseModelChan):", len(rpQueue.ParseModelChan))
belogs.Info("RsyncByUrl(): rsync rsyncModelChan:", rsyncModelChan, " CurRsyncingCount:", atomic.LoadInt64(&rpQueue.CurRsyncingCount),
" rsyncDestPath:", rsyncDestPath, " time(s):", time.Since(start))
rpQueue.ParseModelChan <- parseModelChan
}
func parseCerFiles(parseModelChan ParseModelChan) {
defer func() {
belogs.Debug("parseCerFiles():defer rpQueue.RsyncingParsingCount:", atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
if atomic.LoadInt64(&rpQueue.RsyncingParsingCount) == 0 {
belogs.Debug("parseCerFiles(): call RyncParseEndChan{}, RsyncingParsingCount is 0")
rpQueue.RsyncParseEndChan <- RsyncParseEndChan{}
}
}()
belogs.Debug("parseCerFiles(): parseModelChan:", parseModelChan)
// if have erorr, should set RsyncingParsingCount -1
// get all cer files, include subcer
m := make(map[string]string, 0)
m[".cer"] = ".cer"
cerFiles, err := osutil.GetAllFilesBySuffixs(parseModelChan.FilePathName, m)
if err != nil {
belogs.Error("parseCerFiles():GetAllFilesBySuffixs fail, parseModelChan.FilePathName:", parseModelChan.FilePathName, " err:", err)
belogs.Debug("parseCerFiles():GetAllFilesBySuffixs, before RsyncingParsingCount-1:", atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
atomic.AddInt64(&rpQueue.RsyncingParsingCount, -1)
belogs.Debug("parseCerFiles():GetAllFilesBySuffixs, after RsyncingParsingCount-1:", atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
return
}
belogs.Debug("parseCerFiles(): len(cerFiles):", len(cerFiles))
// if there are no cer files, return
if len(cerFiles) == 0 {
belogs.Debug("parseCerFiles():len(cerFiles)==0, before RsyncingParsingCount-1:", atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
atomic.AddInt64(&rpQueue.RsyncingParsingCount, -1)
belogs.Debug("parseCerFiles():len(cerFiles)==0, after RsyncingParsingCount-1:", atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
return
}
// foreach every cerfiles to parseCerAndGetSubCaRepositoryUrl
subCaRepositoryUrls := make([]string, 0, len(cerFiles))
for _, cerFile := range cerFiles {
// just trigger sync ,no need save to db
subCaRepositoryUrl := parseCerAndGetSubCaRepositoryUrl(cerFile)
if len(subCaRepositoryUrl) > 0 {
subCaRepositoryUrls = append(subCaRepositoryUrls, subCaRepositoryUrl)
}
}
var rsyncingParsingCountSub int64
if len(subCaRepositoryUrls) == 0 {
rsyncingParsingCountSub = -1
} else {
rsyncingParsingCountSub = int64(len(subCaRepositoryUrls)) - 1
}
belogs.Info("parseCerFiles():len(cerFiles):", len(cerFiles),
" len(subCaRepositoryUrls):", len(subCaRepositoryUrls),
" rsyncingParsingCountSub:", rsyncingParsingCountSub)
// the father rsyncingparsingcount -1 ,and the children rsyncingparsingcount + len()
belogs.Debug("parseCerFiles():will add subCaRepositoryUrls, before RsyncingParsingCount:",
atomic.LoadInt64(&rpQueue.RsyncingParsingCount), " rsyncingParsingCountSub:", rsyncingParsingCountSub)
atomic.AddInt64(&rpQueue.RsyncingParsingCount, rsyncingParsingCountSub)
belogs.Debug("parseCerFiles():will add subCaRepositoryUrls, after RsyncingParsingCount:",
atomic.LoadInt64(&rpQueue.RsyncingParsingCount), " rsyncingParsingCountSub:", rsyncingParsingCountSub)
// call add notifies to rsyncqueue
if len(subCaRepositoryUrls) > 0 {
addSubCaRepositoryUrlsToRpQueue(subCaRepositoryUrls)
}
}
// call /parsevalidate/parse to parse cert, and save result
func parseCerAndGetSubCaRepositoryUrl(cerFile string) (subCaRepositoryUrl string) {
// call parse, not need to save body to db
start := time.Now()
belogs.Debug("ParseCerAndGetSubCaRepositoryUrl():/parsevalidate/parsefilesimple cerFile:", cerFile)
parseCerSimple := model.ParseCerSimple{}
err := httpclient.PostFileAndUnmarshalResponseModel("http://"+conf.String("rpstir2-rp::serverHost")+":"+conf.String("rpstir2-rp::serverHttpPort")+
"/parsevalidate/parsefilesimple", cerFile, "file", false, &parseCerSimple)
if err != nil {
rpQueue.RsyncResult.FailParseValidateCerts.Store(cerFile, err.Error())
belogs.Error("ParseCerAndGetSubCaRepositoryUrl(): PostFileAndUnmarshalResponseModel fail:", cerFile, " err:", err)
return ""
}
// get the sub repo url in cer, and send it to rpqueue
belogs.Info("ParseCerAndGetSubCaRepositoryUrl(): cerFile:", cerFile, " caRepository:", jsonutil.MarshalJson(parseCerSimple),
" time(s):", time.Since(start))
return parseCerSimple.CaRepository
}
func addSubCaRepositoryUrlsToRpQueue(subCaRepositoryUrls []string) {
rsyncConcurrentCount := conf.Int("rsync::rsyncConcurrentCount")
belogs.Debug("AddSubCaRepositoryUrlsToRpQueue(): len(rpQueue.RsyncModelChan)+len(subCaRepositoryUrls):", len(rpQueue.RsyncModelChan),
" + ", len(subCaRepositoryUrls), " compare rsync::rsyncConcurrentCount ", rsyncConcurrentCount)
for i, subCaRepositoryUrl := range subCaRepositoryUrls {
belogs.Debug("AddSubCaRepositoryUrlsToRpQueue():will PreCheckRsyncUrl, rpQueue.RsyncingParsingCount: ",
atomic.LoadInt64(&rpQueue.RsyncingParsingCount),
" subCaRepositoryUrl:", subCaRepositoryUrl)
if !rpQueue.PreCheckRsyncUrl(subCaRepositoryUrl) {
belogs.Debug("AddSubCaRepositoryUrlsToRpQueue():PreCheckRsyncUrl have exists, before RsyncingParsingCount-1:", subCaRepositoryUrl, atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
atomic.AddInt64(&rpQueue.RsyncingParsingCount, -1)
belogs.Debug("AddSubCaRepositoryUrlsToRpQueue():PreCheckRsyncUrl have exists, after RsyncingParsingCount-1:", subCaRepositoryUrl, atomic.LoadInt64(&rpQueue.RsyncingParsingCount))
continue
}
curRsyncingCount := int(atomic.LoadInt64(&rpQueue.CurRsyncingCount))
if curRsyncingCount <= 2 {
// when less 2, not need to wait
} else if curRsyncingCount > 2 && curRsyncingCount <= rsyncConcurrentCount {
waitForRsyncUrl(1, subCaRepositoryUrl)
} else {
belogs.Debug("AddSubCaRepositoryUrlsToRpQueue():waitForRsyncUrl,i + rpQueue.curRsyncingCount: ", curRsyncingCount)
waitForRsyncUrl(i+curRsyncingCount, subCaRepositoryUrl)
}
belogs.Debug("AddSubCaRepositoryUrlsToRpQueue():will AddRsyncUrl subCaRepositoryUrl: ", subCaRepositoryUrl)
go rpQueue.AddRsyncUrl(subCaRepositoryUrl, conf.VariableString("rsync::destPath")+"/")
}
}
// will try fail urls to rsync again
func tryAgainFailRsyncUrls() bool {
// try again
belogs.Debug("TryAgainFailRsyncUrls():try fail urls again: rpQueue.RsyncResult.FailUrls:", jsonutil.MarshalJson(rpQueue.RsyncResult.FailUrls),
" rpQueue.RsyncResult.FailUrlsTryCount:", rpQueue.RsyncResult.FailUrlsTryCount)
if rpQueue.RsyncResult.FailUrlsTryCount <= uint64(conf.Int("rsync::failRsyncUrlsTryCount")) {
failRsyncUrls := make([]string, 0)
rpQueue.RsyncResult.FailUrls.Range(func(key, v interface{}) bool {
failRsyncUrl := key.(string)
failRsyncUrls = append(failRsyncUrls, failRsyncUrl)
// delete saved url ,so can try again
rpQueue.DelRsyncAddedUrl(failRsyncUrl)
// delete in range, is ok
rpQueue.RsyncResult.FailUrls.Delete(failRsyncUrl)
return true
})
// clear fail rsync urls
rpQueue.RsyncResult.FailUrls = sync.Map{}
belogs.Debug("TryAgainFailRsyncUrls(): failRysncUrl:", len(failRsyncUrls), failRsyncUrls,
" rpQueue.RsyncResult.FailRsyncUrlsTryCount: ", rpQueue.RsyncResult.FailUrlsTryCount)
atomic.AddUint64(&rpQueue.RsyncResult.FailUrlsTryCount, 1)
belogs.Debug("TryAgainFailRsyncUrls():after rpQueue.RsyncResult.FailUrlsTryCount: ", rpQueue.RsyncResult.FailUrlsTryCount)
// check rsync concurrent count, wait some time,
rsyncConcurrentCount := conf.Int("rsync::rsyncConcurrentCount")
atomic.AddInt64(&rpQueue.RsyncingParsingCount, int64(len(failRsyncUrls)))
belogs.Debug("TryAgainFailRsyncUrls(): len(failRsyncUrls):", len(failRsyncUrls),
" failRsyncUrls:", failRsyncUrls)
for i, failRsyncUrl := range failRsyncUrls {
curRsyncingCount := int(atomic.LoadInt64(&rpQueue.CurRsyncingCount))
if curRsyncingCount <= 2 {
} else if curRsyncingCount > 2 && curRsyncingCount <= rsyncConcurrentCount {
belogs.Debug("TryAgainFailRsyncUrls():waitForRsyncUrl, i is smaller, i: ", i,
" , will wait 1:", 1)
waitForRsyncUrl(1, failRsyncUrl)
} else {
belogs.Debug("TryAgainFailRsyncUrls():waitForRsyncUrl, i is bigger, i: ", i,
" , will wait curRsyncingCount+1:", curRsyncingCount+1)
waitForRsyncUrl(1+curRsyncingCount/2, failRsyncUrl)
}
go rpQueue.AddRsyncUrl(failRsyncUrl, conf.VariableString("rsync::destPath")+"/")
}
return true
}
return false
}
//rsync should wait for some url, because some nic limited access frequency
func waitForRsyncUrl(curRsyncCount int, url string) {
if curRsyncCount == 0 {
return
}
belogs.Debug("waitForRsyncUrl(): curRsyncCount : ", curRsyncCount, " will add:", conf.Int("rsync::rsyncDefaultWaitMs"), " 2* runtime.NumCPU():", 2*runtime.NumCPU())
curRsyncCount = curRsyncCount + conf.Int("rsync::rsyncDefaultWaitMs") + 2*runtime.NumCPU()
// apnic and afrinic should not visit too often
if strings.Contains(url, "rpki.apnic.net") {
curRsyncCount = curRsyncCount * 2
} else if strings.Contains(url, "rpki.afrinic.net") {
curRsyncCount = curRsyncCount * 10
}
min := uint(conf.Int("rsync::rsyncPerDelayMs") * curRsyncCount)
randR := uint(conf.Int("rsync::rsyncDelayRandMs"))
rand := randutil.IntRange(min, randR)
belogs.Debug("waitForRsyncUrl():after rand, url is :", url, ", curRsyncCount is:", curRsyncCount, ", will sleep rand ms:", rand)
time.Sleep(time.Duration(rand) * time.Millisecond)
}
|
package client
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"time"
"github.com/Huawei/eSDK_K8S_Plugin/src/utils/log"
)
const (
VOLUME_NAME_NOT_EXIST int64 = 50150005
INITIATOR_NOT_EXIST int64 = 50155103
HOSTNAME_ALREADY_EXIST int64 = 50157019
INITIATOR_ALREADY_EXIST int64 = 50155102
INITIATOR_ADDED_TO_HOST int64 = 50157021
OFF_LINE_CODE = "1077949069"
SNAPSHOT_NOT_EXIST int64 = 50150006
FILE_SYSTEM_NOT_EXIST int64 = 33564678
QUOTA_NOT_EXIST int64 = 37767685
)
var (
LOG_FILTER = map[string]map[string]bool{
"POST": map[string]bool{
"/dsware/service/v1.3/sec/login": true,
"/dsware/service/v1.3/sec/keepAlive": true,
},
"GET": map[string]bool{
"/dsware/service/v1.3/storagePool": true,
},
}
)
func logFilter(method, url string) bool {
filter, exist := LOG_FILTER[method]
return exist && filter[url]
}
type Client struct {
url string
user string
password string
authToken string
client *http.Client
}
func NewClient(url, user, password string) *Client {
return &Client{
url: url,
user: user,
password: password,
}
}
func (cli *Client) DuplicateClient() *Client {
dup := *cli
dup.client = nil
return &dup
}
func (cli *Client) Login() error {
jar, _ := cookiejar.New(nil)
cli.client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Jar: jar,
Timeout: 60 * time.Second,
}
log.Infof("Try to login %s.", cli.url)
data := map[string]interface{}{
"userName": cli.user,
"password": cli.password,
}
respHeader, resp, err := cli.call("POST", "/dsware/service/v1.3/sec/login", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
return fmt.Errorf("Login %s error: %d", cli.url, result)
}
cli.authToken = respHeader["X-Auth-Token"][0]
log.Infof("Login %s success", cli.url)
return nil
}
func (cli *Client) Logout() {
defer func() {
cli.authToken = ""
cli.client = nil
}()
if cli.client == nil {
return
}
resp, err := cli.post("/dsware/service/v1.3/sec/logout", nil)
if err != nil {
log.Warningf("Logout %s error: %v", cli.url, err)
return
}
result := int64(resp["result"].(float64))
if result != 0 {
log.Warningf("Logout %s error: %d", cli.url, result)
return
}
log.Infof("Logout %s success.", cli.url)
}
func (cli *Client) KeepAlive() {
_, err := cli.post("/dsware/service/v1.3/sec/keepAlive", nil)
if err != nil {
log.Warningf("Keep token alive error: %v", err)
}
}
func (cli *Client) doCall(method string, url string, data map[string]interface{}) (http.Header, []byte, error) {
var err error
var reqUrl string
var reqBody io.Reader
var respBody []byte
if data != nil {
reqBytes, err := json.Marshal(data)
if err != nil {
log.Errorf("json.Marshal data %v error: %v", data, err)
return nil, nil, err
}
reqBody = bytes.NewReader(reqBytes)
}
reqUrl = cli.url + url
req, err := http.NewRequest(method, reqUrl, reqBody)
if err != nil {
log.Errorf("Construct http request error: %v", err)
return nil, nil, err
}
req.Header.Set("Referer", cli.url)
req.Header.Set("Content-Type", "application/json")
if cli.authToken != "" {
req.Header.Set("X-Auth-Token", cli.authToken)
}
if !logFilter(method, url) {
log.Infof("Request method: %s, url: %s, body: %v", method, reqUrl, data)
}
resp, err := cli.client.Do(req)
if err != nil {
log.Errorf("Send request method: %s, url: %s, error: %v", method, reqUrl, err)
return nil, nil, errors.New("unconnected")
}
defer resp.Body.Close()
respBody, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("Read response data error: %v", err)
return nil, nil, err
}
if !logFilter(method, url) {
log.Infof("Response method: %s, url: %s, body: %s", method, reqUrl, respBody)
}
return resp.Header, respBody, nil
}
func (cli *Client) call(method string, url string, data map[string]interface{}) (http.Header, map[string]interface{}, error) {
var body map[string]interface{}
respHeader, respBody, err := cli.doCall(method, url, data)
if err != nil {
if err.Error() == "unconnected" {
goto RETRY
}
return nil, nil, err
}
err = json.Unmarshal(respBody, &body)
if err != nil {
log.Errorf("Unmarshal response body %s error: %v", respBody, err)
return nil, nil, err
}
if errorCode, ok := body["errorCode"].(string); ok && errorCode == OFF_LINE_CODE {
log.Warningf("User offline, try to relogin %s", cli.url)
goto RETRY
}
return respHeader, body, nil
RETRY:
err = cli.Login()
if err == nil {
respHeader, respBody, err = cli.doCall(method, url, data)
}
if err != nil {
return nil, nil, err
}
err = json.Unmarshal(respBody, &body)
if err != nil {
log.Errorf("Unmarshal response body %s error: %v", respBody, err)
return nil, nil, err
}
return respHeader, body, nil
}
func (cli *Client) get(url string, data map[string]interface{}) (map[string]interface{}, error) {
_, body, err := cli.call("GET", url, data)
return body, err
}
func (cli *Client) post(url string, data map[string]interface{}) (map[string]interface{}, error) {
_, body, err := cli.call("POST", url, data)
return body, err
}
func (cli *Client) put(url string, data map[string]interface{}) (map[string]interface{}, error) {
_, body, err := cli.call("PUT", url, data)
return body, err
}
func (cli *Client) delete(url string, data map[string]interface{}) (map[string]interface{}, error) {
_, body, err := cli.call("DELETE", url, data)
return body, err
}
func (cli *Client) CreateVolume(params map[string]interface{}) error {
data := map[string]interface{}{
"volName": params["name"].(string),
"volSize": params["capacity"].(int64),
"poolId": params["poolId"].(int64),
}
resp, err := cli.post("/dsware/service/v1.3/volume/create", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(string)
return fmt.Errorf("Create volume %v error: %s", data, errorCode)
}
return nil
}
func (cli *Client) GetVolumeByName(name string) (map[string]interface{}, error) {
url := fmt.Sprintf("/dsware/service/v1.3/volume/queryByName?volName=%s", name)
resp, err := cli.get(url, nil)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(float64)
if int64(errorCode) == VOLUME_NAME_NOT_EXIST {
log.Warningf("Volume of name %s doesn't exist", name)
return nil, nil
}
return nil, fmt.Errorf("Get volume by name %s error: %d", name, int64(errorCode))
}
lun, ok := resp["lunDetailInfo"].(map[string]interface{})
if !ok {
return nil, nil
}
return lun, nil
}
func (cli *Client) DeleteVolume(name string) error {
data := map[string]interface{}{
"volNames": []string{name},
}
resp, err := cli.post("/dsware/service/v1.3/volume/delete", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
details := resp["detail"].([]interface{})
detail := details[0].(map[string]interface{})
errorCode := int64(detail["errorCode"].(float64))
if errorCode == VOLUME_NAME_NOT_EXIST {
log.Warningf("Volume %s doesn't exist while deleting.", name)
return nil
}
return fmt.Errorf("Delete volume %s error: %d", name, errorCode)
}
return nil
}
func (cli *Client) AttachVolume(name, ip string) error {
data := map[string]interface{}{
"volName": []string{name},
"ipList": []string{ip},
}
resp, err := cli.post("/dsware/service/v1.3/volume/attach", data)
if err != nil {
return err
}
result := resp[name].([]interface{})
if len(result) == 0 {
return fmt.Errorf("Attach volume %s to %s error", name, ip)
}
attachResult := result[0].(map[string]interface{})
errorCode := attachResult["errorCode"].(string)
if errorCode != "0" {
return fmt.Errorf("Attach volume %s to %s error: %s", name, ip, errorCode)
}
return nil
}
func (cli *Client) DetachVolume(name, ip string) error {
data := map[string]interface{}{
"volName": []string{name},
"ipList": []string{ip},
}
resp, err := cli.post("/dsware/service/v1.3/volume/detach", data)
if err != nil {
return err
}
result := resp["volumeInfo"].([]interface{})
if len(result) == 0 {
return fmt.Errorf("Detach volume %s from %s error", name, ip)
}
detachResult := result[0].(map[string]interface{})
errorCode := detachResult["errorCode"].(string)
if errorCode != "0" {
return fmt.Errorf("Detach volume %s from %s error: %s", name, ip, errorCode)
}
return nil
}
func (cli *Client) GetPoolByName(poolName string) (map[string]interface{}, error) {
resp, err := cli.get("/dsware/service/v1.3/storagePool", nil)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
return nil, fmt.Errorf("Get all pools error: %d", result)
}
storagePools, exist := resp["storagePools"].([]interface{})
if !exist || len(storagePools) <= 0 {
return nil, nil
}
for _, p := range storagePools {
pool := p.(map[string]interface{})
if pool["poolName"].(string) == poolName {
return pool, nil
}
}
return nil, nil
}
func (cli *Client) GetPoolById(poolId int64) (map[string]interface{}, error) {
url := fmt.Sprintf("/dsware/service/v1.3/storagePool?poolId=%d", poolId)
resp, err := cli.get(url, nil)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
return nil, fmt.Errorf("get pool by id %d error: %d", poolId, result)
}
storagePools, exist := resp["storagePools"].([]interface{})
if !exist || len(storagePools) <= 0 {
return nil, nil
}
for _, p := range storagePools {
pool := p.(map[string]interface{})
if int64(pool["poolId"].(float64)) == poolId {
return pool, nil
}
}
return nil, nil
}
func (cli *Client) GetAllPools() (map[string]interface{}, error) {
resp, err := cli.get("/dsware/service/v1.3/storagePool", nil)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
return nil, fmt.Errorf("Get all pools error: %d", result)
}
storagePools, exist := resp["storagePools"].([]interface{})
if !exist || len(storagePools) <= 0 {
return nil, nil
}
pools := make(map[string]interface{})
for _, p := range storagePools {
pool := p.(map[string]interface{})
name := pool["poolName"].(string)
pools[name] = pool
}
return pools, nil
}
func (cli *Client) CreateSnapshot(snapshotName, volName string) error {
data := map[string]interface{}{
"volName": volName,
"snapshotName": snapshotName,
}
resp, err := cli.post("/dsware/service/v1.3/snapshot/create", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
return fmt.Errorf("Create snapshot %s of volume %s error: %d", snapshotName, volName, result)
}
return nil
}
func (cli *Client) DeleteSnapshot(snapshotName string) error {
data := map[string]interface{}{
"snapshotName": snapshotName,
}
resp, err := cli.post("/dsware/service/v1.3/snapshot/delete", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
return fmt.Errorf("Delete snapshot %s error: %d", snapshotName, result)
}
return nil
}
func (cli *Client) GetSnapshotByName(snapshotName string) (map[string]interface{}, error) {
url := fmt.Sprintf("/dsware/service/v1.3/snapshot/queryByName?snapshotName=%s", snapshotName)
resp, err := cli.get(url, nil)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(float64)
if int64(errorCode) == SNAPSHOT_NOT_EXIST {
log.Warningf("Snapshot of name %s doesn't exist", snapshotName)
return nil, nil
}
return nil, fmt.Errorf("get snapshot by name %s error: %d", snapshotName, result)
}
snapshot, ok := resp["snapshot"].(map[string]interface{})
if !ok {
return nil, nil
}
return snapshot, nil
}
func (cli *Client) CreateVolumeFromSnapshot(volName string, volSize int64, snapshotName string) error {
data := map[string]interface{}{
"volName": volName,
"volSize": volSize,
"src": snapshotName,
}
resp, err := cli.post("/dsware/service/v1.3/snapshot/volume/create", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
return fmt.Errorf("Create volume %s from snapshot %s error: %d", volName, snapshotName, result)
}
return nil
}
func (cli *Client) GetHostByName(hostName string) (map[string]interface{}, error) {
data := map[string]interface{}{
"hostName": hostName,
}
resp, err := cli.get("/dsware/service/iscsi/queryAllHost", data)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
return nil, fmt.Errorf("Get host of name %s error: %d", hostName, result)
}
hostList, exist := resp["hostList"].([]interface{})
if !exist {
log.Infof("Host %s does not exist", hostName)
return nil, nil
}
for _, i := range hostList {
host := i.(map[string]interface{})
if host["hostName"] == hostName {
return host, nil
}
}
return nil, nil
}
func (cli *Client) CreateHost(hostName string, alua map[string]interface{}) error {
data := map[string]interface{}{
"hostName": hostName,
}
if switchoverMode, ok := alua["switchoverMode"]; ok {
data["switchoverMode"] = switchoverMode
}
if pathType, ok := alua["pathType"]; ok {
data["pathType"] = pathType
}
resp, err := cli.post("/dsware/service/iscsi/createHost", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
if !cli.checkErrorCode(resp, HOSTNAME_ALREADY_EXIST) {
return fmt.Errorf("Create host %s error", hostName)
}
}
return nil
}
func (cli *Client) UpdateHost(hostName string, alua map[string]interface{}) error {
data := map[string]interface{}{
"hostName": hostName,
}
if switchoverMode, ok := alua["switchoverMode"]; ok {
data["switchoverMode"] = switchoverMode
}
if pathType, ok := alua["pathType"]; ok {
data["pathType"] = pathType
}
resp, err := cli.post("/dsware/service/iscsi/modifyHost", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
return fmt.Errorf("update host %s by %v error", hostName, data)
}
return nil
}
func (cli *Client) GetInitiatorByName(name string) (map[string]interface{}, error) {
data := map[string]interface{}{
"portName": name,
}
resp, err := cli.post("/dsware/service/iscsi/queryPortInfo", data)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
if !cli.checkErrorCode(resp, INITIATOR_NOT_EXIST) {
return nil, fmt.Errorf("Get initiator %s error", name)
}
log.Infof("Initiator %s does not exist", name)
return nil, nil
}
portList, exist := resp["portList"].([]interface{})
if !exist || len(portList) == 0 {
log.Infof("Initiator %s does not exist", name)
return nil, nil
}
return portList[0].(map[string]interface{}), nil
}
func (cli *Client) QueryHostByPort(port string) (string, error) {
data := map[string]interface{}{
"portName": []string{port},
}
resp, err := cli.post("/dsware/service/iscsi/queryHostByPort", data)
if err != nil {
return "", err
}
result := int64(resp["result"].(float64))
if result != 0 {
if !cli.checkErrorCode(resp, INITIATOR_NOT_EXIST) {
return "", fmt.Errorf("Get host initiator %s belongs error", port)
}
log.Infof("Initiator %s does not belong to any host", port)
return "", nil
}
portHostMap, exist := resp["portHostMap"].(map[string]interface{})
if !exist {
log.Infof("Initiator %s does not belong to any host", port)
return "", nil
}
hosts, exist := portHostMap[port].([]interface{})
if !exist || len(hosts) == 0 {
log.Infof("Initiator %s does not belong to any host", port)
return "", nil
}
return hosts[0].(string), nil
}
func (cli *Client) CreateInitiator(name string) error {
data := map[string]interface{}{
"portName": name,
}
resp, err := cli.post("/dsware/service/iscsi/createPort", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
if !cli.checkErrorCode(resp, INITIATOR_ALREADY_EXIST) {
return fmt.Errorf("Create initiator %s error", name)
}
}
return nil
}
func (cli *Client) AddPortToHost(initiatorName, hostName string) error {
data := map[string]interface{}{
"hostName": hostName,
"portNames": []string{initiatorName},
}
resp, err := cli.post("/dsware/service/iscsi/addPortToHost", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
if !cli.checkErrorCode(resp, INITIATOR_ADDED_TO_HOST) {
return fmt.Errorf("Add initiator %s to host %s error", initiatorName, hostName)
}
}
return nil
}
func (cli *Client) AddLunToHost(lunName, hostName string) error {
data := map[string]interface{}{
"hostName": hostName,
"lunNames": []string{lunName},
}
resp, err := cli.post("/dsware/service/iscsi/addLunsToHost", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
return fmt.Errorf("Add lun %s to host %s error: %d", lunName, hostName, result)
}
return nil
}
func (cli *Client) DeleteLunFromHost(lunName, hostName string) error {
data := map[string]interface{}{
"hostName": hostName,
"lunNames": []string{lunName},
}
resp, err := cli.post("/dsware/service/iscsi/deleteLunFromHost", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
return fmt.Errorf("Delete lun %s from host %s error: %d", lunName, hostName, result)
}
return nil
}
func (cli *Client) QueryIscsiPortal() ([]map[string]interface{}, error) {
data := make(map[string]interface{})
resp, err := cli.post("/dsware/service/cluster/dswareclient/queryIscsiPortal", data)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
return nil, fmt.Errorf("Query iscsi portal error: %d", result)
}
var nodeResultList []map[string]interface{}
respData, exist := resp["nodeResultList"].([]interface{})
if exist {
for _, i := range respData {
nodeResultList = append(nodeResultList, i.(map[string]interface{}))
}
}
return nodeResultList, nil
}
func (cli *Client) QueryHostOfVolume(lunName string) ([]map[string]interface{}, error) {
data := map[string]interface{}{
"lunName": lunName,
}
resp, err := cli.post("/dsware/service/iscsi/queryHostFromVolume", data)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
return nil, fmt.Errorf("Query hosts which lun %s mapped error: %d", lunName, result)
}
var hostList []map[string]interface{}
respData, exist := resp["hostList"].([]interface{})
if exist {
for _, i := range respData {
hostList = append(hostList, i.(map[string]interface{}))
}
}
return hostList, nil
}
func (cli *Client) checkErrorCode(resp map[string]interface{}, errorCode int64) bool {
details, exist := resp["detail"].([]interface{})
if !exist || len(details) == 0 {
return false
}
for _, i := range details {
detail := i.(map[string]interface{})
detailErrorCode := int64(detail["errorCode"].(float64))
if detailErrorCode != errorCode {
return false
}
}
return true
}
func (cli *Client) ExtendVolume(lunName string, newCapacity int64) error {
data := map[string]interface{}{
"volName": lunName,
"newVolSize": newCapacity,
}
resp, err := cli.post("/dsware/service/v1.3/volume/expand", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
return fmt.Errorf("extend volume capacity to %d error: %d", newCapacity, result)
}
return nil
}
func (cli *Client) CreateFileSystem(params map[string]interface{}) (map[string]interface{}, error) {
data := map[string]interface{}{
"name": params["name"].(string),
"storage_pool_id": params["poolId"].(int64),
"enable_compress": false,
"enable_dedup": false,
}
resp, err := cli.post("/api/v2/file_service/file_systems", data)
if err != nil {
return nil, err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Create filesystem %v error: %d", data, errorCode)
log.Errorln(msg)
return nil, errors.New(msg)
}
respData := resp["data"].(map[string]interface{})
if respData != nil {
return respData, nil
}
return nil, fmt.Errorf("failed to create filesystem %v", data)
}
func (cli *Client) DeleteFileSystem(id string) error {
url := fmt.Sprintf("/api/v2/file_service/file_systems/%s", id)
resp, err := cli.delete(url, nil)
if err != nil {
return err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Delete filesystem %v error: %d", id, errorCode)
log.Errorln(msg)
return errors.New(msg)
}
return nil
}
func (cli *Client) GetFileSystemByName(name string) (map[string]interface{}, error) {
url := fmt.Sprintf("/api/v2/file_service/file_systems?name=%s", name)
resp, err := cli.get(url, nil)
if err != nil {
return nil, err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode == FILE_SYSTEM_NOT_EXIST {
return nil, nil
}
if errorCode != 0 {
msg := fmt.Sprintf("Get filesystem %v error: %d", name, errorCode)
log.Errorln(msg)
return nil, errors.New(msg)
}
respData := resp["data"].(map[string]interface{})
if respData != nil {
return respData, nil
}
return nil, nil
}
func (cli *Client) CreateNfsShare(params map[string]interface{}) (map[string]interface{}, error) {
data := map[string]interface{}{
"share_path": params["sharepath"].(string),
"file_system_id": params["fsid"].(string),
"description": params["description"].(string),
}
resp, err := cli.post("/api/v2/nas_protocol/nfs_share", data)
if err != nil {
return nil, err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Create nfs share %v error: %d", data, errorCode)
log.Errorln(msg)
return nil, errors.New(msg)
}
respData := resp["data"].(map[string]interface{})
if respData != nil {
return respData, nil
}
return nil, fmt.Errorf("failed to create NFS share %v", data)
}
func (cli *Client) DeleteNfsShare(id string) error {
url := fmt.Sprintf("/api/v2/nas_protocol/nfs_share?id=%s", id)
resp, err := cli.delete(url, nil)
if err != nil {
return err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Delete NFS share %v error: %d", id, errorCode)
log.Errorln(msg)
return errors.New(msg)
}
return nil
}
func (cli *Client) GetNfsShareByPath(path string) (map[string]interface{}, error) {
url := fmt.Sprintf("/api/v2/nas_protocol/nfs_share_list")
resp, err := cli.get(url, nil)
if err != nil {
return nil, err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Get NFS share path %s error: %d", path, errorCode)
log.Errorln(msg)
return nil, errors.New(msg)
}
respData := resp["data"].([]interface{})
for _, s := range respData {
share := s.(map[string]interface{})
if share["share_path"].(string) == path {
return share, nil
}
}
return nil, nil
}
func (cli *Client) AllowNfsShareAccess(params map[string]interface{}) error {
data := map[string]interface{}{
"access_name": params["name"].(string),
"share_id": params["shareid"].(string),
"access_value": params["accessval"].(int),
"sync": 0,
"all_squash": 1,
"root_squash": 1,
"type": 0,
}
resp, err := cli.post("/api/v2/nas_protocol/nfs_share_auth_client", data)
if err != nil {
return err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Allow nfs share %v access error: %d", data, errorCode)
log.Errorln(msg)
return errors.New(msg)
}
return nil
}
func (cli *Client) DeleteNfsShareAccess(accessID string) error {
url := fmt.Sprintf("/api/v2/nas_protocol/nfs_share_auth_client?id=%s", accessID)
resp, err := cli.delete(url, nil)
if err != nil {
return err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Delete nfs share %v access error: %d", accessID, errorCode)
log.Errorln(msg)
return errors.New(msg)
}
return nil
}
func (cli *Client) GetNfsShareAccess(shareID string) (map[string]interface{}, error) {
url := fmt.Sprintf("/api/v2/nas_protocol/nfs_share_auth_client_list?filter=share_id::%s", shareID)
resp, err := cli.get(url, nil)
if err != nil {
return nil, err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Get nfs share %v access error: %d", shareID, errorCode)
log.Errorln(msg)
return nil, errors.New(msg)
}
respData := resp["data"].(map[string]interface{})
if respData != nil {
return respData, nil
}
return nil, err
}
func (cli *Client) CreateQuota(params map[string]interface{}) error {
resp, err := cli.post("/api/v2/file_service/fs_quota", params)
if err != nil {
return err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
msg := fmt.Sprintf("Failed to create quota %v, error: %d", params, errorCode)
log.Errorln(msg)
return errors.New(msg)
}
return nil
}
func (cli *Client) GetQuotaByFileSystem(fsID string) (map[string]interface{}, error) {
url := "/api/v2/file_service/fs_quota?parent_type=40&parent_id=" + fsID + "&range=%7B%22offset%22%3A0%2C%22limit%22%3A100%7D"
resp, err := cli.get(url, nil)
if err != nil {
return nil, err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
return nil, fmt.Errorf("get quota by filesystem id %s error: %d", fsID, errorCode)
}
fsQuotas, exist := resp["data"].([]interface{})
if !exist || len(fsQuotas) <= 0 {
return nil, nil
}
for _, q := range fsQuotas {
quota := q.(map[string]interface{})
return quota, nil
}
return nil, nil
}
func (cli *Client) DeleteQuota(quotaID string) error {
url := fmt.Sprintf("/api/v2/file_service/fs_quota/%s", quotaID)
resp, err := cli.delete(url, nil)
if err != nil {
return err
}
result := resp["result"].(map[string]interface{})
errorCode := int64(result["code"].(float64))
if errorCode != 0 {
if errorCode == QUOTA_NOT_EXIST {
log.Warningf("Quota %s doesn't exist while deleting.", quotaID)
return nil
}
return fmt.Errorf("delete quota %s error: %d", quotaID, errorCode)
}
return nil
}
func (cli *Client) CreateQoS(qosName string, qosData map[string]int) error {
data := map[string]interface{}{
"qosName": qosName,
"qosSpecInfo": qosData,
}
resp, err := cli.post("/dsware/service/v1.3/qos/create", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(string)
return fmt.Errorf("create QoS %v error: %s", data, errorCode)
}
return nil
}
func (cli *Client) DeleteQoS(qosName string) error {
data := map[string]interface{}{
"qosNames": []string{qosName},
}
resp, err := cli.post("/dsware/service/v1.3/qos/delete", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(string)
return fmt.Errorf("delete QoS %v error: %s", data, errorCode)
}
return nil
}
func (cli *Client) AssociateQoSWithVolume(volName, qosName string) error {
data := map[string]interface{}{
"keyNames": []string{volName},
"qosName": qosName,
}
resp, err := cli.post("/dsware/service/v1.3/qos/volume/associate", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(string)
return fmt.Errorf("associate QoS %s with volume %s error: %s", qosName, volName, errorCode)
}
return nil
}
func (cli *Client) DisassociateQoSWithVolume(volName, qosName string) error {
data := map[string]interface{}{
"keyNames": []string{volName},
"qosName": qosName,
}
resp, err := cli.post("/dsware/service/v1.3/qos/volume/disassociate", data)
if err != nil {
return err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(string)
return fmt.Errorf("disassociate QoS %s with volume %s error: %s", qosName, volName, errorCode)
}
return nil
}
func (cli *Client) GetQoSNameByVolume(volName string) (string, error) {
url := fmt.Sprintf("/dsware/service/v1.3/volume/qos?volName=%s", volName)
resp, err := cli.get(url, nil)
if err != nil {
return "", err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(string)
return "", fmt.Errorf("get qos by volume %s error: %s", volName, errorCode)
}
qosName, exist := resp["qosName"].(string)
if !exist {
return "", nil
}
return qosName, nil
}
func (cli *Client) GetAssociateCountOfQoS(qosName string) (int, error) {
resp, err := cli.get("/dsware/service/v1.3/storagePool", nil)
if err != nil {
return 0, err
}
result := int64(resp["result"].(float64))
if result != 0 {
return 0, fmt.Errorf("get all pools error: %d", result)
}
storagePools, exist := resp["storagePools"].([]interface{})
if !exist || len(storagePools) <= 0 {
return 0, nil
}
associatePools, err := cli.getAssociatePoolOfQoS(qosName)
if err != nil {
log.Errorf("Get associate snapshot of QoS %s error: %v", qosName, err)
return 0, err
}
pools := associatePools["pools"].([]interface{})
storagePoolsCount := len(pools)
for _, p := range storagePools {
pool := p.(map[string]interface{})
poolId := int64(pool["poolId"].(float64))
volumes, err := cli.getAssociateObjOfQoS(qosName, "volume", poolId)
if err != nil {
log.Errorf("Get associate volume of QoS %s error: %v", qosName, err)
return 0, err
}
snapshots, err := cli.getAssociateObjOfQoS(qosName, "snapshot", poolId)
if err != nil {
log.Errorf("Get associate snapshot of QoS %s error: %v", qosName, err)
return 0, err
}
volumeCount := int(volumes["totalNum"].(float64))
snapshotCount := int(snapshots["totalNum"].(float64))
totalCount := volumeCount + snapshotCount + storagePoolsCount
if totalCount != 0 {
return totalCount, nil
}
}
return 0, nil
}
func (cli *Client) getAssociateObjOfQoS(qosName, objType string, poolId int64) (map[string]interface{}, error) {
data := map[string]interface{}{
"qosName": qosName,
"poolId": poolId,
}
resp, err := cli.post("/dsware/service/v1.3/qos/volume/list?type=associated", data)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(string)
return nil, fmt.Errorf("get qos %s associate obj %s error: %s", qosName, objType, errorCode)
}
return resp, nil
}
func (cli *Client) getAssociatePoolOfQoS(qosName string) (map[string]interface{}, error) {
data := map[string]interface{}{
"qosName": qosName,
}
resp, err := cli.post("/dsware/service/v1.3/qos/storagePool/list?type=associated", data)
if err != nil {
return nil, err
}
result := int64(resp["result"].(float64))
if result != 0 {
errorCode, _ := resp["errorCode"].(string)
return nil, fmt.Errorf("get qos %s associate storagePool error: %s", qosName, errorCode)
}
return resp, nil
}
|
package post
import (
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/russross/blackfriday"
)
// Post - Overall posts parsed by parts
type Post struct {
Id int
Title string
PublishedDate string
Summary string
Body string
}
// 1. markdown으로 post 작성후 submit 누르면 (파일 업로드?)
// 2. post 받아와서 string으로 변환
// 3. Post struct 형식에 맞게 파싱
// 4. DB 에 저장
func GetPost(w http.ResponseWriter, r *http.Request) {
// 업로드된 파일 받아오기
err := r.ParseMultipartForm(1024)
if err != nil {
log.Println("Executing function r.ParseMultipartForm() while executing function GetPost() in posts.go...")
log.Fatalln(err)
}
fileHeader := r.MultipartForm.File["post"][0]
file, err := fileHeader.Open()
if err != nil {
log.Println("Executing function fileHeader.Open() while executing function GetPost() in posts.go...")
log.Fatalln(err)
}
// post 받아와서 string으로 변환
data, err := ioutil.ReadAll(file)
if err != nil {
log.Println("Executing function ioutil.ReadAll() while executing function GetPost() in posts.go...")
log.Fatalln(err)
}
post := markdownToPost(data)
err = post.insert()
if err != nil {
log.Println("Executing function post.Insert() while executing GetPost() in posts.go...")
log.Fatalln(err)
}
http.Redirect(w, r, "/", 302)
}
func markdownToPost(data []byte) Post {
rendered := string(blackfriday.MarkdownCommon(data))
result := Post{}
// 제목 찾는 인덱스
startIndex := strings.Index(rendered, "<h1>") + 4
endIndex := strings.Index(rendered, "</h1>")
result.Title = rendered[startIndex:endIndex]
// 요약 찾는 인덱스
startIndex = strings.Index(rendered, "<p>") + 3
endIndex = strings.Index(rendered, "</p>")
result.Summary = rendered[startIndex:endIndex]
startIndex = endIndex
result.Body = rendered[startIndex:]
return result
}
|
// Copyright 2021 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 tests
import (
"context"
"crypto/tls"
"crypto/x509"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"
"github.com/go-sql-driver/mysql"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/config"
tmysql "github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/server"
"github.com/pingcap/tidb/server/internal/testserverclient"
"github.com/pingcap/tidb/server/internal/testutil"
util2 "github.com/pingcap/tidb/server/internal/util"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/testkit"
"github.com/pingcap/tidb/util"
"github.com/stretchr/testify/require"
)
// isTLSExpiredError checks error is caused by TLS expired.
func isTLSExpiredError(err error) bool {
err = errors.Cause(err)
switch inval := err.(type) {
case x509.CertificateInvalidError:
if inval.Reason != x509.Expired {
return false
}
case *tls.CertificateVerificationError:
invalid, ok := inval.Err.(x509.CertificateInvalidError)
if !ok || invalid.Reason != x509.Expired {
return false
}
return true
default:
return false
}
return true
}
// this test will change `kv.TxnTotalSizeLimit` which may affect other test suites,
// so we must make it running in serial.
func TestLoadData1(t *testing.T) {
ts := createTidbTestSuite(t)
ts.RunTestLoadDataWithColumnList(t, ts.server)
ts.RunTestLoadData(t, ts.server)
ts.RunTestLoadDataWithSelectIntoOutfile(t)
ts.RunTestLoadDataForSlowLog(t)
}
func TestConfigDefaultValue(t *testing.T) {
ts := createTidbTestSuite(t)
ts.RunTestsOnNewDB(t, nil, "config", func(dbt *testkit.DBTestKit) {
rows := dbt.MustQuery("select @@tidb_slow_log_threshold;")
ts.CheckRows(t, rows, "300")
})
}
// Fix issue#22540. Change tidb_dml_batch_size,
// then check if load data into table with auto random column works properly.
func TestLoadDataAutoRandom(t *testing.T) {
err := failpoint.Enable("github.com/pingcap/tidb/executor/BeforeCommitWork", "sleep(1000)")
require.NoError(t, err)
defer func() {
//nolint:errcheck
_ = failpoint.Disable("github.com/pingcap/tidb/executor/BeforeCommitWork")
}()
ts := createTidbTestSuite(t)
ts.RunTestLoadDataAutoRandom(t)
}
func TestLoadDataAutoRandomWithSpecialTerm(t *testing.T) {
ts := createTidbTestSuite(t)
ts.RunTestLoadDataAutoRandomWithSpecialTerm(t)
}
func TestExplainFor(t *testing.T) {
ts := createTidbTestSuite(t)
ts.RunTestExplainForConn(t)
}
func TestStmtCount(t *testing.T) {
cfg := util2.NewTestConfig()
cfg.Port = 0
cfg.Status.ReportStatus = true
cfg.Status.StatusPort = 0
cfg.Status.RecordDBLabel = false
cfg.Performance.TCPKeepAlive = true
ts := createTidbTestSuiteWithCfg(t, cfg)
ts.RunTestStmtCount(t)
}
func TestDBStmtCount(t *testing.T) {
ts := createTidbTestSuite(t)
ts.RunTestDBStmtCount(t)
}
func TestLoadDataListPartition(t *testing.T) {
ts := createTidbTestSuite(t)
ts.RunTestLoadDataForListPartition(t)
ts.RunTestLoadDataForListPartition2(t)
ts.RunTestLoadDataForListColumnPartition(t)
ts.RunTestLoadDataForListColumnPartition2(t)
}
func TestInvalidTLS(t *testing.T) {
ts := createTidbTestSuite(t)
cfg := util2.NewTestConfig()
cfg.Port = 0
cfg.Status.StatusPort = 0
cfg.Security = config.Security{
SSLCA: "bogus-ca-cert.pem",
SSLCert: "bogus-server-cert.pem",
SSLKey: "bogus-server-key.pem",
}
_, err := server.NewServer(cfg, ts.tidbdrv)
require.Error(t, err)
}
func TestTLSAuto(t *testing.T) {
ts := createTidbTestSuite(t)
// Start the server without TLS configure, letting the server create these as AutoTLS is enabled
connOverrider := func(config *mysql.Config) {
config.TLSConfig = "skip-verify"
}
cli := testserverclient.NewTestServerClient()
cfg := util2.NewTestConfig()
cfg.Port = cli.Port
cfg.Status.ReportStatus = false
cfg.Security.AutoTLS = true
cfg.Security.RSAKeySize = 528 // Reduces unittest runtime
err := os.MkdirAll(cfg.TempStoragePath, 0700)
require.NoError(t, err)
server, err := server.NewServer(cfg, ts.tidbdrv)
require.NoError(t, err)
server.SetDomain(ts.domain)
cli.Port = testutil.GetPortFromTCPAddr(server.ListenAddr())
go func() {
err := server.Run()
require.NoError(t, err)
}()
time.Sleep(time.Millisecond * 100)
err = cli.RunTestTLSConnection(t, connOverrider) // Relying on automatically created TLS certificates
require.NoError(t, err)
server.Close()
}
func TestTLSBasic(t *testing.T) {
ts := createTidbTestSuite(t)
dir := t.TempDir()
fileName := func(file string) string {
return filepath.Join(dir, file)
}
// Generate valid TLS certificates.
caCert, caKey, err := generateCert(0, "TiDB CA", nil, nil, fileName("ca-key.pem"), fileName("ca-cert.pem"))
require.NoError(t, err)
serverCert, _, err := generateCert(1, "tidb-server", caCert, caKey, fileName("server-key.pem"), fileName("server-cert.pem"))
require.NoError(t, err)
_, _, err = generateCert(2, "SQL Client Certificate", caCert, caKey, fileName("client-key.pem"), fileName("client-cert.pem"))
require.NoError(t, err)
err = registerTLSConfig("client-certificate", fileName("ca-cert.pem"), fileName("client-cert.pem"), fileName("client-key.pem"), "tidb-server", true)
require.NoError(t, err)
// Start the server with TLS but without CA, in this case the server will not verify client's certificate.
connOverrider := func(config *mysql.Config) {
config.TLSConfig = "skip-verify"
}
cli := testserverclient.NewTestServerClient()
cfg := util2.NewTestConfig()
cfg.Port = cli.Port
cfg.Status.ReportStatus = false
cfg.Security = config.Security{
SSLCert: fileName("server-cert.pem"),
SSLKey: fileName("server-key.pem"),
}
server, err := server.NewServer(cfg, ts.tidbdrv)
require.NoError(t, err)
server.SetDomain(ts.domain)
cli.Port = testutil.GetPortFromTCPAddr(server.ListenAddr())
go func() {
err := server.Run()
require.NoError(t, err)
}()
time.Sleep(time.Millisecond * 100)
err = cli.RunTestTLSConnection(t, connOverrider) // We should establish connection successfully.
require.NoError(t, err)
cli.RunTestRegression(t, connOverrider, "TLSRegression")
// Perform server verification.
connOverrider = func(config *mysql.Config) {
config.TLSConfig = "client-certificate"
}
err = cli.RunTestTLSConnection(t, connOverrider) // We should establish connection successfully.
require.NoError(t, err, "%v", errors.ErrorStack(err))
cli.RunTestRegression(t, connOverrider, "TLSRegression")
// Test SSL/TLS session vars
var v *variable.SessionVars
stats, err := server.Stats(v)
require.NoError(t, err)
_, hasKey := stats["Ssl_server_not_after"]
require.True(t, hasKey)
_, hasKey = stats["Ssl_server_not_before"]
require.True(t, hasKey)
require.Equal(t, serverCert.NotAfter.Format("Jan _2 15:04:05 2006 MST"), stats["Ssl_server_not_after"])
require.Equal(t, serverCert.NotBefore.Format("Jan _2 15:04:05 2006 MST"), stats["Ssl_server_not_before"])
server.Close()
}
func TestTLSVerify(t *testing.T) {
ts := createTidbTestSuite(t)
dir := t.TempDir()
fileName := func(file string) string {
return filepath.Join(dir, file)
}
// Generate valid TLS certificates.
caCert, caKey, err := generateCert(0, "TiDB CA", nil, nil, fileName("ca-key.pem"), fileName("ca-cert.pem"))
require.NoError(t, err)
_, _, err = generateCert(1, "tidb-server", caCert, caKey, fileName("server-key.pem"), fileName("server-cert.pem"))
require.NoError(t, err)
_, _, err = generateCert(2, "SQL Client Certificate", caCert, caKey, fileName("client-key.pem"), fileName("client-cert.pem"))
require.NoError(t, err)
err = registerTLSConfig("client-certificate", fileName("ca-cert.pem"), fileName("client-cert.pem"), fileName("client-key.pem"), "tidb-server", true)
require.NoError(t, err)
// Start the server with TLS & CA, if the client presents its certificate, the certificate will be verified.
cli := testserverclient.NewTestServerClient()
cfg := util2.NewTestConfig()
cfg.Port = cli.Port
cfg.Socket = dir + "/tidbtest.sock"
cfg.Status.ReportStatus = false
cfg.Security = config.Security{
SSLCA: fileName("ca-cert.pem"),
SSLCert: fileName("server-cert.pem"),
SSLKey: fileName("server-key.pem"),
}
server, err := server.NewServer(cfg, ts.tidbdrv)
require.NoError(t, err)
server.SetDomain(ts.domain)
defer server.Close()
cli.Port = testutil.GetPortFromTCPAddr(server.ListenAddr())
go func() {
err := server.Run()
require.NoError(t, err)
}()
time.Sleep(time.Millisecond * 100)
// The client does not provide a certificate, the connection should succeed.
err = cli.RunTestTLSConnection(t, nil)
require.NoError(t, err)
connOverrider := func(config *mysql.Config) {
config.TLSConfig = "client-certificate"
}
cli.RunTestRegression(t, connOverrider, "TLSRegression")
// The client provides a valid certificate.
connOverrider = func(config *mysql.Config) {
config.TLSConfig = "client-certificate"
}
err = cli.RunTestTLSConnection(t, connOverrider)
require.NoError(t, err)
cli.RunTestRegression(t, connOverrider, "TLSRegression")
require.False(t, isTLSExpiredError(errors.New("unknown test")))
require.False(t, isTLSExpiredError(x509.CertificateInvalidError{Reason: x509.CANotAuthorizedForThisName}))
require.True(t, isTLSExpiredError(x509.CertificateInvalidError{Reason: x509.Expired}))
_, _, err = util.LoadTLSCertificates("", "wrong key", "wrong cert", true, 528)
require.Error(t, err)
_, _, err = util.LoadTLSCertificates("wrong ca", fileName("server-key.pem"), fileName("server-cert.pem"), true, 528)
require.Error(t, err)
// Test connecting with a client that does not have TLS configured.
// It can still connect, but it should not be able to change "require_secure_transport" to "ON"
// because that is a lock-out risk.
err = cli.RunTestEnableSecureTransport(t, nil)
require.ErrorContains(t, err, "require_secure_transport can only be set to ON if the connection issuing the change is secure")
// Success: when using a secure connection, the value of "require_secure_transport" can change to "ON"
err = cli.RunTestEnableSecureTransport(t, connOverrider)
require.NoError(t, err)
// This connection will now fail since the client is not configured to use TLS.
err = cli.RunTestTLSConnection(t, nil)
require.ErrorContains(t, err, "Connections using insecure transport are prohibited while --require_secure_transport=ON")
// However, this connection is successful
err = cli.RunTestTLSConnection(t, connOverrider)
require.NoError(t, err)
// Test socketFile does not require TLS enabled in require-secure-transport.
// Since this restriction should only apply to TCP connections.
err = cli.RunTestTLSConnection(t, func(config *mysql.Config) {
config.User = "root"
config.Net = "unix"
config.Addr = cfg.Socket
config.DBName = "test"
})
require.NoError(t, err)
}
func TestErrorNoRollback(t *testing.T) {
ts := createTidbTestSuite(t)
// Generate valid TLS certificates.
caCert, caKey, err := generateCert(0, "TiDB CA", nil, nil, "/tmp/ca-key-rollback.pem", "/tmp/ca-cert-rollback.pem")
require.NoError(t, err)
_, _, err = generateCert(1, "tidb-server", caCert, caKey, "/tmp/server-key-rollback.pem", "/tmp/server-cert-rollback.pem")
require.NoError(t, err)
_, _, err = generateCert(2, "SQL Client Certificate", caCert, caKey, "/tmp/client-key-rollback.pem", "/tmp/client-cert-rollback.pem")
require.NoError(t, err)
err = registerTLSConfig("client-cert-rollback-test", "/tmp/ca-cert-rollback.pem", "/tmp/client-cert-rollback.pem", "/tmp/client-key-rollback.pem", "tidb-server", true)
require.NoError(t, err)
defer func() {
os.Remove("/tmp/ca-key-rollback.pem")
os.Remove("/tmp/ca-cert-rollback.pem")
os.Remove("/tmp/server-key-rollback.pem")
os.Remove("/tmp/server-cert-rollback.pem")
os.Remove("/tmp/client-key-rollback.pem")
os.Remove("/tmp/client-cert-rollback.pem")
}()
cli := testserverclient.NewTestServerClient()
cfg := util2.NewTestConfig()
cfg.Port = cli.Port
cfg.Status.ReportStatus = false
cfg.Security = config.Security{
SSLCA: "wrong path",
SSLCert: "wrong path",
SSLKey: "wrong path",
}
_, err = server.NewServer(cfg, ts.tidbdrv)
require.Error(t, err)
// test reload tls fail with/without "error no rollback option"
cfg.Security = config.Security{
SSLCA: "/tmp/ca-cert-rollback.pem",
SSLCert: "/tmp/server-cert-rollback.pem",
SSLKey: "/tmp/server-key-rollback.pem",
}
server, err := server.NewServer(cfg, ts.tidbdrv)
require.NoError(t, err)
server.SetDomain(ts.domain)
cli.Port = testutil.GetPortFromTCPAddr(server.ListenAddr())
go func() {
err := server.Run()
require.NoError(t, err)
}()
defer server.Close()
time.Sleep(time.Millisecond * 100)
connOverrider := func(config *mysql.Config) {
config.TLSConfig = "client-cert-rollback-test"
}
err = cli.RunTestTLSConnection(t, connOverrider)
require.NoError(t, err)
os.Remove("/tmp/server-key-rollback.pem")
err = cli.RunReloadTLS(t, connOverrider, false)
require.Error(t, err)
tlsCfg := server.GetTLSConfig()
require.NotNil(t, tlsCfg)
err = cli.RunReloadTLS(t, connOverrider, true)
require.NoError(t, err)
tlsCfg = server.GetTLSConfig()
require.Nil(t, tlsCfg)
}
func TestPrepareCount(t *testing.T) {
ts := createTidbTestSuite(t)
qctx, err := ts.tidbdrv.OpenCtx(uint64(0), 0, uint8(tmysql.DefaultCollationID), "test", nil, nil)
require.NoError(t, err)
prepareCnt := atomic.LoadInt64(&variable.PreparedStmtCount)
ctx := context.Background()
_, err = Execute(ctx, qctx, "use test;")
require.NoError(t, err)
_, err = Execute(ctx, qctx, "drop table if exists t1")
require.NoError(t, err)
_, err = Execute(ctx, qctx, "create table t1 (id int)")
require.NoError(t, err)
stmt, _, _, err := qctx.Prepare("insert into t1 values (?)")
require.NoError(t, err)
require.Equal(t, prepareCnt+1, atomic.LoadInt64(&variable.PreparedStmtCount))
require.NoError(t, err)
err = qctx.GetStatement(stmt.ID()).Close()
require.NoError(t, err)
require.Equal(t, prepareCnt, atomic.LoadInt64(&variable.PreparedStmtCount))
require.NoError(t, qctx.Close())
}
func TestPrepareExecute(t *testing.T) {
ts := createTidbTestSuite(t)
qctx, err := ts.tidbdrv.OpenCtx(uint64(0), 0, uint8(tmysql.DefaultCollationID), "test", nil, nil)
require.NoError(t, err)
ctx := context.Background()
_, err = qctx.Execute(ctx, "use test")
require.NoError(t, err)
_, err = qctx.Execute(ctx, "create table t1(id int primary key, v int)")
require.NoError(t, err)
_, err = qctx.Execute(ctx, "insert into t1 values(1, 100)")
require.NoError(t, err)
stmt, _, _, err := qctx.Prepare("select * from t1 where id=1")
require.NoError(t, err)
rs, err := stmt.Execute(ctx, nil)
require.NoError(t, err)
req := rs.NewChunk(nil)
require.NoError(t, rs.Next(ctx, req))
require.Equal(t, 2, req.NumCols())
require.Equal(t, req.NumCols(), len(rs.Columns()))
require.Equal(t, 1, req.NumRows())
require.Equal(t, int64(1), req.GetRow(0).GetInt64(0))
require.Equal(t, int64(100), req.GetRow(0).GetInt64(1))
// issue #33509
_, err = qctx.Execute(ctx, "alter table t1 drop column v")
require.NoError(t, err)
rs, err = stmt.Execute(ctx, nil)
require.NoError(t, err)
req = rs.NewChunk(nil)
require.NoError(t, rs.Next(ctx, req))
require.Equal(t, 1, req.NumCols())
require.Equal(t, req.NumCols(), len(rs.Columns()))
require.Equal(t, 1, req.NumRows())
require.Equal(t, int64(1), req.GetRow(0).GetInt64(0))
}
func TestDefaultCharacterAndCollation(t *testing.T) {
ts := createTidbTestSuite(t)
// issue #21194
// 255 is the collation id of mysql client 8 default collation_connection
qctx, err := ts.tidbdrv.OpenCtx(uint64(0), 0, uint8(255), "test", nil, nil)
require.NoError(t, err)
testCase := []struct {
variable string
except string
}{
{"collation_connection", "utf8mb4_0900_ai_ci"},
{"character_set_connection", "utf8mb4"},
{"character_set_client", "utf8mb4"},
}
for _, tc := range testCase {
sVars, b := qctx.GetSessionVars().GetSystemVar(tc.variable)
require.True(t, b)
require.Equal(t, tc.except, sVars)
}
}
func TestReloadTLS(t *testing.T) {
ts := createTidbTestSuite(t)
// Generate valid TLS certificates.
caCert, caKey, err := generateCert(0, "TiDB CA", nil, nil, "/tmp/ca-key-reload.pem", "/tmp/ca-cert-reload.pem")
require.NoError(t, err)
_, _, err = generateCert(1, "tidb-server", caCert, caKey, "/tmp/server-key-reload.pem", "/tmp/server-cert-reload.pem")
require.NoError(t, err)
_, _, err = generateCert(2, "SQL Client Certificate", caCert, caKey, "/tmp/client-key-reload.pem", "/tmp/client-cert-reload.pem")
require.NoError(t, err)
err = registerTLSConfig("client-certificate-reload", "/tmp/ca-cert-reload.pem", "/tmp/client-cert-reload.pem", "/tmp/client-key-reload.pem", "tidb-server", true)
require.NoError(t, err)
defer func() {
os.Remove("/tmp/ca-key-reload.pem")
os.Remove("/tmp/ca-cert-reload.pem")
os.Remove("/tmp/server-key-reload.pem")
os.Remove("/tmp/server-cert-reload.pem")
os.Remove("/tmp/client-key-reload.pem")
os.Remove("/tmp/client-cert-reload.pem")
}()
// try old cert used in startup configuration.
cli := testserverclient.NewTestServerClient()
cfg := util2.NewTestConfig()
cfg.Port = cli.Port
cfg.Status.ReportStatus = false
cfg.Security = config.Security{
SSLCA: "/tmp/ca-cert-reload.pem",
SSLCert: "/tmp/server-cert-reload.pem",
SSLKey: "/tmp/server-key-reload.pem",
}
server, err := server.NewServer(cfg, ts.tidbdrv)
require.NoError(t, err)
server.SetDomain(ts.domain)
cli.Port = testutil.GetPortFromTCPAddr(server.ListenAddr())
go func() {
err := server.Run()
require.NoError(t, err)
}()
time.Sleep(time.Millisecond * 100)
// The client provides a valid certificate.
connOverrider := func(config *mysql.Config) {
config.TLSConfig = "client-certificate-reload"
}
err = cli.RunTestTLSConnection(t, connOverrider)
require.NoError(t, err)
// try reload a valid cert.
tlsCfg := server.GetTLSConfig()
cert, err := x509.ParseCertificate(tlsCfg.Certificates[0].Certificate[0])
require.NoError(t, err)
oldExpireTime := cert.NotAfter
_, _, err = generateCert(1, "tidb-server", caCert, caKey, "/tmp/server-key-reload2.pem", "/tmp/server-cert-reload2.pem", func(c *x509.Certificate) {
c.NotBefore = time.Now().Add(-24 * time.Hour).UTC()
c.NotAfter = time.Now().Add(1 * time.Hour).UTC()
})
require.NoError(t, err)
err = os.Rename("/tmp/server-key-reload2.pem", "/tmp/server-key-reload.pem")
require.NoError(t, err)
err = os.Rename("/tmp/server-cert-reload2.pem", "/tmp/server-cert-reload.pem")
require.NoError(t, err)
connOverrider = func(config *mysql.Config) {
config.TLSConfig = "skip-verify"
}
err = cli.RunReloadTLS(t, connOverrider, false)
require.NoError(t, err)
connOverrider = func(config *mysql.Config) {
config.TLSConfig = "client-certificate-reload"
}
err = cli.RunTestTLSConnection(t, connOverrider)
require.NoError(t, err)
tlsCfg = server.GetTLSConfig()
cert, err = x509.ParseCertificate(tlsCfg.Certificates[0].Certificate[0])
require.NoError(t, err)
newExpireTime := cert.NotAfter
require.True(t, newExpireTime.After(oldExpireTime))
// try reload a expired cert.
_, _, err = generateCert(1, "tidb-server", caCert, caKey, "/tmp/server-key-reload3.pem", "/tmp/server-cert-reload3.pem", func(c *x509.Certificate) {
c.NotBefore = time.Now().Add(-24 * time.Hour).UTC()
c.NotAfter = c.NotBefore.Add(1 * time.Hour).UTC()
})
require.NoError(t, err)
err = os.Rename("/tmp/server-key-reload3.pem", "/tmp/server-key-reload.pem")
require.NoError(t, err)
err = os.Rename("/tmp/server-cert-reload3.pem", "/tmp/server-cert-reload.pem")
require.NoError(t, err)
connOverrider = func(config *mysql.Config) {
config.TLSConfig = "skip-verify"
}
err = cli.RunReloadTLS(t, connOverrider, false)
require.NoError(t, err)
connOverrider = func(config *mysql.Config) {
config.TLSConfig = "client-certificate-reload"
}
err = cli.RunTestTLSConnection(t, connOverrider)
require.NotNil(t, err)
require.Truef(t, isTLSExpiredError(err), "real error is %+v", err)
server.Close()
}
|
package main
import (
"fmt"
"log"
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
// "github.com/kataras/iris"
// "net/http"
"encoding/json"
_"github.com/go-sql-driver/mysql"
"database/sql"
"reflect"
"strconv"
"strings"
// "net/http"
)
// User bind struct
// type User struct {
// Firstname string `json:"firstname"`
// Lastname string `json:"lastname"`
// Age int `json:"age"`
// }
// func Get(ctx *iris.Context) {
// peter := User{
// Firstname: "John",
// Lastname: "Doe",
// Age: 25,
// }
// ctx.JSON(iris.StatusOK, peter)
// }
type Error struct {
Status int16 `json:"status"`
Message string `json:"message"`
}
func Products(ctx *iris.Context) {
fmt.Println("1 Starting connection")
// db, err := sql.Open("mysql", "<username>:<password>@tcp(127.0.0.1:<port>)/<dbname>" )
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")
rows, err := db.Query("select id, title, image, price, stock_status, target_url, merchant from products")
if err != nil {
log.Fatal(err)
}
type Product struct {
Id int `json:"id"`
Title string `json:"title"`
Image string `json:"image"`
Price float64 `json:"price"`
StockStatus string `json:"stock_status"`
TargetUrl string `json:"target_url"`
Merchant string `json:"merchant"`
}
var products []Product
for rows.Next() {
var id int
var title, image, stoctkStatus, tagetUrl, merchant string
var price float64
rows.Scan(&id , &title, &image, &price, &stoctkStatus, &tagetUrl, &merchant)
products = append(products, Product{id , title, image, price, stoctkStatus, tagetUrl, merchant})
}
// productsBytes, _ := json.Marshal(&products)
// w.Write(productsBytes)
fmt.Println("Returning JSON representation of all products")
ctx.JSON(iris.StatusOK, products)
db.Close()
}
func Product(ctx *iris.Context) {
fmt.Println("2 Starting connection")
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")
if err != nil {
log.Fatal(err)
}
id := ctx.Param("id")
rows, err := db.Query("select id, title, image, price, stock_status, target_url, merchant from products where id="+id)
if err != nil {
log.Fatal(err)
}else{
fmt.Println("Query succesfully excuted while fetching single product")
}
type Product struct {
Id int `json:"id"`
Title string `json:"title"`
Image string `json:"image"`
Price float64 `json:"price"`
StockStatus string `json:"stock_status"`
TargetUrl string `json:"target_url"`
Merchant string `json:"merchant"`
}
var product Product
found := false
for rows.Next() {
var id int
var title, image, stoctkStatus, tagetUrl, merchant string
var price float64
fmt.Println("Scanning")
rows.Scan(&id , &title, &image, &price, &stoctkStatus, &tagetUrl, &merchant)
product = Product{id , title, image, price, stoctkStatus, tagetUrl, merchant}
found = true
}
// productsBytes, _ := json.Marshal(&products)
// w.Write(productsBytes)
fmt.Println(found)
if found==true {
fmt.Println("Returning JSON representation of a product")
ctx.JSON(iris.StatusOK, product)
} else {
fmt.Println("Returning JSON representation of a product")
ctx.JSON(iris.StatusBadRequest, Error{400, "product with this id does not exist"})
}
db.Close()
}
func CreateProduct(ctx *iris.Context) {
fmt.Println("3 Starting connection")
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")
if err != nil {
log.Fatal(err, "H")
}
forms := ctx.FormValues()
title := ctx.FormValue("title")
image := ctx.FormValue("image")
price := ctx.FormValue("price")
stockStatus := ctx.FormValue("stock_status")
tagetUrl := ctx.FormValue("target_url")
merchant := ctx.FormValue("merchant")
// merchant := forms["merchant"][0]
fmt.Println("================")
for key, value := range forms {
// fmt.Println("key:", key, len(key),", value: ", value)
if strings.TrimSpace(key) == "merchant" {
// fmt.Println ("Fetching .....")
// fmt.Println(reflect.TypeOf(value))
merchant = value[0]
}
}
fmt.Println(".....", forms["merchant"])
fmt.Println()
fmt.Println("================")
fmt.Println("Got", title, image, price, stockStatus)
fmt.Println("Target: ", tagetUrl, "Merchant: ",merchant)
query := "INSERT INTO products(title, image, price, stock_status, target_url, merchant) values('"+
title +"', '"+image+"', "+price+", "+stockStatus+", '"+tagetUrl+"', '"+merchant+"')"
fmt.Println("Executing ", query)
stmt, err := db.Prepare(query)
if err != nil {
ctx.JSON(iris.StatusInternalServerError, map[string]interface{}{"message": "error while processing INSERT query, all the fields are required","required_fields": "title, image, price, stock_status, target_url" ,"status": 500})
return
}
_, err = stmt.Exec()
if err != nil {
log.Fatal(err)
} else {
ctx.JSON(iris.StatusOK, map[string]interface{}{"message": "product successfully created", "status": 200})
fmt.Println("Query succesfully excuted while INSERTING record of single product")
}
db.Close()
}
func UpdateProduct(ctx *iris.Context) {
fmt.Println("4 Starting connection")
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")
// fmt.Println(ctx.PathString())
if err != nil {
log.Fatal(err, "Error while updating product")
}
id := ctx.FormValue("id")
title := ctx.FormValue("title")
image := ctx.FormValue("image")
price := ctx.FormValue("price")
stockStatus := ctx.FormValue("stock_status")
tagetUrl := ctx.FormValue("target_url")
merchant := ctx.FormValue("merchant")
fmt.Println(id, reflect.TypeOf(id), len(id))
if id == "" {
fmt.Println("Blank id")
ctx.JSON(iris.StatusBadRequest, map[string]interface{}{"message": "id is required", "status": 400})
return
} else {
_, err = strconv.Atoi(id)
fmt.Println("Worng id")
if err != nil {
ctx.JSON(iris.StatusBadRequest, map[string]interface{}{"message": "id should be a number", "status": 400})
return
}
}
fields := []string{"title", "image", "price", "stock_status", "target_url", "merchant"}
fieldsValue := []string{title, image, price, stockStatus, tagetUrl, merchant}
fmt.Println("Got", title, image, price, stockStatus, tagetUrl, merchant)
// query := "INSERT INTO products(title, image, price, stock_status, target_url) values('"+
// title +"', '"+image+"', "+price+", "+stockStatus+", '"+tagetUrl+"')"
query := "UPDATE products set "
for index,v := range fields {
fmt.Println(index, v)
if v != "" {
query += fields[index] +"="
if fields[index] == "price" || fields[index] == "stock_status" {
query += fieldsValue[index] + ","
} else {
query += "'"+fieldsValue[index] + "',"
}
}
}
fmt.Println(query)
fmt.Println(reflect.TypeOf(query))
fmt.Println(query[:len(query)-1])
query = query[:len(query)-1]
query += " where id="+id
fmt.Println("Executing ", query)
// fmt.Println("Executing ", query)
stmt, err := db.Prepare(query)
if err != nil {
ctx.JSON(iris.StatusInternalServerError, map[string]interface{}{"message": "error while processing UPDATE query", "status": 500})
return
}
_, err = stmt.Exec()
if err != nil {
log.Fatal(err)
} else {
ctx.JSON(iris.StatusOK, map[string]interface{}{"message": "product successfully updated", "status": 200})
fmt.Println("Query succesfully executed while UPDATING record of single product")
}
db.Close()
}
// func CreateProductUi(ctx *iris.Context) {
// ctx.SetContentType("text/html")
// fmt.Println("Rendering page")
// ctx.Render("create_product.html", struct{Name string}{Name: "Rishikesh"})
// }
func Login(ctx *iris.Context) {
fmt.Println("4 Starting connection")
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")
if err != nil {
fmt.Println("Check DB connection")
}
email := ctx.FormValue("email")
password := ctx.FormValue("password")
// fmt.Println("URL => ",ctx.URLParam("email"))
// myMap := ctx.FormValues()
// var keyStrMap string
// for k,_ := range myMap {
// keyStrMap = k
// break
// }
// type AuthData struct{
// Email string `json:"email"`
// Password string `json:"password"`
// }
// keyMap := AuthData{}
// err = json.Unmarshal([]byte(keyStrMap), &keyMap)
// fmt.Println(keyMap, reflect.TypeOf(keyMap))
// email := keyMap.Email
// password := keyMap.Password
if email == "" || password == "" {
fmt.Println("Email & Password(OR)")
fmt.Println("Email & Password(AND)")
myMap := ctx.FormValues()
var keyStrMap string
for k,_ := range myMap {
keyStrMap = k
break
}
type AuthData struct{
Email string `json:"email"`
Password string `json:"password"`
}
keyMap := AuthData{}
err = json.Unmarshal([]byte(keyStrMap), &keyMap)
fmt.Println(keyMap, reflect.TypeOf(keyMap))
email = keyMap.Email
password = keyMap.Password
if email == "" || password == "" {
fmt.Println("Blank email or password")
ctx.JSON(iris.StatusBadRequest, map[string]interface{}{"message": "email & password are required fields", "status": 400})
return
}
}
fmt.Println("Got", email, " & ", password)
var fetchedId int
var fetchedEmail, fetchedPassword, fetchedFirstname, fetchedLastname string
rows, err := db.Query("Select id, email, password, fname, lname from users where email='"+email+"' AND password='"+password+"';")
if err != nil {
log.Fatal(err)
ctx.JSON(iris.StatusInternalServerError, map[string]interface{}{"message": "error while processing SELECT(login) query", "status": 500})
return
}
found := false
for rows.Next(){
rows.Scan(&fetchedId, &fetchedEmail, &fetchedPassword, &fetchedFirstname, &fetchedLastname)
found = true
}
if !found {
ctx.JSON(iris.StatusUnauthorized, map[string]interface{}{"message": "email or password is incorrect", "status": 401})
return
}
ctx.JSON(iris.StatusOK, map[string]interface{}{"message": "user found", "id": fetchedId, "email": fetchedEmail, "fullname": fetchedFirstname+" "+fetchedLastname, "status": 200})
fmt.Println("Query succesfully executed while UPDATING record of single user")
db.Close()
}
func Users(ctx *iris.Context) {
// db, err := sql.Open("mysql", "<username>:<password>@tcp(127.0.0.1:<port>)/<dbname>" )
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")
// w.Header().Set("Content-Type", "application/json")
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("select id, fname, lname, uname, email, contact, profile_pic from users")
if err != nil {
log.Fatal(err)
}
type User struct {
Id int `json:"id"`
Fname string `json:"firstname"`
Lname string `json:"lastname"`
Uname string `json:"username"`
Email string `json:"email"`
Contact int `json:"contact"`
ProfilePic string `json:"profile_pic"`
}
var users []User
for rows.Next() {
var id, contact int
var fname string
var lname string
var uname, email, profile_pic string
rows.Scan(&id ,&fname, &lname, &uname, &email, &contact, &profile_pic)
users = append(users, User{id, fname, lname, uname, email, contact, profile_pic })
}
// usersBytes, _ := json.Marshal(&users)
ctx.JSON(iris.StatusOK, users)
db.Close()
}
func User(ctx *iris.Context) {
fmt.Println("Starting connection")
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")
if err != nil {
log.Fatal(err)
}
id := ctx.Param("id")
_, err = strconv.Atoi(id)
if err != nil {
ctx.JSON(iris.StatusOK, map[string]interface{}{"message": "id should be an integer", "status": 400})
return
}
rows, err := db.Query("select id, fname, lname, uname, email, contact, profile_pic from users where id="+id)
if err != nil {
ctx.JSON(iris.StatusInternalServerError, map[string]interface{}{"message": "Error while query execution", "status": 500})
return
}else{
fmt.Println("Query succesfully excuted while fetching single user")
}
type User struct {
Id int `json:"id"`
Fname string `json:"fname"`
Lname string `json:"lname"`
Uname string `json:"uname"`
Email string `json:"email"`
Contact int `json:"contact"`
ProfilePic string `json:"profile_pic"`
}
var user User
found := false
for rows.Next() {
var id, contact int
var fname, lname, uname, email, profile_pic string
fmt.Println("Scanning")
rows.Scan(&id, &fname, &lname, &uname, &email, &contact, &profile_pic)
if profile_pic == "" {
profile_pic = "https://cdn2.iconfinder.com/data/icons/circle-icons-1/64/profle-512.png"
}
user = User{id , fname, lname, uname, email, contact, profile_pic}
found = true
}
// productsBytes, _ := json.Marshal(&products)
// w.Write(productsBytes)
fmt.Println(found)
if found==true {
fmt.Println("Returning JSON representation of a user")
ctx.JSON(iris.StatusOK, user)
} else {
fmt.Println("Returning JSON representation of a product")
ctx.JSON(iris.StatusBadRequest, Error{400, "user with this id does not exist"})
}
db.Close()
}
func Register(ctx *iris.Context) {
fmt.Println("4 Starting connection")
fmt.Println(ctx.FormValues())
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")
fname := ctx.FormValue("fname")
lname := ctx.FormValue("lname")
uname := ctx.FormValue("uname")
contact := ctx.FormValue("contact")
email := ctx.FormValue("email")
password := ctx.FormValue("password")
var contactInt int
fmt.Println(reflect.TypeOf(contact), contact)
// fmt.Println("URL => ",ctx.URLParam("email"))
// myMap := ctx.FormValues()
// var keyStrMap string
// for k,_ := range myMap {
// keyStrMap = k
// break
// }
// type AuthData struct{
// Email string `json:"email"`
// Password string `json:"password"`
// }
// keyMap := AuthData{}
// err = json.Unmarshal([]byte(keyStrMap), &keyMap)
// fmt.Println(keyMap, reflect.TypeOf(keyMap))
// email := keyMap.Email
// password := keyMap.Password
if email == "" && password == "" && fname == "" && lname == "" && uname == "" && contact == ""{
fmt.Println("Email & Password & Fname, Lname, Uname (AND)")
myMap := ctx.FormValues()
var keyStrMap string
for k,_ := range myMap {
keyStrMap = k
break
}
fmt.Println("Key Str Map => ", keyStrMap)
type AuthData struct{
Fname string `json:"fname"`
Lname string `json:"lname"`
Uname string `json:"uname"`
Contact int `json:"contact"`
Email string `json:"email"`
Password string `json:"password"`
}
keyMap := AuthData{}
err = json.Unmarshal([]byte(keyStrMap), &keyMap)
fmt.Println(keyMap, reflect.TypeOf(keyMap))
email = keyMap.Email
fmt.Println("Email: ",email)
password = keyMap.Password
fmt.Println("Password: ",password)
fname = keyMap.Fname
fmt.Println("Fname: ", fname)
lname = keyMap.Lname
fmt.Println("Lname: ",lname)
contactInt = keyMap.Contact
fmt.Println("Contact: ", contactInt)
uname = keyMap.Uname
fmt.Println("Uname: ",uname)
fmt.Println("Details: ",fname, lname, uname, password, email, contactInt)
if email == "" || password == "" || uname == "" || fname == "" {
fmt.Println("Details: ",fname, lname, uname, password, email, contactInt)
fmt.Println("email, password, fname, uname & contact are required fields")
ctx.JSON(iris.StatusBadRequest, map[string]interface{}{"message": "email, password, fname, uname & contact are required fields", "status": 400})
return
}
}
fmt.Println("Got", email, fname, lname, uname, contact, " & ", password)
// _, err = strconv.Atoi(contact)
// if err != nil {
// ctx.JSON(iris.StatusBadRequest, map[string]interface{}{"message": "contact should be a mobile number of the form 917353787704", "status": 500})
// return
// }
email = strings.TrimSpace(email)
// password = strings.TrimSpace(password)
rows, err := db.Query("SELECT id, fname, lname from users where email='"+email+"'")
found := false
for rows.Next() {
found = true
break
}
if found {
ctx.JSON(iris.StatusBadRequest, map[string]interface{}{"message": "This email is already registered", "status": 400})
return
}
stmt, err := db.Prepare("INSERT INTO users( fname, lname, uname, email, contact, profile_pic, password) values('"+
fname+"', '"+lname+"', '"+uname+"', '"+email+"', "+strconv.Itoa(contactInt)+", 'https://cdn2.iconfinder.com/data/icons/circle-icons-1/64/profle-512.png', '"+
password+"' )")
if err != nil {
log.Fatal(err)
ctx.JSON(iris.StatusInternalServerError, map[string]interface{}{"message": "error while processing INSERT(signup) query", "status": 500})
return
}
res, err := stmt.Exec()
if err != nil {
// log.Fatal(err)
ctx.JSON(iris.StatusInternalServerError, map[string]interface{}{"message": "error while processing INSERT(signup) query", "status": 500})
return
}
userId, err := res.LastInsertId()
if err != nil {
// log.Fatal(err)
ctx.JSON(iris.StatusInternalServerError, map[string]interface{}{"message": "error while fetching user id", "status": 500})
return
}
ctx.JSON(iris.StatusOK, map[string]interface{}{"message": "you got your account successfully registered", "userId": userId, "status": 200})
fmt.Println("Query succesfully executed while INSERTING(CREATING) a new user")
db.Close()
}
func CacheFile(ctx *iris.Context) {
fmt.Println("Ok, Printing data at a time.")
// ctx.Render("catche_file.html", struct {} {})
// ctx.Write([]byte("<h1>Cookie</h1>"))
ctx.Write([]byte(htmlText))
}
func Home(ctx *iris.Context) {
fmt.Println("Ok, Visiting Home")
// ctx.Render("catche_file.html", struct {} {})
// ctx.Write([]byte("<h1>Cookie</h1>"))
ctx.Write([]byte(htmlTextHome))
}
func Profile(ctx *iris.Context) {
fmt.Println("Ok, Visiting Profile")
// ctx.Render("catche_file.html", struct {} {})
// ctx.Write([]byte("<h1>Cookie</h1>"))
ctx.Write([]byte(htmlTextProfile))
}
func main() {
fmt.Println("Starting the development server at 8080")
// iris.Config.IsDevelopment = true
app := iris.New()
app.Adapt(httprouter.New())
app.Get("/products/", Products)
app.Get("/products/:id", Product)
app.Post("/products/create/", CreateProduct)
app.Put("/products/update/", UpdateProduct)
app.Post("/login/", Login)
app.Post("/register/", Register)
app.Get("/users/", Users)
app.Get("/users/:id", User)
app.Get("/catche_file/",CacheFile)
app.Get("/",Home)
app.Get("/profile/", Profile)
app.Post("/", Home)
// app.Get("/ui/create/", CreateProductUi)
app.Listen("0.0.0.0:8000")
// iris.Get("/products/", Products)
// iris.Get("/products/:id", Product)
// iris.Post("/products/create/", CreateProduct)
// iris.Get("/ui/create/", CreateProductUi)
// iris.Listen(":8080")
}
var htmlText = `<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
console.log("Hello"+user)
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
<h1>Cookie</h1>
</body>
</html>
`
var htmlTextHome = `<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<style type="text/css">
body{
background-color: #7f8c8d;
}
</style>
<body>
<!--NAVBAR-->
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html" style="color: white">Sharpseller </a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li><a href="about.html">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
<!-- <li><a href="#">Sign in</a></li>
<li><a href="#">Sign up</a></li> -->
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
<li><a href="login.html"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
</div>
</nav>
<!--NAVBAR END-->
<h1 style="color: white" class="text-center" >SharpSeller</h1>
<div id="login-overlay" class="modal-dialog" style="margin-top: 5%">
<div class="modal-content">
<div class="modal-header">
<!-- <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> -->
<h4 class="modal-title" id="myModalLabel" style="color: blue">Login to <span style="color: green">sharpseller.com</span></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-6">
<div class="well">
<form id="loginForm" method="post" novalidate="novalidate" onsubmit="return login()">
<div class="form-group">
<label for="username" class="control-label">Email</label>
<input type="text" class="form-control" id="email" name="email" value="" required="" title="Please enter you username" placeholder="sharpseller@gmail.com" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="password" class="control-label">Password</label>
<input type="password" class="form-control" id="password" name="password" value="" required="" placeholder="******" title="Please enter your password" />
<span class="help-block"></span>
</div>
<div id="loginErrorMsg" class="alert alert-error hide">Wrong username og password</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" id="remember" /> Remember login
</label>
<p class="help-block">(if this is a private computer)</p>
</div>
<input type="submit" class="btn btn-success btn-block" value="Submit" />
<a href="/forgot/" class="btn btn-default btn-block">Help to login</a>
</form>
</div>
</div>
<div class="col-xs-6">
<p class="lead">Register now for <span class="text-success">FREE</span></p>
<ul class="list-unstyled" style="line-height: 2">
<li><span class="fa fa-check text-success"></span> See all your orders</li>
<li><span class="fa fa-check text-success"></span> Fast re-order</li>
<li><span class="fa fa-check text-success"></span> Save your favorites</li>
<li><span class="fa fa-check text-success"></span> Fast checkout</li>
<li><span class="fa fa-check text-success"></span> Get a gift <small>(only new customers)</small></li>
<li><a href="#"><u>Read more</u></a></li>
</ul>
<p><a href="#" class="btn btn-info btn-block">Yes please, register now!</a></p>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
console.log("Hello"+user)
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function login(){
console.log("Happening")
// alert("Great")
var em = document.getElementById("email").value;
var pass = document.getElementById("password").value;
console.log(em, pass)
alert(em + " - " + pass)
// alert(email + " - "+password)
// $http.post("http://127.0.0.1:8080/login/",JSON.stringify( { username: em, password: pass })).success(
// function(data, status, headers, config){
// // console.log(response.data)
// alert(data)
// // return false
// }.error(
// function(data, status, headers, config){
// // console.log(response.data)
// alert("Error occured")
// // return false
// })
// )
//
// var v = $http({
// url: 'http://127.0.0.1:8080/login/',
// method: "POST",
// data: { email: em, password: pass }
// })
// .then(function(response) {
// // success
// alert("Hello")
// },
// function(response) { // optional
// // failed
// alert("Error")
// });
// fetch('http://127.0.0.1:8080/login/', {
// method: 'POST',
// body: JSON.stringify( { email: em, password: pass })
// }).then(function(response) {
// console.log(response.json(), response.data)
// alert(response.json())
// return response.json();
// }).then(function(data) {
// alert("error")
// });
fetch("http://0.0.0.0:8080/login/",{method: "POST", headers: {"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"} ,body: JSON.stringify({email: em, password: pass}) })
.then((response) => response.json())
.then((response) => {
// if(response.status==200){
// alert("success")
// } else {
// alert("no success")
// }
console.log( response )
if (response.status==200){
try{
// document.cookie = "userId=Rishikesh; expires=Thu 07 Jun 2017 00:00:00 UTC; path=/"+
// console.log(document.cookie)
// alert("Cookie Set", document.cookie)
console.log(response.id, typeof response.id)
setCookie("utaxi_hygull_id",response.id,1)
console.log("cookie set")
} catch(err) {
alert(err.message)
}
window.location.href = "http://0.0.0.0:8080/profile/"
console.log(response)
return true
} else {
// window.location.href = "error.html"
alert("Invalid credentials")
console.log(response)
return false
}
// for(v of ){
// console.log(v)
// }
})
.catch((error) => {
alert("Error while OTP Request")
return false
})
// console.log(v)
}
</script>
</body>
</html> `
var htmlTextProfile = `<!DOCTYPE html>
<html lang="en">
<head>
<title>Profile</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<style type="text/css">
.card {
padding-top: 20px;
margin: 10px 0 20px 0;
background-color: rgba(214, 224, 226, 0.2);
border-top-width: 0;
border-bottom-width: 2px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.card .card-heading {
padding: 0 20px;
margin: 0;
}
.card .card-heading.simple {
font-size: 20px;
font-weight: 300;
color: #777;
border-bottom: 1px solid #e5e5e5;
}
.card .card-heading.image img {
display: inline-block;
width: 46px;
height: 46px;
margin-right: 15px;
vertical-align: top;
border: 0;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
}
.card .card-heading.image .card-heading-header {
display: inline-block;
vertical-align: top;
}
.card .card-heading.image .card-heading-header h3 {
margin: 0;
font-size: 14px;
line-height: 16px;
color: #262626;
}
.card .card-heading.image .card-heading-header span {
font-size: 12px;
color: #999999;
}
.card .card-body {
padding: 0 20px;
margin-top: 20px;
}
.card .card-media {
padding: 0 20px;
margin: 0 -14px;
}
.card .card-media img {
max-width: 100%;
max-height: 100%;
}
.card .card-actions {
min-height: 30px;
padding: 0 20px 20px 20px;
margin: 20px 0 0 0;
}
.card .card-comments {
padding: 20px;
margin: 0;
background-color: #f8f8f8;
}
.card .card-comments .comments-collapse-toggle {
padding: 0;
margin: 0 20px 12px 20px;
}
.card .card-comments .comments-collapse-toggle a,
.card .card-comments .comments-collapse-toggle span {
padding-right: 5px;
overflow: hidden;
font-size: 12px;
color: #999;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-comments .media-heading {
font-size: 13px;
font-weight: bold;
}
.card.people {
position: relative;
display: inline-block;
width: 170px;
height: 300px;
padding-top: 0;
margin-left: 20px;
overflow: hidden;
vertical-align: top;
}
.card.people:first-child {
margin-left: 0;
}
.card.people .card-top {
position: absolute;
top: 0;
left: 0;
display: inline-block;
width: 170px;
height: 150px;
background-color: #ffffff;
}
.card.people .card-top.green {
background-color: #53a93f;
}
.card.people .card-top.blue {
background-color: #427fed;
}
.card.people .card-info {
position: absolute;
top: 150px;
display: inline-block;
width: 100%;
height: 101px;
overflow: hidden;
background: #ffffff;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.card.people .card-info .title {
display: block;
margin: 8px 14px 0 14px;
overflow: hidden;
font-size: 16px;
font-weight: bold;
line-height: 18px;
color: #404040;
}
.card.people .card-info .desc {
display: block;
margin: 8px 14px 0 14px;
overflow: hidden;
font-size: 12px;
line-height: 16px;
color: #737373;
text-overflow: ellipsis;
}
.card.people .card-bottom {
position: absolute;
bottom: 0;
left: 0;
display: inline-block;
width: 100%;
padding: 10px 20px;
line-height: 29px;
text-align: center;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.card.hovercard {
position: relative;
padding-top: 0;
overflow: hidden;
text-align: center;
background-color: rgba(214, 224, 226, 0.2);
}
.card.hovercard .cardheader {
background: url("http://lorempixel.com/850/280/nature/4/");
background-size: cover;
height: 135px;
}
.card.hovercard .avatar {
position: relative;
top: -50px;
margin-bottom: -50px;
}
.card.hovercard .avatar img {
width: 100px;
height: 100px;
max-width: 100px;
max-height: 100px;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
border: 5px solid rgba(255,255,255,0.5);
}
.card.hovercard .info {
padding: 4px 8px 10px;
}
.card.hovercard .info .title {
margin-bottom: 4px;
font-size: 24px;
line-height: 1;
color: #262626;
vertical-align: middle;
}
.card.hovercard .info .desc {
overflow: hidden;
font-size: 12px;
line-height: 20px;
color: #737373;
text-overflow: ellipsis;
}
.card.hovercard .bottom {
padding: 0 20px;
margin-bottom: 17px;
}
.btn{ border-radius: 50%; width:32px; height:32px; line-height:18px; }
h1{
color: green;
}
</style>
<style type="text/css">
body{
background-color: #ecf0f1;
}
</style>
</head>
<body>
<div class="container" ng-app="myApp" ng-controller="customersCtrl">
<h1 class="text-center">Profile</h1>
<div class="row">
<div class="col-lg-6 col-sm-6 col-md-6 col-sm--offset-3 col-lg-offset-3 col-md-offset-3 col-xs-10 col-xs-offset-1">
<div class="card hovercard">
<div class="cardheader">
</div>
<div class="avatar">
<img alt="" src="{{user.profile_pic}}">
</div>
<div class="info">
<div class="title">
<a target="_blank" href="http://scripteden.com/">{{user.fname}}</a>
</div>
<div class="desc">{{user.email}}</div>
<div class="desc">Software developer at Google</div>
<div class="desc">One of the creator of Golang</div>
</div>
<div class="bottom">
<a class="btn btn-primary btn-twitter btn-sm" href="https://twitter.com/webmaniac">
<i class="fa fa-twitter"></i>
</a>
<a class="btn btn-danger btn-sm" rel="publisher"
href="https://plus.google.com/+ahmshahnuralam">
<i class="fa fa-google-plus"></i>
</a>
<a class="btn btn-primary btn-sm" rel="publisher"
href="https://plus.google.com/shahnuralam">
<i class="fa fa-facebook"></i>
</a>
<a class="btn btn-warning btn-sm" rel="publisher" href="https://plus.google.com/shahnuralam">
<i class="fa fa-behance"></i>
</a>
</div>
</div>
</div>
</div>
<p id="pId"></p>
</div>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
var myCookie = document.cookie;
console.log("cookie value is ", myCookie)
// document.getElementById("pId").innerHTML = myCookie+"some";
console.log("cookie type: ", typeof myCookie)
console.log("Split", myCookie.split("="))
uid = 1
cookieArr = myCookie.split("=")
console.log(cookieArr)
var uid = cookieArr[1]
console.log("User id: ", uid)
$http.get("http://0.0.0.0:8080/users/"+uid).then(function (response) {
console.log("response.data: ", response.data)
$scope.user = response.data;
});
});
</script>
</body>
</html>
`
|
package utils
import (
"encoding/json"
"io/ioutil"
"zinx/src/zinx/ziface"
)
/*
存储一切有关 zinx 框架的全局参数,共其他模块使用
一些参数可以通过 zinx.json 由用户配置
*/
type GLobalObj struct {
/*
server
*/
TcpServer ziface.IServer // 当前zinx 全局的 server 对象
StrHostIP string // 当前服务器主机监听的IP
ITcpPort int // 当前服务器主机监听的port
StrName string // 当前服务器主的名称
/*
zinx
*/
StrVersion string // 当前zinx 的版本号
IMaxConn int // 当前zinx 主机所允许最大连接数
IMaxPackageSize uint32 // 当前zinx 数据包的最大值
IWorkerPoolSize uint32 // 当前业务工作worker池 Goroutine 数量
IMaxWorkerTaskLen uint32 // Zinx 框架允许用户最多开辟多少个 worker(限定条件)
}
/*
定义一个全局的对外 GlobalObj
*/
var GlobalObject *GLobalObj
// 从 zinx.json 去 加载用于自定义的参数
func (pG *GLobalObj) Reload() {
data, err := ioutil.ReadFile("conf/zinx.json")
//strFile, _ := exec.LookPath(os.Args[0])
//strPath, _ := filepath.Abs(strFile)
//index := strings.LastIndex(strPath, string(os.PathSeparator))
//strPath = strPath[:index]
//datapath := path.Join(strPath, "conf/zinx.json")
//fmt.Println(" Reload conf path",datapath)
//data,err :=ioutil.ReadFile(datapath)
if err != nil {
panic(err)
//fmt.Println(" Reload conf/zinx.json err=",err)
}
// 将json 文件数据解析到struct 中
err = json.Unmarshal(data, &GlobalObject)
if err != nil {
panic(err)
//fmt.Println(" Reload conf/zinx.json err=",err)
}
}
/*
提供一个 init 方法,初始化当前的 pGlobalObject
*/
func init() {
// 如果配置文件没有加载,默认值
GlobalObject = &GLobalObj{
StrName: "ZinxServerApp",
StrVersion: "V0.9",
ITcpPort: 8999,
IMaxConn: 1000,
IMaxPackageSize: 4096,
IWorkerPoolSize: 10, // worker 工作池的队列的个数
IMaxWorkerTaskLen: 1024, // 每个worker 对应的消息队列的任务的数量的最大值
}
// 应该尝试从 conf/zinx.json 去加载用户自定义的参数
GlobalObject.Reload()
}
|
/*
* @lc app=leetcode id=54 lang=golang
*
* [54] Spiral Matrix
*
* https://leetcode.com/problems/spiral-matrix/description/
*
* algorithms
* Medium (30.67%)
* Likes: 1147
* Dislikes: 420
* Total Accepted: 242.1K
* Total Submissions: 788.3K
* Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]'
*
* Given a matrix of m x n elements (m rows, n columns), return all elements of
* the matrix in spiral order.
*
* Example 1:
*
*
* Input:
* [
* [ 1, 2, 3 ],
* [ 4, 5, 6 ],
* [ 7, 8, 9 ]
* ]
* Output: [1,2,3,6,9,8,7,4,5]
*
*
* Example 2:
*
* Input:
* [
* [1, 2, 3, 4],
* [5, 6, 7, 8],
* [9,10,11,12]
* ]
* Output: [1,2,3,4,8,12,11,10,9,5,6,7]
*
*/
func spiralOrder(matrix [][]int) []int {
ret := []int{}
m:= len(matrix)
if m == 0 {
// 빈 슬라이스가 들어 오면 빈 슬라이스를 리턴한다.
return ret
}
n:= len(matrix[0])
// 초기 요소 0,0 에서 시작한다.
i, j := 0, 0
for ;; {
// 최후의 하나 요소가 남으면 그 요소를 추가 하고 끝낸다.
if m == 1 && n == 1 {
ret=append(ret, matrix[i][j])
break;
}
// 상단 열을 추가한다.
for step:= 0 ; step < n-1 ; step++ {
ret=append(ret, matrix[i][j])
j++
}
// 우측 열을 진행 하기 전에 m 이 1이면
// 현재 가리키고 있는 요소만 추가 하고 끝낸다.
if m == 1 {
ret=append(ret, matrix[i][j])
break;
}
// 우측 열을 추가한다.
for step:= 0 ; step < m-1 ; step++ {
ret=append(ret, matrix[i][j])
i++
}
// 하단 열을 진행 하기 전에
// n 이 1 이면 현재 가키리는 요소만 추가하고 끝낸다.
if n == 1 {
ret=append(ret, matrix[i][j])
break;
}
// 하단 열을 추가한다.
for step:= 0 ; step < n-1 ; step++ {
ret=append(ret, matrix[i][j])
j--
}
// 좌측 열을 추가한다.
for step:= 0 ; step < m-1 ; step++ {
ret=append(ret, matrix[i][j])
i--
}
// 최외측 열을 제외 하기 위해 2씩 뺀다.
m = m - 2
n = n - 2
// 남은 배열이 없으면 끝낸다.
if m <=0 || n <= 0 {
break
}
// 요소 좌표에 1씩 더해 안쪽 열로 위치를 바꾼다.
i ++
j ++
}
return ret
// 이 알고리즘은 제일 바깥쪽 열을 순회 하면서 결과를 추가하고
// i, j 에 1씩 추가 해 안쪽 열로 진입해 4면의 열을 추가 하는 방식으로
// 결과를 구한다.
// 전체 순회 하는 갯수는 n 에 비례하므로
// 수행 시간 복잡도는 O(n) 이다.
}
|
package pool
import (
"github.com/yuin/gopher-lua"
"layeh.com/gopher-luar"
"reflect"
"sync"
)
type module struct {
state *lua.LState
table *lua.LTable
method sync.Map
}
func (m *module) To(val interface{}, name ...string) bool {
if len(name) > 0 {
return __toValue(m.state.GetField(m.table, name[0]), val)
}
return __toValue(m.table, val)
}
func (m *module) Call(name string, args ...interface{}) {
m.__callByName(name, 0, nil, args...)
}
func (m *module) Method(name string, val interface{}) bool {
method := m.__method(name)
if nil == method {
return false
}
typ := reflect.TypeOf(val).Elem()
build := func(*lua.LState) []reflect.Value {
return nil
}
if typ.NumOut() > 0 {
build = func(state *lua.LState) []reflect.Value {
result := make([]reflect.Value, typ.NumOut())
top := state.GetTop()
for i, l := 0, typ.NumOut(); i < l; i++ {
v := reflect.New(typ.Out(i))
result[i] = v.Elem()
if i < top {
__toValue(state.Get(-(i + 1)), v.Interface())
}
}
return result
}
}
reflect.ValueOf(val).Elem().Set(
reflect.MakeFunc(
typ,
func(args []reflect.Value) (results []reflect.Value) {
var params []interface{}
if len(args) > 0 {
params = make([]interface{}, len(args))
for i := range args {
if args[i].IsValid() {
params[i] = args[i].Interface()
}
}
}
return m.__call(method, typ.NumOut(), build, params...)
}),
)
return true
}
func (m *module) __method(name string) (method *lua.LFunction) {
if it, ok := m.method.Load(name); ok {
method = it.(*lua.LFunction)
} else if f := m.state.GetField(m.table, name); lua.LTFunction == f.Type() {
method = f.(*lua.LFunction)
m.method.Store(name, method)
}
return
}
func (m *module) __callByName(name string, nret int, result func(*lua.LState) []reflect.Value, args ...interface{}) []reflect.Value {
return m.__call(m.__method(name), nret, result, args...)
}
func (m *module) __call(method *lua.LFunction, nret int, result func(*lua.LState) []reflect.Value, args ...interface{}) []reflect.Value {
thread, cancelFunc := m.state.NewThread()
defer thread.Close()
if cancelFunc != nil {
defer cancelFunc()
}
defer thread.SetTop(0)
thread.Push(method)
thread.Push(m.table)
for _, v := range args {
thread.Push(luar.New(thread, v))
}
thread.Call(len(args)+1, nret)
if nil != result {
return result(thread)
}
return nil
}
|
package filters
import (
"math"
"math/rand"
"sync"
"github.com/stripe/unilog/clevels"
"github.com/stripe/unilog/json"
)
var startSystemAusterityLevel sync.Once
// AusterityFilter applies system-wide austerity levels to a log
// line. If austerity levels indicate a line should be shedded, the
// like's contents will replaced with "(shedded)" in text mode and the
// "shedded"=true attribude in JSON mode.
//
// Shedding log lines retains their time stamps.
type AusterityFilter struct{}
// AusteritySetup starts the parser for the system austerity level. It is
// exported so that tests can call it with testing=true in test setup,
// which will disable sending the austerity level (and also appease
// the race detector).
func AusteritySetup(testing bool) {
// Start austerity level loop sender in goroutine just once
startSystemAusterityLevel.Do(func() {
if !testing {
go clevels.SendSystemAusterityLevel()
}
})
}
// FilterLine applies shedding to a text event
func (a *AusterityFilter) FilterLine(line string) string {
AusteritySetup(false)
if ShouldShed(clevels.Criticality(line)) {
return "(shedded)"
}
return line
}
// FilterJSON applies shedding to a JSON event
func (a *AusterityFilter) FilterJSON(line *json.LogLine) {
AusteritySetup(false)
if ShouldShed(clevels.JSONCriticality(*line)) {
// clear the line:
newLine := map[string]interface{}{}
if ts, ok := (*line)["ts"]; ok {
newLine["ts"] = ts
}
newLine["shedded"] = true
*line = newLine
}
}
// ShouldShed returns true if the given criticalityLevel indicates a log
// should be shed, according to the system austerity level
func ShouldShed(criticalityLevel clevels.AusterityLevel) bool {
austerityLevel := <-clevels.SystemAusterityLevel
if criticalityLevel >= austerityLevel {
return false
}
return rand.Float64() > samplingRate(austerityLevel, criticalityLevel)
}
// samplingRate calculates the rate at which loglines will be sampled for the
// given criticality level and austerity level. For example, if the austerity level
// is Critical (3), then lines that are Sheddable (0) will be sampled at .001.
func samplingRate(austerityLevel, criticalityLevel clevels.AusterityLevel) float64 {
if criticalityLevel > austerityLevel {
return 1
}
levelDiff := austerityLevel - criticalityLevel
samplingRate := math.Pow(10, float64(-levelDiff))
return samplingRate
}
|
package main
import (
"os"
"github.com/gekalogiros/sniffio/cmd"
)
func main() {
root:=cmd.NewSniffioCommand()
root.AddCommand(
cmd.NewVersionCommand(os.Stdout),
cmd.NewArpCommand(os.Stdout),
cmd.NewIfacesCommand(os.Stdout),
cmd.NewTCPCommand(os.Stdout),
)
root.Execute()
} |
package openshift_osinserver
import (
"k8s.io/client-go/rest"
configapi "github.com/openshift/origin/pkg/cmd/server/apis/config"
"github.com/openshift/origin/pkg/oauthserver/oauthserver"
genericapiserver "k8s.io/apiserver/pkg/server"
// for metrics
_ "k8s.io/kubernetes/pkg/client/metrics/prometheus"
)
func RunOpenShiftOsinServer(oauthConfig configapi.OAuthConfig, kubeClientConfig *rest.Config, stopCh <-chan struct{}) error {
oauthServerConfig, err := oauthserver.NewOAuthServerConfigFromInternal(oauthConfig, kubeClientConfig)
if err != nil {
return err
}
// TODO you probably want to set this
//oauthServerConfig.GenericConfig.CorsAllowedOriginList = genericConfig.CorsAllowedOriginList
//oauthServerConfig.GenericConfig.SecureServing = genericConfig.SecureServing
//oauthServerConfig.GenericConfig.AuditBackend = genericConfig.AuditBackend
//oauthServerConfig.GenericConfig.AuditPolicyChecker = genericConfig.AuditPolicyChecker
// Build the list of valid redirect_uri prefixes for a login using the openshift-web-console client to redirect to
oauthServerConfig.ExtraOAuthConfig.AssetPublicAddresses = []string{oauthConfig.AssetPublicURL}
oauthServer, err := oauthServerConfig.Complete().New(genericapiserver.NewEmptyDelegate())
if err != nil {
return err
}
return oauthServer.GenericAPIServer.PrepareRun().Run(stopCh)
}
|
package endpoints
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
shd "github.com/ebikode/eLearning-core/domain/schedule"
usr "github.com/ebikode/eLearning-core/domain/user"
md "github.com/ebikode/eLearning-core/model"
tr "github.com/ebikode/eLearning-core/translation"
ut "github.com/ebikode/eLearning-core/utils"
"github.com/go-chi/chi"
)
// GetScheduleEndpoint fetch a single schedule
func GetScheduleEndpoint(shs shd.ScheduleService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
scheduleID, _ := strconv.ParseUint(chi.URLParam(r, "scheduleID"), 10, 64)
var schedule *md.Schedule
schedule = shs.GetSchedule(uint(scheduleID))
resp := ut.Message(true, "")
resp["schedule"] = schedule
ut.Respond(w, r, resp)
}
}
// GetAdminSchedulesEndpoint fetch a single schedule
func GetAdminSchedulesEndpoint(shs shd.ScheduleService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
page, limit := ut.PaginationParams(r)
schedules := shs.GetSchedules(page, limit)
var nextPage int
if len(schedules) == limit {
nextPage = page + 1
}
resp := ut.Message(true, "")
resp["current_page"] = page
resp["next_page"] = nextPage
resp["limit"] = limit
resp["schedules"] = schedules
ut.Respond(w, r, resp)
}
}
// GetCourseSchedulesEndpoint all schedules of a tutor user
func GetCourseSchedulesEndpoint(shs shd.ScheduleService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
courseID, _ := strconv.ParseUint(chi.URLParam(r, "courseID"), 10, 64)
schedules := shs.GetSchedulesByCourse(uint(courseID))
resp := ut.Message(true, "")
resp["schedules"] = schedules
ut.Respond(w, r, resp)
}
}
// GetTutorCourseSchedulesEndpoint all schedules of a tutor user
func GetTutorCourseSchedulesEndpoint(shs shd.ScheduleService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Get User Token Data
tokenData := r.Context().Value("tokenData").(*md.UserTokenData)
userID := string(tokenData.UserID)
courseID, _ := strconv.ParseUint(chi.URLParam(r, "courseID"), 10, 64)
schedules := shs.GetSchedulesByCourseOwner(userID, uint(courseID))
resp := ut.Message(true, "")
resp["schedules"] = schedules
ut.Respond(w, r, resp)
}
}
// CreateScheduleEndpoint ...
func CreateScheduleEndpoint(shs shd.ScheduleService, uss usr.UserService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Get User Token Data
tokenData := r.Context().Value("tokenData").(*md.UserTokenData)
userID := string(tokenData.UserID)
payload := shd.Payload{}
err := json.NewDecoder(r.Body).Decode(&payload)
fmt.Println("second Error check", err)
tParam := tr.TParam{
Key: "error.request_error",
TemplateData: nil,
PluralCount: nil,
}
if err != nil {
// Respond with an errortra nslated
resp := ut.Message(false, ut.Translate(tParam, r))
ut.ErrorRespond(http.StatusBadRequest, w, r, resp)
return
}
checkUser := uss.GetUser(userID)
if checkUser == nil {
tParam = tr.TParam{
Key: "error.user_not_found",
TemplateData: nil,
PluralCount: nil,
}
resp := ut.Message(false, ut.Translate(tParam, r))
ut.ErrorRespond(http.StatusBadRequest, w, r, resp)
return
}
// Validate schedule input
err = shd.Validate(payload, r)
if err != nil {
validationFields := shd.ValidationFields{}
fmt.Println("third Error check", validationFields)
b, _ := json.Marshal(err)
// Respond with an errortranslated
resp := ut.Message(false, ut.Translate(tParam, r))
json.Unmarshal(b, &validationFields)
resp["error"] = validationFields
ut.ErrorRespond(http.StatusBadRequest, w, r, resp)
return
}
schedule := md.Schedule{
CourseID: payload.CourseID,
WeekDay: payload.WeekDay,
TimeFromHour: payload.TimeFromHour,
TimeFromMinute: payload.TimeFromMinute,
TimeToHour: payload.TimeToHour,
TimeToMunite: payload.TimeToMunite,
}
// Create a schedule
newSchedule, errParam, err := shs.CreateSchedule(schedule)
if err != nil {
// Check if the error is duplischeduleion error
cErr := ut.CheckUniqueError(r, err)
if cErr != nil {
ut.ErrorRespond(http.StatusBadRequest, w, r, ut.Message(false, cErr.Error()))
return
}
// Respond with an errortranslated
ut.ErrorRespond(http.StatusBadRequest, w, r, ut.Message(false, ut.Translate(errParam, r)))
return
}
tParam = tr.TParam{
Key: "general.resource_created",
TemplateData: nil,
PluralCount: nil,
}
resp := ut.Message(true, ut.Translate(tParam, r))
resp["schedule"] = newSchedule
ut.Respond(w, r, resp)
}
}
// UpdateScheduleEndpoint
func UpdateScheduleEndpoint(shs shd.ScheduleService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Get User Token Data
tokenData := r.Context().Value("tokenData").(*md.UserTokenData)
userID := string(tokenData.UserID)
// Translation Param
tParam := tr.TParam{
Key: "error.request_error",
TemplateData: nil,
PluralCount: nil,
}
// Parse the schedule id param
scheduleID, pErr := strconv.ParseUint(chi.URLParam(r, "scheduleID"), 10, 64)
if pErr != nil || uint(scheduleID) < 1 {
// Respond with an error translated
resp := ut.Message(false, ut.Translate(tParam, r))
ut.ErrorRespond(http.StatusBadRequest, w, r, resp)
return
}
schedulePayload := shd.Payload{}
// dECODE THE REQUEST BODY
err := json.NewDecoder(r.Body).Decode(&schedulePayload)
if err != nil {
// Respond with an error translated
resp := ut.Message(false, ut.Translate(tParam, r))
ut.ErrorRespond(http.StatusBadRequest, w, r, resp)
return
}
// Validate schedule input
err = shd.ValidateUpdates(schedulePayload, r)
if err != nil {
validationFields := shd.ValidationFields{}
b, _ := json.Marshal(err)
// Respond with an errortranslated
resp := ut.Message(false, ut.Translate(tParam, r))
json.Unmarshal(b, &validationFields)
resp["error"] = validationFields
ut.ErrorRespond(http.StatusBadRequest, w, r, resp)
return
}
// Get the schedule
checkSchedule := shs.GetSchedule(uint(scheduleID))
if checkSchedule.Course.UserID != userID {
tParam = tr.TParam{
Key: "error.course_not_found",
TemplateData: nil,
PluralCount: nil,
}
resp := ut.Message(false, ut.Translate(tParam, r))
ut.ErrorRespond(http.StatusBadRequest, w, r, resp)
return
}
// Assign new values
checkSchedule.WeekDay = schedulePayload.WeekDay
checkSchedule.TimeFromHour = schedulePayload.TimeFromHour
checkSchedule.TimeFromMinute = schedulePayload.TimeFromMinute
checkSchedule.TimeToHour = schedulePayload.TimeToHour
checkSchedule.TimeToMunite = schedulePayload.TimeToMunite
checkSchedule.Status = schedulePayload.Status
// Update a schedule
updatedSchedule, errParam, err := shs.UpdateSchedule(checkSchedule)
if err != nil {
// Check if the error is duplischeduleion error
cErr := ut.CheckUniqueError(r, err)
if cErr != nil {
ut.ErrorRespond(http.StatusBadRequest, w, r, ut.Message(false, cErr.Error()))
return
}
// Respond with an errortranslated
ut.ErrorRespond(http.StatusBadRequest, w, r, ut.Message(false, ut.Translate(errParam, r)))
return
}
tParam = tr.TParam{
Key: "general.update_success",
TemplateData: nil,
PluralCount: nil,
}
resp := ut.Message(true, ut.Translate(tParam, r))
resp["schedule"] = updatedSchedule
ut.Respond(w, r, resp)
}
}
|
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
var _ sdk.Msg = &MsgCreateAchievement{}
func NewMsgCreateAchievement(creator string, achievementID string, owner string) *MsgCreateAchievement {
return &MsgCreateAchievement{
Creator: creator,
AchievementID: achievementID,
Owner: owner,
}
}
func (msg *MsgCreateAchievement) Route() string {
return RouterKey
}
func (msg *MsgCreateAchievement) Type() string {
return "CreateAchievement"
}
func (msg *MsgCreateAchievement) GetSigners() []sdk.AccAddress {
creator, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
panic(err)
}
return []sdk.AccAddress{creator}
}
func (msg *MsgCreateAchievement) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(msg)
return sdk.MustSortJSON(bz)
}
func (msg *MsgCreateAchievement) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err)
}
return nil
}
var _ sdk.Msg = &MsgUpdateAchievement{}
func NewMsgUpdateAchievement(creator string, id uint64, achievementID string, owner string, createdAt int32) *MsgUpdateAchievement {
return &MsgUpdateAchievement{
Id: id,
Creator: creator,
AchievementID: achievementID,
Owner: owner,
CreatedAt: createdAt,
}
}
func (msg *MsgUpdateAchievement) Route() string {
return RouterKey
}
func (msg *MsgUpdateAchievement) Type() string {
return "UpdateAchievement"
}
func (msg *MsgUpdateAchievement) GetSigners() []sdk.AccAddress {
creator, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
panic(err)
}
return []sdk.AccAddress{creator}
}
func (msg *MsgUpdateAchievement) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(msg)
return sdk.MustSortJSON(bz)
}
func (msg *MsgUpdateAchievement) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err)
}
return nil
}
var _ sdk.Msg = &MsgDeleteAchievement{}
func NewMsgDeleteAchievement(creator string, id uint64) *MsgDeleteAchievement {
return &MsgDeleteAchievement{
Id: id,
Creator: creator,
}
}
func (msg *MsgDeleteAchievement) Route() string {
return RouterKey
}
func (msg *MsgDeleteAchievement) Type() string {
return "DeleteAchievement"
}
func (msg *MsgDeleteAchievement) GetSigners() []sdk.AccAddress {
creator, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
panic(err)
}
return []sdk.AccAddress{creator}
}
func (msg *MsgDeleteAchievement) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(msg)
return sdk.MustSortJSON(bz)
}
func (msg *MsgDeleteAchievement) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err)
}
return nil
}
|
package testkit
import (
"reflect"
"strings"
"testing"
)
// AssertEqual asserts that two values are equal
func AssertEqual(t *testing.T, expected interface{}, got interface{}) {
if !reflect.DeepEqual(expected, got) {
t.Errorf("\n\n---- Expected:\n%v\n++++ Got:\n%v\n\n", expected, got)
}
}
// AssertIsNil asserts that a value is nil
func AssertIsNil(t *testing.T, got interface{}) {
if got != nil {
t.Errorf("\n\n Value '%v' is not nil\n\n", got)
}
}
// AssertContains asserts if a string contains another string
func AssertContains(t *testing.T, s string, substring string) {
t.Helper()
if !strings.Contains(s, substring) {
t.Errorf("\n\n '%v' does not contain '%v'\n\n", s, substring)
}
}
// AssertError asserts if an error is not nil
func AssertError(t testing.TB, got, want error) {
t.Helper()
if got == nil {
t.Fatal("expecting an error, got none")
}
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
|
package gojson
import (
"bytes"
"reflect"
"unsafe"
"fmt"
"strconv"
)
const (
startArray byte = '['
stopArray byte = ']'
startObject byte = '{'
stopObject byte = '}'
startString byte = '"'
escape byte = '\\'
)
// Unarshal parses input bytes and returns new json
func Unmarshal(value []byte) *GoJSON {
json := &GoJSON{}
var node *GoJSON
parseValue(json, node, skip(value))
return json
}
func skip(value []byte) []byte {
i := 0
for i < len(value) && value[i] <= 32 {
i++
}
return value[i:]
}
func parseKey(json *GoJSON, node *GoJSON, value []byte) []byte {
if value[0] != startString {
syntaxError()
}
i := 1
for i < len(value) {
if value[i] == startString {
if value[i-1] == escape {
i++
continue
}
break
}
i++
}
if json.Map == nil {
json.Map = make(map[string]*GoJSON)
}
json.Map[bytesToStr(value[1:i])] = node
return value[i+1:]
}
func parseValue(json *GoJSON, node *GoJSON, value []byte) []byte {
if len(value) == 0 {
return value
}
switch value[0] {
case 'n': // n
if len(value) >= 4 && value[1] == 'u' && value[2] == 'l' && value[3] == 'l' {
node.Type = JSONNull
node.Bytes = value[:4]
return value[4:]
}
case 'f': // f
if len(value) >= 5 && value[1] == 'a' && value[2] == 'l' && value[3] == 's' && value[4] == 'e' { // e
node.Type = JSONBool
node.Bytes = value[:5]
return value[5:]
}
case 't': // t
if len(value) >= 4 && value[1] == 'r' && value[2] == 'u' && value[3] == 'e' {
node.Type = JSONBool
node.Bytes = value[:4]
return value[4:]
}
case startString: // "
return parseString(node, value)
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': // - , 0-9
return parseNumber(node, value)
case startArray:
return parseArray(json, node, value)
case startObject:
return parseObject(json, node, value)
}
return value
}
func parseString(node *GoJSON, value []byte) []byte {
if value[0] != startString {
syntaxError()
}
i := 1
for i < len(value) {
if value[i] == startString {
if value[i-1] == escape {
i++
continue
}
break
}
i++
}
node.Bytes = value[1:i]
node.Type = JSONString
return value[i+1:]
}
func parseNumber(node *GoJSON, value []byte) []byte {
i := 0
nodeType := JSONInt
hasExponent := false
if value[i] == 45 {
i++
} /* - */
loop:
for i < len(value) {
switch value[i] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
i++
case 'E':
hasExponent = true
i++
case '.':
nodeType = JSONFloat
i++
default:
break loop
}
}
node.Type = nodeType
node.Bytes = value[:i]
if hasExponent {
result, err := strconv.ParseFloat(bytesToStr(node.Bytes), 64)
if err == nil {
node.Bytes = []byte(fmt.Sprintf("%f", result))
}
}
return value[i:]
}
func parseArray(json *GoJSON, node *GoJSON, value []byte) []byte {
// Check for empty array
var parent *GoJSON
if json.Type != JSONInvalid {
// is child
if node != nil {
node.Type = JSONArray
} else {
node = NewArray()
}
parent = node
} else {
parent = json
}
parent.Type = JSONArray
value = skip(value[1:])
if len(value) > 0 && value[0] == stopArray {
return value[1:]
}
newNode := &GoJSON{}
value = skip(parseValue(parent, newNode, skip(value)))
if len(value) == 0 {
return value
}
if parent.Array == nil {
parent.Array = make([]*GoJSON, 1)
}
parent.Array[0] = newNode
for value[0] == 44 { // ,
newNode = &GoJSON{}
value = skip(parseValue(parent, newNode, skip(value[1:])))
if len(value) == 0 {
return value
}
parent.Array = append(parent.Array, newNode)
}
if len(value) > 0 && value[0] == stopArray {
return value[1:]
}
return value
}
func parseObject(json *GoJSON, node *GoJSON, value []byte) []byte {
// check for empty object
var parent *GoJSON
if json.Type != JSONInvalid {
// is child
if node != nil {
node.Type = JSONObject
} else {
node = NewObject()
}
parent = node
} else {
parent = json
}
parent.Type = JSONObject
value = skip(value[1:])
if len(value) > 0 && value[0] == stopObject {
return value[1:]
}
newNode := &GoJSON{}
value = skip(parseKey(parent, newNode, skip(value)))
if len(value) == 0 || value[0] != ':' {
syntaxError()
}
value = skip(parseValue(parent, newNode, skip(value[1:])))
if len(value) == 0 {
return value
}
for value[0] == ',' { // ,
newNode = &GoJSON{}
value = skip(parseKey(parent, newNode, skip(value[1:])))
if len(value) == 0 || value[0] != ':' {
syntaxError()
}
value = skip(parseValue(parent, newNode, skip(value[1:])))
if len(value) == 0 {
return value
}
}
if len(value) > 0 && value[0] == stopObject {
return value[1:]
}
return value
}
// Marshal transforms goJSON to []byte
func (g *GoJSON) Marshal(buf ...*bytes.Buffer) []byte {
var bf *bytes.Buffer
if len(buf) > 0 {
bf = buf[0]
} else {
bf = &bytes.Buffer{}
}
if g.Type == JSONObject {
bf.WriteByte(startObject)
idx := 0
for key, value := range g.Map {
if idx > 0 {
bf.WriteByte(44)
} else {
idx++
}
bf.WriteByte(startString)
bf.WriteString(key)
bf.WriteByte(startString)
bf.WriteByte(58)
writeValue(value, bf)
}
bf.WriteByte(stopObject)
} else {
bf.WriteByte(startArray)
for idx, value := range g.Array {
if idx > 0 {
bf.WriteByte(44)
}
writeValue(value, bf)
}
bf.WriteByte(stopArray)
}
return bf.Bytes()
}
func writeValue(value *GoJSON, bf *bytes.Buffer) {
switch value.Type {
case JSONString:
bf.WriteByte(startString)
var p int
for i := 0; i < len(value.Bytes); i++ {
c := value.Bytes[i]
var e byte
switch c {
case '\t':
e = 't'
case '\r':
e = 'r'
case '\n':
e = 'n'
case '\\':
e = '\\'
case '"':
e = '"'
//case '<', '>':
// if !w.EscapeLtGt {
// continue
// }
default:
if c >= 0x20 {
// no escaping is required
continue
}
}
if e != 0 {
bf.Write(value.Bytes[p:i])
bf.WriteByte(escape)
bf.WriteByte(e)
} else {
bf.Write(value.Bytes[p:i])
}
p = i + 1
}
bf.Write(value.Bytes[p:])
bf.WriteByte(startString)
case JSONArray, JSONObject:
value.Marshal(bf)
default:
bf.Write(value.Bytes)
}
}
func bytesToStr(data []byte) string {
h := (*reflect.SliceHeader)(unsafe.Pointer(&data))
sHdr := reflect.StringHeader{h.Data, h.Len}
return *(*string)(unsafe.Pointer(&sHdr))
}
func syntaxError() {
panic("Invalid json")
}
|
// Tideland Go Application Support - Logger
//
// Copyright (C) 2012-2014 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
// +build windows plan9
package logger
import (
"log"
)
// Dummy SysLogger for platforms without syslog
type SysLogger struct {
}
// A dummy NewSysLogger for platforms that don't support syslog. Only returns
// an error.
func NewSysLogger(tag string) (Logger, error) {
log.Fatalf("Syslog not supported on this platform!")
return &SysLogger{}, nil
}
// FAKE Debug logs a message at debug level.
func (sl *SysLogger) Debug(info, msg string) {
}
// FAKE Info logs a message at info level.
func (sl *SysLogger) Info(info, msg string) {
}
// FAKE Warning logs a message at warning level.
func (sl *SysLogger) Warning(info, msg string) {
}
// FAKE Error logs a message at error level.
func (sl *SysLogger) Error(info, msg string) {
}
// FAKE Critical logs a message at critical level.
func (sl *SysLogger) Critical(info, msg string) {
}
|
package w3po
import (
"../../util"
"../report"
"github.com/xojoc/bitset"
)
//intersect returns true if the two sets have at least one element in common
func intersect(a, b map[uint32]struct{}) bool {
for k := range a {
if _, ok := b[k]; ok {
return true
}
}
return false
}
type ListenerDataAccess struct{}
type ListenerAsyncSnd struct{}
type ListenerAsyncRcv struct{}
func (l *ListenerDataAccess) Put(p *util.SyncPair) {
if !p.DataAccess {
return
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
varstate, ok := variables[p.T2]
if !ok {
varstate = newVar()
}
varstate.current++
newFE := &dot{v: t1.vc.clone(), int: varstate.current, t: uint16(p.T1),
sourceRef: p.Ev.Ops[0].SourceRef, line: uint16(p.Ev.Ops[0].Line),
write: p.Write, ls: make(map[uint32]struct{}), pos: p.Ev.LocalIdx}
for _, k := range t1.ls { //copy lockset
newFE.ls[k] = struct{}{}
}
if p.Write {
newFrontier := make([]*dot, 0, len(varstate.frontier))
for _, f := range varstate.frontier {
k := f.v.get(uint32(f.t))
thi_at_j := t1.vc.get(uint32(f.t))
if k > thi_at_j {
newFrontier = append(newFrontier, f) // RW(x) = {j#k | j#k ∈ RW(x) ∧ k > Th(i)[j]}
if !intersect(newFE.ls, f.ls) {
report.ReportRace(report.Location{File: uint32(f.sourceRef), Line: uint32(f.line), W: f.write},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: true}, false, 0)
}
}
}
newFrontier = append(newFrontier, newFE) // ∪{i#Th(i)[i]}
varstate.frontier = newFrontier
} else if p.Read {
newFrontier := make([]*dot, 0, len(varstate.frontier))
//connectTo := make([]*dot, 0)
for _, f := range varstate.frontier {
k := f.v.get(uint32(f.t)) //j#k
thi_at_j := t1.vc.get(uint32(f.t)) //Th(i)[j]
if k > thi_at_j {
newFrontier = append(newFrontier, f) // RW(x) = {j]k | j]k ∈ RW(x) ∧ k > Th(i)[j]}
if f.write {
if !intersect(newFE.ls, f.ls) {
report.ReportRace(report.Location{File: uint32(f.sourceRef), Line: uint32(f.line), W: f.write},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: newFE.write}, false, 0)
}
}
} else {
if f.write {
newFrontier = append(newFrontier, f)
}
}
}
newFrontier = append(newFrontier, newFE) // ∪{i#Th(i)[i]}
varstate.frontier = newFrontier
} else { //volatile synchronize
vol, ok := volatiles[p.T2]
if !ok {
vol = newvc2()
}
t1.vc = t1.vc.ssync(vol)
vol = t1.vc.clone()
volatiles[p.T2] = vol
}
t1.vc = t1.vc.add(p.T1, 1)
threads[p.T1] = t1
variables[p.T2] = varstate
}
//UNLOCK Default
func (l *ListenerAsyncRcv) Put(p *util.SyncPair) {
if !p.AsyncRcv {
return
}
if !p.Unlock {
return
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
lock, ok := locks[p.T2]
if !ok {
lock = newL()
}
if len(t1.ls) > 0 { //remove lock from lockset
t1.ls = t1.ls[:len(t1.ls)-1]
}
t1.vc = t1.vc.add(p.T1, 1)
threads[p.T1] = t1
locks[p.T2] = lock
}
//LOCK Default
func (l *ListenerAsyncSnd) Put(p *util.SyncPair) {
if !p.AsyncSend {
return
}
if !p.Lock {
return
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
lock, ok := locks[p.T2]
if !ok {
lock = newL()
}
t1.ls = append(t1.ls, p.T2)
if len(t1.ls) > 1 {
multiLock++
} else {
singleLock++
}
numCrits++
if len(t1.ls) > maxMulti {
maxMulti = len(t1.ls)
}
t1.vc = t1.vc.add(p.T1, 1)
threads[p.T1] = t1
locks[p.T2] = lock
}
type ListenerDataAccessEE struct{}
func (l *ListenerDataAccessEE) Put(p *util.SyncPair) {
if !p.DataAccess {
return
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
varstate, ok := variables[p.T2]
if !ok {
varstate = newVar()
}
varstate.current++
newFE := &dot{v: t1.vc.clone(), int: varstate.current, t: uint16(p.T1),
sourceRef: p.Ev.Ops[0].SourceRef, line: uint16(p.Ev.Ops[0].Line),
write: p.Write, ls: make(map[uint32]struct{}), pos: p.Ev.LocalIdx}
for _, k := range t1.ls { //copy lockset
newFE.ls[k] = struct{}{}
}
newFrontier := make([]*dot, 0, len(varstate.frontier))
connectTo := make([]*dot, 0)
if p.Write {
for _, f := range varstate.frontier {
k := f.v.get(uint32(f.t))
thi_at_j := t1.vc.get(uint32(f.t))
if k > thi_at_j {
newFrontier = append(newFrontier, f) // RW(x) = {j#k | j#k ∈ RW(x) ∧ k > Th(i)[j]}
if !intersect(newFE.ls, f.ls) {
report.ReportRace(report.Location{File: uint32(f.sourceRef), Line: uint32(f.line), W: f.write},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: true}, false, 0)
}
visited := &bitset.BitSet{}
varstate.findRaces(newFE, f, visited, 0)
} else {
connectTo = append(connectTo, f)
}
}
varstate.updateGraph3(newFE, connectTo)
newFrontier = append(newFrontier, newFE) // ∪{i#Th(i)[i]}
varstate.frontier = newFrontier
//connect to artifical start dot if no connection exists
list, ok := varstate.graph.get(newFE.int)
if ok && len(list) == 0 {
list = append(list, &startDot)
varstate.graph.add(newFE, list)
}
} else if p.Read {
for _, f := range varstate.frontier {
k := f.v.get(uint32(f.t)) //j#k
thi_at_j := t1.vc.get(uint32(f.t)) //Th(i)[j]
if k > thi_at_j {
newFrontier = append(newFrontier, f) // RW(x) = {j]k | j]k ∈ RW(x) ∧ k > Th(i)[j]}
if f.write {
if !intersect(newFE.ls, f.ls) {
report.ReportRace(report.Location{File: uint32(f.sourceRef), Line: uint32(f.line), W: f.write},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: newFE.write}, false, 0)
}
visited := &bitset.BitSet{}
varstate.findRaces(newFE, f, visited, 0)
}
} else {
if f.int > 0 {
connectTo = append(connectTo, f)
}
if f.write {
newFrontier = append(newFrontier, f)
}
}
}
varstate.updateGraph3(newFE, connectTo)
newFrontier = append(newFrontier, newFE) // ∪{i#Th(i)[i]}
varstate.frontier = newFrontier
//connect to artifical start dot if no connection exists
list, ok := varstate.graph.get(newFE.int)
if ok && len(list) == 0 {
list = append(list, &startDot)
varstate.graph.add(newFE, list)
}
} else { //volatile synchronize
vol, ok := volatiles[p.T2]
if !ok {
vol = newvc2()
}
t1.vc = t1.vc.ssync(vol)
vol = t1.vc.clone()
volatiles[p.T2] = vol
}
t1.vc = t1.vc.add(p.T1, 1)
threads[p.T1] = t1
variables[p.T2] = varstate
}
|
package piscine
func DivMod(a int, b int, div *int, mod *int) {
var c int
var d int
c = a / b
d = a % b
*div = c
*mod = d
}
|
package ecr
import (
"encoding/base64"
"log"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
)
func GetToken() (string, string, error) {
sess, err := session.NewSession(&aws.Config{})
if err != nil {
return "", "", err
}
svc := ecr.New(sess)
input := &ecr.GetAuthorizationTokenInput{}
result, err := svc.GetAuthorizationToken(input)
if err != nil {
log.Println("svc.GetAuthorizationToken error")
return "", "", err
}
encodedToken := *result.AuthorizationData[0].AuthorizationToken
decodedToken, err := base64.StdEncoding.DecodeString(encodedToken)
if err != nil {
return "", "", err
}
tokenSplit := strings.Split(string(decodedToken), ":")
return tokenSplit[0], tokenSplit[1], nil
}
|
package timerWithLock
import (
"testing"
"time"
"strconv"
. "github.com/smartystreets/goconvey/convey"
)
func TestTimerManager(t *testing.T) {
manager := NewManager()
Convey("TestTimerManager", t, func() {
Convey("AddTimer", func() {
// 正常的添加一个定时器
key := "AddTimer"
So(manager.HasTimer(key), ShouldEqual, false)
manager.AddTimer(key, 2 * time.Second, func() {
t.Logf("key: %s, time out", key)
})
So(manager.HasTimer(key), ShouldEqual, true)
time.Sleep(3 * time.Second)
// 正常的添加一个定时器,然后再重复添加一次
manager.AddTimer(key, 1 * time.Second, func() {
t.Errorf("key: %s, should not be execute", key)
})
manager.AddTimer(key, 1 * time.Second, func() {
t.Logf("key: %s, time out", key)
})
time.Sleep(2 * time.Second)
So(manager.HasTimer(key), ShouldEqual, false)
})
Convey("CancelTimer", func() {
key := "CancelTimer"
// 正常的取消一个存在的定时器
manager.AddTimer(key, 2 * time.Second, func() {
t.Errorf("key: %s, should not be execute", key)
})
So(manager.CancelTimer(key), ShouldEqual, true)
time.Sleep(3 * time.Second)
// 取消一个不存在的定时器
So(manager.CancelTimer(key), ShouldEqual, false)
})
Convey("OnDoTimer", func() {
key := "OnDoTimer"
// 执行一个不存在的定时器,什么也不会发生
manager.OnDoTimer(key)
// 正常执行一个定时器
manager.AddTimer(key, 10 * time.Second, func() {
t.Logf("key: %s, time out", key)
})
manager.OnDoTimer(key)
// 执行后的定时器应该被清空
So(manager.HasTimer(key), ShouldEqual, false)
})
Convey("IncreaseLeftTime", func() {
key := "IncreaseLeftTime"
// 增加一个不存在的定时器时间,什么也不会发生
manager.IncreaseLeftTime(key, 1 * time.Second)
// 正常添加一个定时器,然后增加其剩余时间
manager.AddTimer(key, 1 * time.Second, func() {
t.Logf("key: %s, time out", key)
})
manager.IncreaseLeftTime(key, 1 * time.Second)
time.Sleep(2 * time.Second)
})
Convey("Reset", func() {
key := "Reset"
// 添加多个定时器
for i := 1; i <= 4; i++ {
manager.AddTimer(key + strconv.Itoa(i), 1 * time.Second, func() {
t.Errorf("key: %s, should not be execute", key + strconv.Itoa(i))
})
}
manager.Reset()
for i := 1; i <= 4; i++ {
So(manager.HasTimer(key + strconv.Itoa(i)), ShouldEqual, false)
}
time.Sleep(1 * time.Second)
})
})
}
|
package def
// Request : 场景执行部分返回,通常需要更换场景
type Request struct {
Continue bool
NextScene string
Terminate bool
ResetData bool
}
// DefaultRequest : 返回默认 Request,执行执行excute
var DefaultRequest = Request{
Continue: true,
NextScene: "",
Terminate: false,
ResetData: true,
}
|
package shell
import (
"fmt"
"os"
"os/exec"
"strings"
"github.com/gruntwork-io/go-commons/errors"
)
// Run the specified shell command with the specified arguments. Connect the command's stdin, stdout, and stderr to
// the currently running app.
func RunShellCommand(options *ShellOptions, command string, args ...string) error {
logCommand(options, command, args...)
cmd := exec.Command(command, args...)
// TODO: consider logging this via options.Logger
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
setCommandOptions(options, cmd)
return errors.WithStackTrace(cmd.Run())
}
// Run the specified shell command with the specified arguments. Return its stdout, stderr, and interleaved output as
// separate strings in a struct.
func RunShellCommandAndGetOutputStruct(options *ShellOptions, command string, args ...string) (*Output, error) {
return runShellCommand(options, false, command, args...)
}
// Run the specified shell command with the specified arguments. Return its stdout and stderr as a string
func RunShellCommandAndGetOutput(options *ShellOptions, command string, args ...string) (string, error) {
out, err := runShellCommand(options, false, command, args...)
return out.Combined(), err
}
// Run the specified shell command with the specified arguments. Return its interleaved stdout and stderr as a string
// and also stream stdout and stderr to the OS stdout/stderr
func RunShellCommandAndGetAndStreamOutput(options *ShellOptions, command string, args ...string) (string, error) {
out, err := runShellCommand(options, true, command, args...)
return out.Combined(), err
}
// Run the specified shell command with the specified arguments. Return its stdout as a string
func RunShellCommandAndGetStdout(options *ShellOptions, command string, args ...string) (string, error) {
out, err := runShellCommand(options, false, command, args...)
return out.Stdout(), err
}
// Run the specified shell command with the specified arguments. Return its stdout as a string and also stream stdout
// and stderr to the OS stdout/stderr
func RunShellCommandAndGetStdoutAndStreamOutput(options *ShellOptions, command string, args ...string) (string, error) {
out, err := runShellCommand(options, true, command, args...)
return out.Stdout(), err
}
// Run the specified shell command with the specified arguments. Return its stdout, stderr, and interleaved output as a
// struct and also stream stdout and stderr to the OS stdout/stderr
func RunShellCommandAndGetOutputStructAndStreamOutput(options *ShellOptions, command string, args ...string) (*Output, error) {
return runShellCommand(options, true, command, args...)
}
// Run the specified shell command with the specified arguments. Return its stdout and stderr as a string and also
// stream stdout and stderr to the OS stdout/stderr
func runShellCommand(options *ShellOptions, streamOutput bool, command string, args ...string) (*Output, error) {
logCommand(options, command, args...)
cmd := exec.Command(command, args...)
setCommandOptions(options, cmd)
cmd.Stdin = os.Stdin
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, errors.WithStackTrace(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, errors.WithStackTrace(err)
}
if err := cmd.Start(); err != nil {
return nil, errors.WithStackTrace(err)
}
output, err := readStdoutAndStderr(
options.Logger,
streamOutput,
stdout,
stderr,
)
if err != nil {
return output, err
}
err = cmd.Wait()
return output, errors.WithStackTrace(err)
}
func logCommand(options *ShellOptions, command string, args ...string) {
if options.SensitiveArgs {
options.Logger.Infof("Running command: %s (args redacted)", command)
} else {
options.Logger.Infof("Running command: %s %s", command, strings.Join(args, " "))
}
}
// Return true if the OS has the given command installed
func CommandInstalled(command string) bool {
_, err := exec.LookPath(command)
return err == nil
}
// CommandInstalledE returns an error if command is not installed
func CommandInstalledE(command string) error {
if commandExists := CommandInstalled(command); !commandExists {
err := fmt.Errorf("Command %s is not installed", command)
return errors.WithStackTrace(err)
}
return nil
}
// setCommandOptions takes the shell options and maps them to the configurations for the exec.Cmd object, applying them
// to the passed in Cmd object.
func setCommandOptions(options *ShellOptions, cmd *exec.Cmd) {
cmd.Dir = options.WorkingDir
cmd.Env = formatEnvVars(options)
}
// formatEnvVars takes environment variables encoded into ShellOptions and converts them to a format understood by
// exec.Command
func formatEnvVars(options *ShellOptions) []string {
env := os.Environ()
for key, value := range options.Env {
env = append(env, fmt.Sprintf("%s=%s", key, value))
}
return env
}
|
package samjung
import (
"fmt"
"os"
"encoding/binary"
"strconv"
)
type column struct {
pk uint64
name string
position string
}
func (r *Samjung) selectRow() error {
fmt.Print("pk: ")
pkStr, err := r.readLine()
if err != nil {
return err
}
pkLen := len(pkStr) - 1
pk, err := strconv.ParseUint(string(pkStr[:pkLen]), 10, 64)
if err != nil {
return err
}
err = r.selectOne(pk)
if err != nil {
return err
}
return nil
}
func (r *Samjung) selectOne(pk uint64) error {
v, ok := r.indexMap[pk]
if ok == false {
fmt.Println("Not found matched row..")
return nil
}
f, err := os.Open(r.baseDir+"/"+tableFile)
if err != nil {
return err
}
defer f.Close()
col, err := r.readRow(f, int64(v), false)
if err != nil {
return err
}
fmt.Printf("ID : %v, Name : %v, Position : %v\n", col.pk, col.name, col.position)
return nil
}
func (r *Samjung) readRow(f *os.File, offset int64, recursive bool) (column, error) {
// pk 위치
_, err := f.Seek(offset, 0)
if err != nil {
return column{}, err
}
pkBuf := make([]byte, 8)
n, err := f.Read(pkBuf)
if err != nil {
return column{}, err
}
if n != 8 {
return column{}, fmt.Errorf("Why not return 8 bytes?")
}
pk := binary.BigEndian.Uint64(pkBuf)
// name의 variable integer
offset = offset + int64(8)
_, err = f.Seek(offset, 0)
if err != nil {
return column{}, err
}
nameLenBuf := make([]byte, 10)
_, err = f.Read(nameLenBuf)
if err != nil {
return column{}, err
}
nameLen, varintLen := binary.Uvarint(nameLenBuf)
// name value
offset = offset + int64(varintLen)
_, err = f.Seek(offset, 0)
if err != nil {
return column{}, err
}
nameBuf := make([]byte, nameLen)
_, err = f.Read(nameBuf)
if err != nil {
return column{}, err
}
name := string(nameBuf)
// position의 variable integer
offset = offset + int64(nameLen)
_, err = f.Seek(offset, 0)
if err != nil {
return column{}, err
}
positionLenBuf := make([]byte, 10)
_, err = f.Read(positionLenBuf)
if err != nil {
return column{}, err
}
positionLen, varintLen := binary.Uvarint(positionLenBuf)
// position value
offset = offset + int64(varintLen)
_, err = f.Seek(offset, 0)
if err != nil {
return column{}, err
}
positionBuf := make([]byte, positionLen)
_, err = f.Read(positionBuf)
if err != nil {
return column{}, err
}
position := string(positionBuf)
offset = offset + int64(positionLen)
return column{pk, name, position}, nil
}
|
package controllers
import (
"context"
"encoding/json"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"log"
"net/http"
"reactgomongo/models"
)
func AddTodo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Methods", "POST")
SetHeaders(w)
var todo models.Todo
_ = json.NewDecoder(r.Body).Decode(&todo)
if todo.Title == ""{
http.Error(w, "Title is required", http.StatusBadRequest)
return
}
if todo.Description == ""{
http.Error(w, "Description is required", http.StatusBadRequest)
return
}
todo.Completed = false
insertTodo, err := todoscol.InsertOne(context.TODO(), todo)
if err != nil {
log.Fatal(err)
}
todo.ID = insertTodo.InsertedID.(primitive.ObjectID)
json.NewEncoder(w).Encode(todo)
}
func GetAllTodos(w http.ResponseWriter, r *http.Request){
SetHeaders(w)
w.Header().Set("Access-Control-Allow-Methods", "GET")
// Filter only for todos that are incomplete
filter := bson.M{"completed": false}
cur, err := todoscol.Find(context.TODO(), filter)
if err != nil {
log.Fatal(err)
}
results := make([]primitive.M, 0)
for cur.Next(context.Background()) {
var result bson.M
e := cur.Decode(&result)
if e != nil {
log.Fatal(e)
}
// fmt.Println("cur..>", cur, "result", reflect.TypeOf(result), reflect.TypeOf(result["_id"]))
results = append(results, result)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
cur.Close(context.TODO())
json.NewEncoder(w).Encode(results)
}
func GetTodo(w http.ResponseWriter, r *http.Request) {
SetHeaders(w)
w.Header().Set("Access-Control-Allow-Methods", "GET")
var todo models.Todo
params := mux.Vars(r)
id, _ := primitive.ObjectIDFromHex(params["id"])
filter := bson.M{"_id": id}
err := todoscol.FindOne(context.TODO(), filter).Decode(&todo)
if err != nil {
log.Fatal(err)
}
json.NewEncoder(w).Encode(todo)
}
func UpdateTodo(w http.ResponseWriter, r *http.Request) {
SetHeaders(w)
w.Header().Set("Access-Control-Allow-Methods", "PUT")
// Simulating putting response into struct
// Would normally get updates from here instead of setting completed to true
var todo models.Todo
_ = json.NewDecoder(r.Body).Decode(&todo)
params := mux.Vars(r)
id, _ := primitive.ObjectIDFromHex(params["id"])
filter := bson.M{"_id": id}
update := bson.D{
{"$set", bson.D{
{"completed", true},
}}}
_, err := todoscol.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
todo.ID = id
json.NewEncoder(w).Encode(todo)
}
func DeleteTodo(w http.ResponseWriter, r *http.Request){
SetHeaders(w)
w.Header().Set("Access-Control-Allow-Methods", "DELETE")
params := mux.Vars(r)
id, _ := primitive.ObjectIDFromHex(params["id"])
_, err := todoscol.DeleteOne(context.TODO(), bson.M{"_id": id})
if err != nil {
log.Fatal(err)
}
type Response struct {
Message string `json:"message" bson:"message"`
}
response := Response{
Message: "Successfully Deleted",
}
json.NewEncoder(w).Encode(response)
}
|
package gocyclo
import "fmt"
func function1(i int) {
if i < 0 {
fmt.Println("negative")
} else if i < 10 {
fmt.Println("between 0 and 9 inclusive")
} else if i < 20 {
fmt.Println("between 10 and 19 inclusive")
} else {
fmt.Println("20 or more")
}
}
func function2(i int) {
switch {
case i < 0:
fmt.Println("negative")
case i < 10:
fmt.Println("between 0 and 9 inclusive")
case i < 20:
fmt.Println("between 10 and 19 inclusive")
default:
fmt.Println("20 or more")
}
}
func function3(numbers []int) {
for _, i := range numbers {
switch {
case i < 0:
fmt.Println("negative")
case i < 10:
fmt.Println("between 0 and 9 inclusive")
case i < 20:
fmt.Println("between 10 and 19 inclusive")
default:
fmt.Println("20 or more")
}
}
}
|
package db
import (
"database/sql"
"fmt"
"log"
"sync"
_ "github.com/mattn/go-sqlite3"
)
type BotDB struct {
db *sql.DB
locker *sync.Mutex
}
// Open DB connection
func (db *BotDB) Open(dbPath string) {
var err error
db.db, err = sql.Open("sqlite3", dbPath)
if err != nil {
log.Fatal(err)
}
db.locker = &sync.Mutex{}
}
func (db *BotDB) Close() {
db.db.Close()
}
func (db *BotDB) QueryRow(query string, params ...interface{}) *sql.Row {
db.locker.Lock()
defer db.locker.Unlock()
stmt, err := db.db.Prepare(query)
if err != nil {
fmt.Println("Crashed while querying")
log.Fatal(err)
}
defer stmt.Close()
row := stmt.QueryRow(params...)
return row
}
func (db *BotDB) Update(query string, params ...interface{}) {
db.locker.Lock()
defer db.locker.Unlock()
stmt, err := db.db.Prepare(query)
if err != nil {
fmt.Println("Crashed while preparing")
log.Fatal(err)
}
defer stmt.Close()
_, err = stmt.Exec(params...)
if err != nil {
fmt.Println("Crashed while updating")
log.Fatal(err)
}
}
|
package gobase
import (
"errors"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var base Database
type Database interface {
Insert(data []interface{}) error
InsertBulk(data [][]interface{}) error
Find(key string) error
Update([]interface{}) error
UpdateBulk([]interface{}) error
}
type db struct {
dbase *gorm.DB
}
func (d db) Insert(data []interface{}) error {
return errors.New("Error Insert data to Database")
}
func (d db) InsertBulk(data [][]interface{}) error {
return errors.New("Error Insert bulk data to Database")
}
func (d db) Find(key string) error {
return errors.New("Error select data from Database")
}
func (d db) Update([]interface{}) error {
return errors.New("Error Update data into Database")
}
func (d db) UpdateBulk([]interface{}) error {
return errors.New("Error Update bulk data into Database")
}
type DBConnection interface {
SetConnection() error
}
func connecting(d Database) {
base = d
}
type host struct {
url string
port string
user string
password string
dbname string
}
func (h host) SetConnection() {
efDB, errConnectDB := gorm.Open("postgres", fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable", h.url, h.port, h.user, h.password, h.dbname))
var base db
if errConnectDB != nil {
base = db{
dbase: efDB,
}
connecting(nil)
}
connecting(base)
}
func Connect(url, port, user, password, name string) (Database, error) {
varHost := host{
url: url,
port: port,
user: user,
password: password,
dbname: name,
}
if url == "" || port == "" || user == "" || password == "" || name == "" {
return base, errors.New("Parameters must not empty")
}
varHost.SetConnection()
return base, nil
}
|
// Package pprofutil contains utilities for pprof HTTP handlers.
package pprofutil
import (
"net/http"
"net/http/pprof"
"net/url"
)
// BasePath is the default base path used by [RoutePprof].
//
// TODO(a.garipov): Consider adding the ability to configure the base path.
const BasePath = "/debug/pprof/"
// Router is the interface for HTTP routers, such as [*http.ServeMux].
type Router interface {
Handle(pattern string, h http.Handler)
}
// RouterFunc is a functional implementation of the [Router] interface.
type RouterFunc func(pattern string, h http.Handler)
// Handle implements the [Router] interface for RouterFunc.
func (f RouterFunc) Handle(pattern string, h http.Handler) {
f(pattern, h)
}
// RoutePprof adds all pprof handlers to r under the paths within [BasePath].
func RoutePprof(r Router) {
// See also profileSupportsDelta in src/net/http/pprof/pprof.go.
routes := []struct {
handler http.Handler
pattern string
}{{
handler: http.HandlerFunc(pprof.Index),
pattern: "/",
}, {
handler: pprof.Handler("allocs"),
pattern: "/allocs",
}, {
handler: pprof.Handler("block"),
pattern: "/block",
}, {
handler: http.HandlerFunc(pprof.Cmdline),
pattern: "/cmdline",
}, {
handler: pprof.Handler("goroutine"),
pattern: "/goroutine",
}, {
handler: pprof.Handler("heap"),
pattern: "/heap",
}, {
handler: pprof.Handler("mutex"),
pattern: "/mutex",
}, {
handler: http.HandlerFunc(pprof.Profile),
pattern: "/profile",
}, {
handler: http.HandlerFunc(pprof.Symbol),
pattern: "/symbol",
}, {
handler: pprof.Handler("threadcreate"),
pattern: "/threadcreate",
}, {
handler: http.HandlerFunc(pprof.Trace),
pattern: "/trace",
}}
for _, route := range routes {
pattern, err := url.JoinPath(BasePath, route.pattern)
if err != nil {
// Generally shouldn't happen, as the list of patterns is static.
panic(err)
}
r.Handle(pattern, route.handler)
}
}
|
package registration
import (
"crypto/rand"
"crypto/rsa"
"encoding/json"
"fmt"
"github.com/catmullet/Raithe/app/types"
"github.com/catmullet/Raithe/app/utils"
"github.com/labstack/echo"
)
var (
registeredAgents []types.SecurityToken
)
func getAgents() types.Agents {
return utils.GetAgentsFromList()
}
// RegisterAsAgent Registers an agent specified in the agents_list.json file.
func RegisterAsAgent(ctx echo.Context) error {
reg := types.Register{}
err := json.NewDecoder(ctx.Request().Body).Decode(®)
if err != nil {
fmt.Println(err)
}
agents := getAgents()
if isAlreadyRegistered(reg.AgentName) {
return ctx.JSON(200, types.RegisterResponse{Success: false, Message: "Agent is already Registered"})
}
for _, val := range agents.Agents {
if val == reg.AgentName {
token, _ := GeneratePrivateKey()
secToken := types.SecurityToken{AgentName: reg.AgentName, Token: token}
registeredAgents = append(registeredAgents, secToken)
return ctx.JSON(200, types.RegisterResponse{Success: true, SecurityToken: secToken})
}
}
return ctx.JSON(200, types.RegisterResponse{Success: false, Message: "Unrecognized Agent"})
}
func isAlreadyRegistered(agentName string) bool {
for _, val := range registeredAgents {
if val.AgentName == agentName {
return true
}
}
return false
}
// GeneratePrivateKey Returns key for the security token
func GeneratePrivateKey() (string, error) {
// Private Key generation
privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", privateKey.D.Bytes()), nil
}
// IsAgentRegistered Returns whether the agent has registered
func IsAgentRegistered(token types.SecurityToken) bool {
for _, val := range registeredAgents {
if val.Token == token.Token && val.AgentName == token.AgentName {
return true
}
}
return false
}
// InvalidateTokens Invalidates the tokens for agents, requiring a new registration from agents.
func InvalidateTokens(ctx echo.Context) error {
inv := types.InvalidateTokens{}
err := ctx.Bind(&inv)
if err != nil {
return err
}
if !IsAgentRegistered(inv.Token) {
return ctx.JSON(403, types.ValidateResponse{Success: false, Message: "Security Token Not Recognized"})
}
registeredAgents = []types.SecurityToken{}
return ctx.JSON(200, "Invalidated Tokens")
}
// DumpTokens Dumps all tokens to the console.
func DumpTokens(ctx echo.Context) error {
inv := types.InvalidateTokens{}
err := ctx.Bind(&inv)
if err != nil {
return err
}
if !IsAgentRegistered(inv.Token) {
return ctx.JSON(403, types.ValidateResponse{Success: false, Message: "Security Token Not Recognized"})
}
for _, val := range registeredAgents {
fmt.Println(val)
}
return ctx.JSON(200, "Tokens Have been dumped to logs")
}
|
package handlers
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
// GetValue is the HTTP handler to process incoming KV Get requests
// It gets the value from the in memory KV store
func GetValue(w http.ResponseWriter, r *http.Request) {
// Obtain the key from URL params
key := mux.Vars(r)["key"]
value, err := Store.Get(key)
if err != nil {
log.WithFields(log.Fields{"error": err}).Error("failed to get value")
w.WriteHeader(http.StatusInternalServerError)
return
}
log.WithFields(log.Fields{
"key": key,
"value": value,
}).Debug("successful getvalue")
// json encode response value
json.NewEncoder(w).Encode(value)
}
|
package main
import (
"fmt"
"github.com/bb-orz/gt/cmd"
"github.com/bb-orz/gt/utils"
"github.com/urfave/cli/v2"
"os"
"time"
)
func main() {
app := cli.NewApp()
app.Name = "gt"
app.Version = "2.1"
app.Compiled = time.Now()
app.Usage = "A generation tool of go app scaffold which base on bb-orz/goinfras."
app.UsageText = "gt [option] [command] [args]"
app.ArgsUsage = "[args and such]"
app.UseShortOptionHandling = true
app.Action = func(c *cli.Context) error {
fmt.Println("gt (goinfras tool) is a generation tool of go app scaffold which base on bb-orz/goinfras.")
return nil
}
app.Commands = []*cli.Command{
cmd.InitCommand(), // 初始化命令
cmd.ModelCommand(), // 创建数据库表模型命令
cmd.DomainCommand(), // 创建领域模块命令
cmd.ServiceCommand(), // 服务创建命令
cmd.RestfulCommand(), // Restful API创建命令
cmd.RPCCommand(), // RPC Service 创建命令
cmd.StarterCommand(), // Starter 创建命令
}
err := app.Run(os.Args)
if err != nil {
utils.CommandLogger.Fail(utils.AppCmd, err)
}
}
|
package main
import "fmt"
import "jikeshijian/L5/lib"
var block = "package"
func main() {
block := "function"
{
block := "inner"
fmt.Printf("The block is %s.\n", block)
}
fmt.Printf("The block is %s.\n", block)
lib.Print();
} |
/*
* Get the scheduled activities associated with a group.
*/
package main
import (
"encoding/hex"
"flag"
"fmt"
"os"
"path"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/grrtrr/clcv2/clcv2cli"
"github.com/grrtrr/exit"
"github.com/kr/pretty"
"github.com/olekukonko/tablewriter"
)
func main() {
var uuid string
var simple = flag.Bool("simple", false, "Use simple (debugging) output format")
var location = flag.String("l", "", "Location to use if using a Group-Name instead of a UUID")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [options] <Group Name or UUID>\n", path.Base(os.Args[0]))
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
os.Exit(1)
}
client, err := clcv2cli.NewCLIClient()
if err != nil {
exit.Fatal(err.Error())
}
if _, err := hex.DecodeString(flag.Arg(0)); err == nil {
uuid = flag.Arg(0)
} else if *location == "" {
exit.Errorf("Need a location argument (-l) if not using Group UUID (%s)", flag.Arg(0))
} else {
if grp, err := client.GetGroupByName(flag.Arg(0), *location); err != nil {
exit.Errorf("failed to resolve group name %q: %s", flag.Arg(0), err)
} else if grp == nil {
exit.Errorf("No group named %q was found in %s", flag.Arg(0), *location)
} else {
uuid = grp.Id
}
}
sa, err := client.GetGroupScheduledActivities(uuid)
if err != nil {
exit.Fatalf("failed to query billing details of group %s: %s", flag.Arg(0), err)
}
if *simple {
pretty.Println(sa)
} else {
table := tablewriter.NewWriter(os.Stdout)
table.SetAutoFormatHeaders(false)
table.SetAlignment(tablewriter.ALIGN_RIGHT)
table.SetAutoWrapText(false)
table.SetHeader([]string{"Type", "On?", "Exp?",
"Repeat", "Expire", "Begin", "Next", "#Count", "Days", "Modified",
})
for _, s := range sa {
var beginStr, nextStr string
modifiedStr := humanize.Time(s.ChangeInfo.ModifiedDate)
/* The ModifiedBy field can be an email address, or an API Key (hex string) */
if _, err := hex.DecodeString(s.ChangeInfo.ModifiedBy); err == nil {
modifiedStr += " via API Key"
} else {
modifiedStr += " by " + s.ChangeInfo.ModifiedBy
}
if s.BeginDateUtc.IsZero() {
beginStr = "never"
} else {
beginStr = s.BeginDateUtc.In(time.Local).Format("Mon 2 Jan 15:04 MST")
}
if s.NextOccurrenceDateUtc.IsZero() {
nextStr = "never"
} else {
nextStr = s.NextOccurrenceDateUtc.In(time.Local).Format("Mon 2 Jan 15:04 MST")
}
table.Append([]string{
s.Type, s.Status, fmt.Sprint(s.IsExpired),
s.Repeat, s.Expire, beginStr, nextStr,
fmt.Sprint(s.OccurrenceCount),
strings.Join(s.CustomWeeklyDays, "/"), modifiedStr,
})
}
table.Render()
}
}
|
//////////////////////////////////////////////////////////////////////////
//
// 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 (
"reflect"
"strconv"
"errors"
"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/openconfig/ygot/ygot"
log "github.com/golang/glog"
)
type PlatformApp struct {
path *PathInfo
reqData []byte
ygotRoot *ygot.GoStruct
ygotTarget *interface{}
eepromTs *db.TableSpec
eepromTable map[string]dbEntry
}
func init() {
log.Info("Init called for Platform module")
err := register("/openconfig-platform:components",
&appInfo{appType: reflect.TypeOf(PlatformApp{}),
ygotRootType: reflect.TypeOf(ocbinds.OpenconfigPlatform_Components{}),
isNative: false})
if err != nil {
log.Fatal("Register Platform app module with App Interface failed with error=", err)
}
err = addModel(&ModelData{Name: "openconfig-platform",
Org: "OpenConfig working group",
Ver: "1.0.2"})
if err != nil {
log.Fatal("Adding model data to appinterface failed with error=", err)
}
}
func (app *PlatformApp) initialize(data appData) {
log.Info("initialize:if:path =", data.path)
app.path = NewPathInfo(data.path)
app.reqData = data.payload
app.ygotRoot = data.ygotRoot
app.ygotTarget = data.ygotTarget
app.eepromTs = &db.TableSpec{Name: "EEPROM_INFO"}
}
func (app *PlatformApp) getAppRootObject() (*ocbinds.OpenconfigPlatform_Components) {
deviceObj := (*app.ygotRoot).(*ocbinds.Device)
return deviceObj.Components
}
func (app *PlatformApp) translateAction(dbs [db.MaxDB]*db.DB) error {
err := errors.New("Not supported")
return err
}
func (app *PlatformApp) translateSubscribe(req translateSubRequest) (translateSubResponse, error) {
return emptySubscribeResponse(req.path)
}
func (app *PlatformApp) processSubscribe(req processSubRequest) (processSubResponse, error) {
return processSubResponse{}, tlerr.New("not implemented")
}
func (app *PlatformApp) translateCreate(d *db.DB) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
err = errors.New("PlatformApp Not implemented, translateCreate")
return keys, err
}
func (app *PlatformApp) translateUpdate(d *db.DB) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
err = errors.New("PlatformApp Not implemented, translateUpdate")
return keys, err
}
func (app *PlatformApp) translateReplace(d *db.DB) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
err = errors.New("Not implemented PlatformApp translateReplace")
return keys, err
}
func (app *PlatformApp) translateDelete(d *db.DB) ([]db.WatchKeys, error) {
var err error
var keys []db.WatchKeys
err = errors.New("Not implemented PlatformApp translateDelete")
return keys, err
}
func (app *PlatformApp) translateGet(dbs [db.MaxDB]*db.DB) error {
var err error
log.Info("PlatformApp: translateGet - path: ", app.path.Path)
return err
}
func (app *PlatformApp) processCreate(d *db.DB) (SetResponse, error) {
var err error
var resp SetResponse
err = errors.New("Not implemented PlatformApp processCreate")
return resp, err
}
func (app *PlatformApp) processUpdate(d *db.DB) (SetResponse, error) {
var err error
var resp SetResponse
err = errors.New("Not implemented PlatformApp processUpdate")
return resp, err
}
func (app *PlatformApp) processReplace(d *db.DB) (SetResponse, error) {
var err error
var resp SetResponse
log.Info("processReplace:intf:path =", app.path)
err = errors.New("Not implemented, PlatformApp processReplace")
return resp, err
}
func (app *PlatformApp) processDelete(d *db.DB) (SetResponse, error) {
var err error
var resp SetResponse
err = errors.New("Not implemented PlatformApp processDelete")
return resp, err
}
func (app *PlatformApp) processGet(dbs [db.MaxDB]*db.DB) (GetResponse, error) {
pathInfo := app.path
log.Infof("Received GET for PlatformApp Template: %s ,path: %s, vars: %v",
pathInfo.Template, pathInfo.Path, pathInfo.Vars)
stateDb := dbs[db.StateDB]
var payload []byte
// Read eeprom info from DB
app.eepromTable = make(map[string]dbEntry)
tbl, derr := stateDb.GetTable(app.eepromTs)
if derr != nil {
log.Error("EEPROM_INFO table get failed!")
return GetResponse{Payload: payload}, derr
}
keys, _ := tbl.GetKeys()
for _, key := range keys {
e, kerr := tbl.GetEntry(key)
if kerr != nil {
log.Error("EEPROM_INFO entry get failed!")
return GetResponse{Payload: payload}, kerr
}
app.eepromTable[key.Get(0)] = dbEntry{entry: e}
}
targetUriPath, perr := getYangPathFromUri(app.path.Path)
if perr != nil {
log.Infof("getYangPathFromUri failed.")
return GetResponse{Payload: payload}, perr
}
if isSubtreeRequest(targetUriPath, "/openconfig-platform:components") {
return app.doGetSysEeprom()
}
err := errors.New("Not supported component")
return GetResponse{Payload: payload}, err
}
func (app *PlatformApp) processAction(dbs [db.MaxDB]*db.DB) (ActionResponse, error) {
var resp ActionResponse
err := errors.New("Not implemented")
return resp, err
}
///////////////////////////
/**
Structures to read syseeprom from redis-db
*/
type EepromDb struct {
Product_Name string
Part_Number string
Serial_Number string
Base_MAC_Address string
Manufacture_Date string
Device_Version string
Label_Revision string
Platform_Name string
ONIE_Version string
MAC_Addresses int
Manufacturer string
Manufacture_Country string
Vendor_Name string
Diag_Version string
Service_Tag string
Vendor_Extension string
Magic_Number int
Card_Type string
Hardware_Version string
Software_Version string
Model_Name string
}
func (app *PlatformApp) getEepromDbObj () (EepromDb){
log.Infof("parseEepromDb Enter")
var eepromDbObj EepromDb
for epItem, _ := range app.eepromTable {
e := app.eepromTable[epItem].entry
name := e.Get("Name")
switch name {
case "Device Version":
eepromDbObj.Device_Version = e.Get("Value")
case "Service Tag":
eepromDbObj.Service_Tag = e.Get("Value")
case "Vendor Extension":
eepromDbObj.Vendor_Extension = e.Get("Value")
case "Magic Number":
mag, _ := strconv.ParseInt(e.Get("Value"), 10, 64)
eepromDbObj.Magic_Number = int(mag)
case "Card Type":
eepromDbObj.Card_Type = e.Get("Value")
case "Hardware Version":
eepromDbObj.Hardware_Version = e.Get("Value")
case "Software Version":
eepromDbObj.Software_Version = e.Get("Value")
case "Model Name":
eepromDbObj.Model_Name = e.Get("Value")
case "ONIE Version":
eepromDbObj.ONIE_Version = e.Get("Value")
case "Serial Number":
eepromDbObj.Serial_Number = e.Get("Value")
case "Vendor Name":
eepromDbObj.Vendor_Name = e.Get("Value")
case "Manufacturer":
eepromDbObj.Manufacturer = e.Get("Value")
case "Manufacture Country":
eepromDbObj.Manufacture_Country = e.Get("Value")
case "Platform Name":
eepromDbObj.Platform_Name = e.Get("Value")
case "Diag Version":
eepromDbObj.Diag_Version = e.Get("Value")
case "Label Revision":
eepromDbObj.Label_Revision = e.Get("Value")
case "Part Number":
eepromDbObj.Part_Number = e.Get("Value")
case "Product Name":
eepromDbObj.Product_Name = e.Get("Value")
case "Base MAC Address":
eepromDbObj.Base_MAC_Address = e.Get("Value")
case "Manufacture Date":
eepromDbObj.Manufacture_Date = e.Get("Value")
case "MAC Addresses":
mac, _ := strconv.ParseInt(e.Get("Value"), 10, 16)
eepromDbObj.MAC_Addresses = int(mac)
}
}
return eepromDbObj
}
func (app *PlatformApp) getSysEepromFromDb (eeprom *ocbinds.OpenconfigPlatform_Components_Component_State, all bool) (error) {
log.Infof("getSysEepromFromDb Enter")
eepromDb := app.getEepromDbObj()
empty := false
removable := false
name := "System Eeprom"
location := "Slot 1"
if all == true {
eeprom.Empty = &empty
eeprom.Removable = &removable
eeprom.Name = &name
eeprom.OperStatus = ocbinds.OpenconfigPlatformTypes_COMPONENT_OPER_STATUS_ACTIVE
eeprom.Location = &location
if eepromDb.Product_Name != "" {
eeprom.Id = &eepromDb.Product_Name
}
if eepromDb.Part_Number != "" {
eeprom.PartNo = &eepromDb.Part_Number
}
if eepromDb.Serial_Number != "" {
eeprom.SerialNo = &eepromDb.Serial_Number
}
if eepromDb.Base_MAC_Address != "" {
}
if eepromDb.Manufacture_Date != "" {
eeprom.MfgDate = &eepromDb.Manufacture_Date
}
if eepromDb.Label_Revision != "" {
eeprom.HardwareVersion = &eepromDb.Label_Revision
}
if eepromDb.Platform_Name != "" {
eeprom.Description = &eepromDb.Platform_Name
}
if eepromDb.ONIE_Version != "" {
}
if eepromDb.MAC_Addresses != 0 {
}
if eepromDb.Manufacturer != "" {
eeprom.MfgName = &eepromDb.Manufacturer
}
if eepromDb.Manufacture_Country != "" {
}
if eepromDb.Vendor_Name != "" {
if eeprom.MfgName == nil {
eeprom.MfgName = &eepromDb.Vendor_Name
}
}
if eepromDb.Diag_Version != "" {
}
if eepromDb.Service_Tag != "" {
if eeprom.SerialNo == nil {
eeprom.SerialNo = &eepromDb.Service_Tag
}
}
if eepromDb.Hardware_Version != "" {
eeprom.HardwareVersion = &eepromDb.Hardware_Version
}
if eepromDb.Software_Version != "" {
eeprom.SoftwareVersion = &eepromDb.Software_Version
}
} else {
targetUriPath, _ := getYangPathFromUri(app.path.Path)
switch targetUriPath {
case "/openconfig-platform:components/component/state/name":
eeprom.Name = &name
case "/openconfig-platform:components/component/state/location":
eeprom.Location = &location
case "/openconfig-platform:components/component/state/empty":
eeprom.Empty = &empty
case "/openconfig-platform:components/component/state/removable":
eeprom.Removable = &removable
case "/openconfig-platform:components/component/state/oper-status":
eeprom.OperStatus = ocbinds.OpenconfigPlatformTypes_COMPONENT_OPER_STATUS_ACTIVE
case "/openconfig-platform:components/component/state/id":
if eepromDb.Product_Name != "" {
eeprom.Id = &eepromDb.Product_Name
}
case "/openconfig-platform:components/component/state/part-no":
if eepromDb.Part_Number != "" {
eeprom.PartNo = &eepromDb.Part_Number
}
case "/openconfig-platform:components/component/state/serial-no":
if eepromDb.Serial_Number != "" {
eeprom.SerialNo = &eepromDb.Serial_Number
}
if eepromDb.Service_Tag != "" {
if eeprom.SerialNo == nil {
eeprom.SerialNo = &eepromDb.Service_Tag
}
}
case "/openconfig-platform:components/component/state/mfg-date":
if eepromDb.Manufacture_Date != "" {
eeprom.MfgDate = &eepromDb.Manufacture_Date
}
case "/openconfig-platform:components/component/state/hardware-version":
if eepromDb.Label_Revision != "" {
eeprom.HardwareVersion = &eepromDb.Label_Revision
}
if eepromDb.Hardware_Version != "" {
if eeprom.HardwareVersion == nil {
eeprom.HardwareVersion = &eepromDb.Hardware_Version
}
}
case "/openconfig-platform:components/component/state/description":
if eepromDb.Platform_Name != "" {
eeprom.Description = &eepromDb.Platform_Name
}
case "/openconfig-platform:components/component/state/mfg-name":
if eepromDb.Manufacturer != "" {
eeprom.MfgName = &eepromDb.Manufacturer
}
if eepromDb.Vendor_Name != "" {
if eeprom.MfgName == nil {
eeprom.MfgName = &eepromDb.Vendor_Name
}
}
case "/openconfig-platform:components/component/state/software-version":
if eepromDb.Software_Version != "" {
eeprom.SoftwareVersion = &eepromDb.Software_Version
}
}
}
return nil
}
func (app *PlatformApp) doGetSysEeprom () (GetResponse, error) {
log.Infof("Preparing collection for system eeprom");
var payload []byte
var err error
pf_cpts := app.getAppRootObject()
targetUriPath, _ := getYangPathFromUri(app.path.Path)
switch targetUriPath {
case "/openconfig-platform:components":
pf_comp,_ := pf_cpts.NewComponent("System Eeprom")
ygot.BuildEmptyTree(pf_comp)
err = app.getSysEepromFromDb(pf_comp.State, true)
if err != nil {
return GetResponse{Payload: payload}, err
}
payload, err = dumpIetfJson((*app.ygotRoot).(*ocbinds.Device), true)
case "/openconfig-platform:components/component":
compName := app.path.Var("name")
if compName == "" {
pf_comp,_ := pf_cpts.NewComponent("System Eeprom")
ygot.BuildEmptyTree(pf_comp)
err = app.getSysEepromFromDb(pf_comp.State, true)
if err != nil {
return GetResponse{Payload: payload}, err
}
payload, err = dumpIetfJson(pf_cpts, false)
} else {
if compName != "System Eeprom" {
err = errors.New("Invalid component name")
}
pf_comp := pf_cpts.Component[compName]
if pf_comp != nil {
ygot.BuildEmptyTree(pf_comp)
err = app.getSysEepromFromDb(pf_comp.State, true)
if err != nil {
return GetResponse{Payload: payload}, err
}
payload, err = dumpIetfJson(pf_cpts.Component[compName], false)
} else {
err = errors.New("Invalid input component name")
}
}
case "/openconfig-platform:components/component/state":
compName := app.path.Var("name")
if compName != "" && compName == "System Eeprom" {
pf_comp := pf_cpts.Component[compName]
if pf_comp != nil {
ygot.BuildEmptyTree(pf_comp)
err = app.getSysEepromFromDb(pf_comp.State, true)
if err != nil {
return GetResponse{Payload: payload}, err
}
payload, err = dumpIetfJson(pf_cpts.Component[compName], false)
} else {
err = errors.New("Invalid input component name")
}
} else {
err = errors.New("Invalid component name ")
}
default:
if isSubtreeRequest(targetUriPath, "/openconfig-platform:components/component/state") {
compName := app.path.Var("name")
if compName == "" || compName != "System Eeprom" {
err = errors.New("Invalid input component name")
} else {
pf_comp := pf_cpts.Component[compName]
if pf_comp != nil {
ygot.BuildEmptyTree(pf_comp)
err = app.getSysEepromFromDb(pf_comp.State, false)
if err != nil {
return GetResponse{Payload: payload}, err
}
payload, err = dumpIetfJson(pf_cpts.Component[compName].State, false)
} else {
err = errors.New("Invalid input component name")
}
}
} else {
err = errors.New("Invalid Path")
}
}
return GetResponse{Payload: payload}, err
}
|
package server
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/henglory/Demo_Golang_v0.0.1/handler"
"github.com/henglory/Demo_Golang_v0.0.1/service"
"github.com/henglory/Demo_Golang_v0.0.1/spec"
)
func demo2(s service.Service, c *gin.Context) {
var req spec.Demo2Req
b, err := c.GetRawData()
if err != nil {
c.JSON(500, errorResponse{
StatusCode: 99,
StatusDesc: "MISS FORMAT",
Request: string(b),
})
return
}
err = json.Unmarshal(b, &req)
if err != nil {
c.JSON(500, errorResponse{
StatusCode: 99,
StatusDesc: "MISS FORMAT",
Request: string(b),
})
return
}
res := handler.Demo2(s, req)
c.JSON(200, res)
}
|
package jarviscrypto
import (
"fmt"
"math/big"
"github.com/fomichev/secp256k1"
)
// var secp256k1A *big.Int
// func init() {
// secp256k1A, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000000", 16)
// }
// /*** Modular Arithmetic ***/
// /* NOTE: Returning a new z each time below is very space inefficient, but the
// * alternate accumulator based design makes the point arithmetic functions look
// * absolutely hideous. I may still change this in the future. */
// // addMod computes z = (x + y) % p.
// func addMod(x *big.Int, y *big.Int, p *big.Int) (z *big.Int) {
// z = new(big.Int).Add(x, y)
// z.Mod(z, p)
// return z
// }
// // subMod computes z = (x - y) % p.
// func subMod(x *big.Int, y *big.Int, p *big.Int) (z *big.Int) {
// z = new(big.Int).Sub(x, y)
// z.Mod(z, p)
// return z
// }
// // mulMod computes z = (x * y) % p.
// func mulMod(x *big.Int, y *big.Int, p *big.Int) (z *big.Int) {
// n := new(big.Int).Set(x)
// z = big.NewInt(0)
// for i := 0; i < y.BitLen(); i++ {
// if y.Bit(i) == 1 {
// z = addMod(z, n, p)
// }
// n = addMod(n, n, p)
// }
// return z
// }
// // invMod computes z = (1/x) % p.
// func invMod(x *big.Int, p *big.Int) (z *big.Int) {
// z = new(big.Int).ModInverse(x, p)
// return z
// }
// // expMod computes z = (x^e) % p.
// func expMod(x *big.Int, y *big.Int, p *big.Int) (z *big.Int) {
// z = new(big.Int).Exp(x, y, p)
// return z
// }
// // sqrtMod computes z = sqrt(x) % p.
// func sqrtMod(x *big.Int, p *big.Int) (z *big.Int) {
// /* assert that p % 4 == 3 */
// if new(big.Int).Mod(p, big.NewInt(4)).Cmp(big.NewInt(3)) != 0 {
// panic("p is not equal to 3 mod 4!")
// }
// /* z = sqrt(x) % p = x^((p+1)/4) % p */
// /* e = (p+1)/4 */
// e := new(big.Int).Add(p, big.NewInt(1))
// e = e.Rsh(e, 2)
// z = expMod(x, e, p)
// return z
// }
// func isOdd(a *big.Int) bool {
// return a.Bit(0) == 1
// }
func decompressY(x *big.Int, ybit uint) (*big.Int, error) {
c := secp256k1.SECP256K1().Params()
// Y = +-sqrt(x^3 + B)
x3 := new(big.Int).Mul(x, x)
x3.Mul(x3, x)
x3.Add(x3, c.B)
x3.Mod(x3, c.P)
q := new(big.Int).Div(new(big.Int).Add(c.P,
big.NewInt(1)), big.NewInt(4))
// Now calculate sqrt mod p of x^3 + B
// This code used to do a full sqrt based on tonelli/shanks,
// but this was replaced by the algorithms referenced in
// https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294
y := new(big.Int).Exp(x3, q, c.P)
if ybit != y.Bit(0) {
y.Sub(c.P, y)
}
// Check that y is a square root of x^3 + B.
y2 := new(big.Int).Mul(y, y)
y2.Mod(y2, c.P)
if y2.Cmp(x3) != 0 {
return nil, fmt.Errorf("invalid square root")
}
// Verify that y-coord has expected parity.
if ybit != y.Bit(0) {
return nil, fmt.Errorf("ybit doesn't match oddness")
}
// if !c.IsOnCurve(x, y) {
// return nil, errors.New("IsOnCurve X and Y fail")
// }
return y, nil
// // y^2 = x^3 + b
// // y = sqrt(x^3 + b)
// var y, x3b big.Int
// x3b.Mul(x, x)
// x3b.Mul(&x3b, x)
// x3b.Add(&x3b, c.B)
// x3b.Mod(&x3b, c.P)
// y.ModSqrt(&x3b, c.P)
// if y.Bit(0) != ybit {
// y.Sub(c.P, &y)
// }
// if y.Bit(0) != ybit {
// return nil, errors.New("incorrectly encoded X and Y bit")
// }
// if !c.IsOnCurve(x, y) {
// return nil, errors.New("IsOnCurve X and Y fail")
// }
// return &y, nil
}
|
package learnfunc
func modifyArray(a[3]string)[3]string{
a[1] = "x"
return a
}
func modifySlice(a[]string)[]string{
a[1] = "i"
return a
}
func modifyComplexArray(a[3][]string)[3][]string{
a[1][1] = "s"
a[2] = []string{"o","p","q"}
return a
}
|
package cmds
import (
"fmt"
"github.com/pachyderm/pachyderm/src/client"
"github.com/pachyderm/pachyderm/src/client/enterprise"
"github.com/pachyderm/pachyderm/src/server/pkg/cmdutil"
"github.com/spf13/cobra"
)
// ActivateCmd returns a cobra.Command to activate the enterprise features of
// Pachyderm within a Pachyderm cluster. All repos will go from
// publicly-accessible to accessible only by the owner, who can subsequently add
// users
func ActivateCmd() *cobra.Command {
activate := &cobra.Command{
Use: "activate activation-code",
Short: "Activate the enterprise features of Pachyderm with an activation " +
"code",
Long: "Activate the enterprise features of Pachyderm with an activation " +
"code",
Run: cmdutil.RunFixedArgs(1, func(args []string) error {
activationCode := args[0]
c, err := client.NewOnUserMachine(true, "user")
if err != nil {
return fmt.Errorf("could not connect: %s", err.Error())
}
_, err = c.Enterprise.Activate(c.Ctx(),
&enterprise.ActivateRequest{ActivationCode: activationCode})
return err
}),
}
return activate
}
// GetStateCmd returns a cobra.Command to activate the enterprise features of
// Pachyderm within a Pachyderm cluster. All repos will go from
// publicly-accessible to accessible only by the owner, who can subsequently add
// users
func GetStateCmd() *cobra.Command {
getState := &cobra.Command{
Use: "get-state",
Short: "Check whether the Pachyderm cluster has enterprise features " +
"activated",
Long: "Check whether the Pachyderm cluster has enterprise features " +
"activated",
Run: cmdutil.Run(func(args []string) error {
c, err := client.NewOnUserMachine(true, "user")
if err != nil {
return fmt.Errorf("could not connect: %s", err.Error())
}
resp, err := c.Enterprise.GetState(c.Ctx(), &enterprise.GetStateRequest{})
if err != nil {
return err
}
fmt.Println(resp.State.String())
return nil
}),
}
return getState
}
// Cmds returns pachctl commands related to Pachyderm Enterprise
func Cmds() []*cobra.Command {
enterprise := &cobra.Command{
Use: "enterprise",
Short: "Enterprise commands enable Pachyderm Enterprise features",
Long: "Enterprise commands enable Pachyderm Enterprise features",
}
enterprise.AddCommand(ActivateCmd())
enterprise.AddCommand(GetStateCmd())
return []*cobra.Command{enterprise}
}
|
package main
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
"time"
)
func main() {
//router := gin.Default()
//http.ListenAndServe(":8080", router)
router := gin.Default()
gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)
}
v1 := router.Group("/v1")
{
v1.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"hello": "ok1",
})
})
}
v2 := router.Group("v2")
{
v2.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"hello": "ok2",
})
})
}
router.GET("/cookie", func(c *gin.Context) {
cookie, err := c.Cookie("gin_cookie")
if err != nil {
cookie = "NotSet"
c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
}
log.Printf("Cookie value: %s \n", cookie)
})
s := &http.Server{
Addr: ":8081",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}
|
package aoc2016
import (
"strings"
aoc "github.com/janreggie/aoc/internal"
)
// repertoire represents an array of dictionaries containing bytes
// and their frequency in a given column.
type repertoire []map[byte]uint
// newRepertoire creates a repertoire.
// Note that repertoire is a dynamic structure
// so length could be set to zero but reallocate will just add new elements.
func newRepertoire(length uint) repertoire {
rp := make([]map[byte]uint, length)
for ii := range rp {
rp[ii] = make(map[byte]uint)
}
return rp
}
// length returns the length of the repertoire.
func (rp repertoire) length() uint {
return uint(len(rp))
}
// reallocate reallocates the length of repertoire to a new length.
// If length is no more than rp.length, does nothing.
func (rp *repertoire) reallocate(length uint) {
if length <= rp.length() {
return
}
nrp := make(repertoire, length)
copy(nrp, *rp)
for ii := rp.length(); ii < length; ii++ {
nrp[ii] = make(map[byte]uint)
}
*rp = nrp // for some reason rp = &nrp doesn't work...
}
// add adds some string to the repertoire.
// For example, if input is "abc", then
// rp[0]['a']++, rp[1]['b']++, and rp[2]['c']++.
// Runs reallocate first.
func (rp *repertoire) add(input string) {
rp.reallocate(uint(len(input)))
for ii := range input {
(*rp)[ii][input[ii]]++
}
}
// mostCommon returns the error-corrected version of the message
// as described by Year 2016 Day 6 Part 1
// by checking the most common byte for each map.
func (rp repertoire) mostCommon() string {
var sb strings.Builder
for ii := range rp {
var record struct {
count uint
holder byte
}
for kk, vv := range rp[ii] {
if vv > record.count {
record.count = vv
record.holder = kk
}
}
sb.WriteByte(record.holder)
}
return sb.String()
}
// leastCommon returns the error-corrected version of the message
// as described by Year 2016 Day 6 Part 2
// by checking the least common byte for each map.
func (rp repertoire) leastCommon() string {
var sb strings.Builder
for ii := range rp {
var record struct {
count uint
holder byte
}
record.count = 1<<32 - 1 // highest possible
for kk, vv := range rp[ii] {
if vv < record.count {
record.count = vv
record.holder = kk
}
}
sb.WriteByte(record.holder)
}
return sb.String()
}
// Day06 solves the sixth day puzzle "Signals and Noise".
//
// Input
//
// A file containing some number of lines each having the same length
// as one another. For example:
//
// jsgoijzv
// iwgxjyxi
// yzeeuwoi
// gmgisfmd
// vdtezvan
// secfljup
// dngzexve
// xzanwmgd
// ziobunnv
//
// It is guaranteed that all lines have the same length
// and that there are no more than 600 lines.
func Day06(input string) (answer1, answer2 string, err error) {
rp := newRepertoire(0)
for _, line := range aoc.SplitLines(input) {
rp.add(line)
}
answer1 = rp.mostCommon()
answer2 = rp.leastCommon()
return
}
|
package middlewares
import (
"github.com/gin-gonic/gin"
metadata2 "github.com/owenliang/myf-go/app/middlewares/metadata"
)
func MetadataMiddleware() gin.HandlerFunc {
return func(context *gin.Context) {
metadata := &metadata2.MetaData{
Gin: context,
}
context.Set("metadata", metadata)
}
} |
package logic
import "time"
type SecRequest struct {
ProductId uint `form:"product_id" json:"product_id" binding:"required"`
UserId string `form:"user_id" json:"user_id" binding:"required"` // 用户ID
AccessTime time.Time `json:"access_time"` // 用户访问接口时间
ClientIp string `json:"client_ip"` // 客户端IP
CloseNotify <-chan bool `json:"-"`
ResultChan chan *SecResult `json:"-"`
}
type SecResult struct {
ProductId uint `json:"product_id"`
UserId string `json:"user_id"`
Code int `json:"code"` //状态码
}
|
package main
/**
https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
摩尔投票法
*/
func majorityElement(nums []int) int {
ans := 0
count := 0
for i :=0; i < len(nums); i ++ {
if count == 0 {
ans = nums[i]
}
if ans == nums[i] {
count ++
} else {
count --
}
}
return ans
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/11/16 8:58 下午
# @File : lt_148_排序链表.go
# @Description :
# @Attention :
*/
package offer
// 关键:
// 归并排序法 1. 先找到中点,然后找到左边和右边 2 最后再进行归并
func sortList(head *ListNode) *ListNode {
return sortListMerge1(head)
}
func sortListMerge1(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
mid := sortListMerge2FindMid(head)
tail := mid.Next
mid.Next = nil
left := sortListMerge1(head)
right := sortListMerge1(tail)
return sortListMerge3(left, right)
}
func sortListMerge2FindMid(node *ListNode) *ListNode {
fast := node.Next
slow := node
for nil != fast.Next && fast.Next.Next != nil {
fast = fast.Next.Next
slow = slow.Next
}
return slow
}
func sortListMerge3(l1, l2 *ListNode) *ListNode {
dumy := &ListNode{}
tmp := dumy
for nil != l1 && nil != l2 {
if l1.Val < l2.Val {
tmp.Next = l1
l1 = l1.Next
} else {
tmp.Next = l2
l2 = l2.Next
}
tmp = tmp.Next
}
if nil != l1 {
tmp.Next = l1
}
if nil != l2 {
tmp.Next = l2
}
return dumy.Next
}
|
package main
import (
"flag"
"fmt"
"log"
"os/exec"
"github.com/nickvanw/ircx"
"github.com/sorcix/irc"
)
var (
Version string
user = flag.String("user", "", "Twitch username")
pass = flag.String("pass", "", "Twitch OAuth token")
rate = flag.String("rate", "300", "TTS speech rate")
server = "irc.twitch.tv:6667"
queue = make(chan string)
)
func init() {
flag.Parse()
go func() {
for text := range queue {
Say(text)
}
}()
}
func main() {
bot := ircx.WithLogin(server, *user, *user, *pass)
if err := bot.Connect(); err != nil {
log.Panicln("Unable to dial IRC Server ", err)
}
RegisterHandlers(bot)
bot.HandleLoop()
log.Println("Exiting...")
}
func RegisterHandlers(bot *ircx.Bot) {
bot.HandleFunc(irc.RPL_WELCOME, RegisterConnect)
bot.HandleFunc(irc.PING, PingHandler)
bot.HandleFunc(irc.PRIVMSG, MsgHandler)
bot.HandleFunc(irc.JOIN, JoinHandler)
bot.HandleFunc(irc.PART, PartHandler)
}
func RegisterConnect(s ircx.Sender, m *irc.Message) {
channel := fmt.Sprintf("#%s", *user)
fmt.Println("Connected, joining", channel, "...")
s.Send(&irc.Message{
Command: irc.JOIN,
Params: []string{channel},
})
}
func JoinHandler(s ircx.Sender, m *irc.Message) {
queue <- fmt.Sprintf("%s has joined.", m.Prefix.Name)
}
func PartHandler(s ircx.Sender, m *irc.Message) {
queue <- fmt.Sprintf("%s has left.", m.Prefix.Name)
}
func MsgHandler(s ircx.Sender, m *irc.Message) {
queue <- m.Prefix.Name + ": " + m.Trailing
}
func Say(text string) {
path, err := exec.LookPath("say")
if err != nil {
log.Fatal("can't find say")
}
fmt.Println(text)
cmd := exec.Command(path, "-r", *rate, text)
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
}
func PingHandler(s ircx.Sender, m *irc.Message) {
s.Send(&irc.Message{
Command: irc.PONG,
Params: m.Params,
Trailing: m.Trailing,
})
}
|
package main
type ConfigTypes struct {
EmailSettings struct {
Email string `yaml:"email"`
Password string `yaml:"password"`
Name string `yaml:"name"`
ToEmail string `yaml:"to_email"`
} `yaml:"email_settings"`
MessageSettings struct {
Password string `yaml:"passcode"`
} `yaml:"message_settings"`
}
type Basic struct {
Message string `yaml:"message"`
}
type FailureMessage struct {
Time string `json:"time"`
Failure_type string `json:"type_of_failure"`
}
type MotionResponse struct {
File string `json:"file"`
Time string `json:"time"`
Severity int `json:"severity"`
}
type MonitorState struct {
State bool
}
type AlarmEvent struct {
User string `string:"user"`
State string `string:"state"`
}
type MapMessage struct {
message string
routing_key string
time string
valid bool
}
type DeviceFound struct {
Device_name string `json:"name"`
Ip_address string `json:"address"`
Status int `json:"status"`
}
type StatusFH struct {
LastFault string `json:"last_fault"`
}
type Fault struct {
Count int
Name string
}
const FAILURE string = "Failure.*"
const FAILURENETWORK string = "Failure.Network" //Level 5
const FAILURECOMPONENT string = "Failure.Component" //Level 3
const FAILUREACCESS string = "Failure.Access" //Level 6
const FAILURECAMERA string = "Failure.Camera" // Level 2
const MOTIONRESPONSE string = "Motion.Response"
const MOTIONEVENT string = "Motion.Event"
const DEVICEFOUND string = "Device.Found"
const MONITORSTATE string = "Monitor.State"
const CAMERASTART string = "Camera.Start"
const CAMERASTOP string = "Camera.Stop"
const ALARMEVENT string = "Alarm.Event"
const STATUSFH string = "Status.FH"
const EXCHANGENAME string = "topics"
const EXCHANGETYPE string = "topic"
const TIMEFORMAT string = "2006/01/02 15:04:05"
//
const DEVICE_TITLE string = "New Device - Network"
const DEVICEBLOCKED_MESSAGE string = "A blocked device has joined the\n" +
"network. Device name: "
const DEVICEUNKNOWN_MESSAGE string = "A unknown device has joined the\n" +
"network. Device name: "
const IPADDRESS string = ". IP Address: "
//
const ACTIVATE_TITLE string = "Alarm has been activated"
const ACT_MESSAGE string = "The alarm state has been changed.\n" +
"Please ensure that whoever enacted this " +
"was authorised to do so"
const DEACTIVATE_TITLE string = "Alarm has been deactivated"
//
const UPDATESTATE string = "Motion state changed"
const SERVERERROR string = "Server is failing to send"
const MOTIONMESSAGE string = "There was movement in the property. \n Head to the drive space and check the image taken by HouseGuard"
//
const GUIDUPDATE_TITLE string = "Daily GUID Key Inside"
const GUIDUPDATE_MESSAGE string = "Key: "
//
const BOTH_ROLE string = "BOTH"
const ADMIN_ROLE string = "ADMIN"
//
const STATEUPDATESEVERITY int = 2
const SERVERSEVERITY int = 4
const BLOCKED int = 2
const UNKNOWN int = 4
const FAILURECONVERT string = "Failed to convert"
const FAILUREPUBLISH string = "Failed to publish"
var SubscribedMessagesMap map[uint32]*MapMessage
var key_id uint32 = 0
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-11-09 09:50
# @File : lt_457_Circular_Array_Loop.go
# @Description :
# @Attention :
*/
package two_points
import "testing"
func Test_circularArrayLoop(t *testing.T) {
nums:=[]int{-1,2,1,2}
circularArrayLoop(nums)
}
func Test_setZero(t *testing.T) {
type args struct {
nums []int
i int
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setZero(tt.args.nums, tt.args.i)
})
}
}
|
// Copyright 2015-2018 trivago N.V.
//
// 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 awss3
import (
"fmt"
"strings"
"gollum/core/components"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/sirupsen/logrus"
)
const minUploadPartSize = 5 * 1024 * 1024
// BatchedFileWriterInterface extends the components.BatchedWriter interface for rotation checks
type BatchedFileWriterInterface interface {
components.BatchedWriter
GetUploadCount() int
}
// BatchedFileWriter is the file producer core.BatchedWriter implementation for the core.BatchedWriterAssembly
type BatchedFileWriter struct {
s3Client *s3.S3
s3Bucket string
s3SubFolder string
fileName string
logger logrus.FieldLogger
currentMultiPart int64 // current multipart count
s3UploadID *string // upload id from s3 for active file
totalSize int // total size off all writes to this writer (need for rotations)
completedParts []*s3.CompletedPart // collection of uploaded parts
// need separate byte buffer for min 5mb part uploads.
// @see http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadComplete.html
activeBuffer *s3ByteBuffer
}
// NewBatchedFileWriter returns a BatchedFileWriter instance
func NewBatchedFileWriter(s3Client *s3.S3, bucket string, fileName string, logger logrus.FieldLogger) BatchedFileWriter {
var s3Bucket, s3SubFolder string
if strings.Contains(bucket, "/") {
split := strings.SplitN(bucket, "/", 2)
s3Bucket, s3SubFolder = split[0], split[1]
} else {
s3Bucket = bucket
s3SubFolder = ""
}
batchedFileWriter := BatchedFileWriter{
s3Client: s3Client,
s3Bucket: s3Bucket,
s3SubFolder: s3SubFolder,
fileName: fileName,
logger: logger,
}
batchedFileWriter.init()
return batchedFileWriter
}
// init BatchedFileWriter struct
func (w *BatchedFileWriter) init() {
w.totalSize = 0
w.currentMultiPart = 0
w.completedParts = []*s3.CompletedPart{}
w.activeBuffer = newS3ByteBuffer()
w.createMultipartUpload()
}
// Write is part of the BatchedWriter interface and wraps the file.Write() implementation
func (w *BatchedFileWriter) Write(p []byte) (n int, err error) {
w.activeBuffer.Write(p)
if size, _ := w.activeBuffer.Size(); size >= minUploadPartSize {
w.logger.WithField("size", size).Debug("Buffer size ready for request")
w.uploadPartInput()
} else {
w.logger.WithField("size", size).Debug("Buffer size not big enough vor request")
}
length := len(p)
w.totalSize += length
return length, nil
}
// Name is part of the BatchedWriter interface and wraps the file.Name() implementation
func (w *BatchedFileWriter) Name() string {
return w.fileName
}
// Size is part of the BatchedWriter interface and wraps the file.Stat().Size() implementation
func (w *BatchedFileWriter) Size() int64 {
return int64(w.totalSize)
}
// IsAccessible is part of the BatchedWriter interface and check if the writer can access his file
func (w *BatchedFileWriter) IsAccessible() bool {
return w.s3UploadID != nil
}
// Close is part of the Close interface and handle the file close or compression call
func (w *BatchedFileWriter) Close() error {
// flush upload buffer
err := w.uploadPartInput()
w.completeMultipartUpload()
return err
}
// GetUploadCount returns the count of completed part uploads
func (w *BatchedFileWriter) GetUploadCount() int {
return len(w.completedParts)
}
func (w *BatchedFileWriter) getS3Path() string {
if w.s3SubFolder != "" {
return fmt.Sprintf("%s/%s", w.s3SubFolder, w.Name())
}
return w.Name()
}
func (w *BatchedFileWriter) uploadPartInput() (err error) {
if size, _ := w.activeBuffer.Size(); size < 1 {
w.logger.Warning("uploadPartInput(): empty buffer - no upload necessary")
return
}
// increase and get currentMultiPart count
w.currentMultiPart++
currentMultiPart := w.currentMultiPart
// get and reset active buffer
buffer := w.activeBuffer
w.activeBuffer = newS3ByteBuffer()
input := &s3.UploadPartInput{
Body: buffer,
Bucket: aws.String(w.s3Bucket),
Key: aws.String(w.getS3Path()),
PartNumber: aws.Int64(currentMultiPart),
UploadId: w.s3UploadID,
}
result, err := w.s3Client.UploadPart(input)
if err != nil {
w.logger.WithError(err).WithField("input", input).Errorf("Can't upload part '%d'", currentMultiPart)
return
}
w.logger.
WithField("part", currentMultiPart).
WithField("result", result).
Debug("upload part successfully send")
completedPart := s3.CompletedPart{}
completedPart.SetETag(*result.ETag)
completedPart.SetPartNumber(currentMultiPart)
w.completedParts = append(w.completedParts, &completedPart)
return
}
func (w *BatchedFileWriter) createMultipartUpload() {
input := &s3.CreateMultipartUploadInput{
Bucket: aws.String(w.s3Bucket),
Key: aws.String(w.getS3Path()),
}
result, err := w.s3Client.CreateMultipartUpload(input)
if err != nil {
w.logger.WithError(err).WithField("file", w.Name()).Error("Can't create multipart upload")
return
}
w.s3UploadID = result.UploadId
w.logger.WithField("uploadId", result.UploadId).Debug("successfully created multipart upload")
}
func (w *BatchedFileWriter) completeMultipartUpload() {
if w.currentMultiPart < 1 {
w.logger.Warning("No completeMultipartUpload request necessary for zero parts")
return
}
input := &s3.CompleteMultipartUploadInput{
Bucket: aws.String(w.s3Bucket),
Key: aws.String(w.getS3Path()),
UploadId: w.s3UploadID,
MultipartUpload: &s3.CompletedMultipartUpload{
Parts: w.completedParts,
},
}
result, err := w.s3Client.CompleteMultipartUpload(input)
if err != nil {
w.logger.WithError(err).
WithField("input", input).
WithField("response", result).
Error("Can't complete multipart upload")
return
}
w.logger.
WithField("location", *result.Location).
WithField("parts", len(w.completedParts)).
Debug("successfully completed MultipartUpload")
w.s3UploadID = nil // reset upload id
}
|
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package alpha
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"strings"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl/operations"
)
func (r *Feature) validate() error {
if err := dcl.RequiredParameter(r.Project, "Project"); err != nil {
return err
}
if err := dcl.RequiredParameter(r.Location, "Location"); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(r.ResourceState) {
if err := r.ResourceState.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.Spec) {
if err := r.Spec.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.State) {
if err := r.State.validate(); err != nil {
return err
}
}
return nil
}
func (r *FeatureResourceState) validate() error {
return nil
}
func (r *FeatureSpec) validate() error {
if !dcl.IsEmptyValueIndirect(r.Multiclusteringress) {
if err := r.Multiclusteringress.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.Cloudauditlogging) {
if err := r.Cloudauditlogging.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.Fleetobservability) {
if err := r.Fleetobservability.validate(); err != nil {
return err
}
}
return nil
}
func (r *FeatureSpecMulticlusteringress) validate() error {
if err := dcl.Required(r, "configMembership"); err != nil {
return err
}
return nil
}
func (r *FeatureSpecCloudauditlogging) validate() error {
return nil
}
func (r *FeatureSpecFleetobservability) validate() error {
if !dcl.IsEmptyValueIndirect(r.LoggingConfig) {
if err := r.LoggingConfig.validate(); err != nil {
return err
}
}
return nil
}
func (r *FeatureSpecFleetobservabilityLoggingConfig) validate() error {
if !dcl.IsEmptyValueIndirect(r.DefaultConfig) {
if err := r.DefaultConfig.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.FleetScopeLogsConfig) {
if err := r.FleetScopeLogsConfig.validate(); err != nil {
return err
}
}
return nil
}
func (r *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) validate() error {
return nil
}
func (r *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) validate() error {
return nil
}
func (r *FeatureState) validate() error {
if !dcl.IsEmptyValueIndirect(r.State) {
if err := r.State.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.Servicemesh) {
if err := r.Servicemesh.validate(); err != nil {
return err
}
}
return nil
}
func (r *FeatureStateState) validate() error {
return nil
}
func (r *FeatureStateServicemesh) validate() error {
return nil
}
func (r *FeatureStateServicemeshAnalysisMessages) validate() error {
if !dcl.IsEmptyValueIndirect(r.MessageBase) {
if err := r.MessageBase.validate(); err != nil {
return err
}
}
return nil
}
func (r *FeatureStateServicemeshAnalysisMessagesMessageBase) validate() error {
if !dcl.IsEmptyValueIndirect(r.Type) {
if err := r.Type.validate(); err != nil {
return err
}
}
return nil
}
func (r *FeatureStateServicemeshAnalysisMessagesMessageBaseType) validate() error {
return nil
}
func (r *Feature) basePath() string {
params := map[string]interface{}{}
return dcl.Nprintf("https://gkehub.googleapis.com/v1alpha/", params)
}
// featureApiOperation represents a mutable operation in the underlying REST
// API such as Create, Update, or Delete.
type featureApiOperation interface {
do(context.Context, *Feature, *Client) error
}
// newUpdateFeatureUpdateFeatureRequest creates a request for an
// Feature resource's UpdateFeature update type by filling in the update
// fields based on the intended state of the resource.
func newUpdateFeatureUpdateFeatureRequest(ctx context.Context, f *Feature, c *Client) (map[string]interface{}, error) {
req := map[string]interface{}{}
res := f
_ = res
if v := f.Labels; !dcl.IsEmptyValueIndirect(v) {
req["labels"] = v
}
if v, err := expandFeatureSpec(c, f.Spec, res); err != nil {
return nil, fmt.Errorf("error expanding Spec into spec: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["spec"] = v
}
return req, nil
}
// marshalUpdateFeatureUpdateFeatureRequest converts the update into
// the final JSON request body.
func marshalUpdateFeatureUpdateFeatureRequest(c *Client, m map[string]interface{}) ([]byte, error) {
return json.Marshal(m)
}
type updateFeatureUpdateFeatureOperation struct {
// If the update operation has the REQUIRES_APPLY_OPTIONS trait, this will be populated.
// Usually it will be nil - this is to prevent us from accidentally depending on apply
// options, which should usually be unnecessary.
ApplyOptions []dcl.ApplyOption
FieldDiffs []*dcl.FieldDiff
}
// do creates a request and sends it to the appropriate URL. In most operations,
// do will transcribe a subset of the resource into a request object and send a
// PUT request to a single URL.
func (c *Client) listFeatureRaw(ctx context.Context, r *Feature, pageToken string, pageSize int32) ([]byte, error) {
u, err := r.urlNormalized().listURL(c.Config.BasePath)
if err != nil {
return nil, err
}
m := make(map[string]string)
if pageToken != "" {
m["pageToken"] = pageToken
}
if pageSize != FeatureMaxPage {
m["pageSize"] = fmt.Sprintf("%v", pageSize)
}
u, err = dcl.AddQueryParams(u, m)
if err != nil {
return nil, err
}
resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider)
if err != nil {
return nil, err
}
defer resp.Response.Body.Close()
return ioutil.ReadAll(resp.Response.Body)
}
type listFeatureOperation struct {
Resources []map[string]interface{} `json:"resources"`
Token string `json:"nextPageToken"`
}
func (c *Client) listFeature(ctx context.Context, r *Feature, pageToken string, pageSize int32) ([]*Feature, string, error) {
b, err := c.listFeatureRaw(ctx, r, pageToken, pageSize)
if err != nil {
return nil, "", err
}
var m listFeatureOperation
if err := json.Unmarshal(b, &m); err != nil {
return nil, "", err
}
var l []*Feature
for _, v := range m.Resources {
res, err := unmarshalMapFeature(v, c, r)
if err != nil {
return nil, m.Token, err
}
res.Project = r.Project
res.Location = r.Location
l = append(l, res)
}
return l, m.Token, nil
}
func (c *Client) deleteAllFeature(ctx context.Context, f func(*Feature) bool, resources []*Feature) error {
var errors []string
for _, res := range resources {
if f(res) {
// We do not want deleteAll to fail on a deletion or else it will stop deleting other resources.
err := c.DeleteFeature(ctx, res)
if err != nil {
errors = append(errors, err.Error())
}
}
}
if len(errors) > 0 {
return fmt.Errorf("%v", strings.Join(errors, "\n"))
} else {
return nil
}
}
type deleteFeatureOperation struct{}
func (op *deleteFeatureOperation) do(ctx context.Context, r *Feature, c *Client) error {
r, err := c.GetFeature(ctx, r)
if err != nil {
if dcl.IsNotFound(err) {
c.Config.Logger.InfoWithContextf(ctx, "Feature not found, returning. Original error: %v", err)
return nil
}
c.Config.Logger.WarningWithContextf(ctx, "GetFeature checking for existence. error: %v", err)
return err
}
u, err := r.deleteURL(c.Config.BasePath)
if err != nil {
return err
}
// Delete should never have a body
body := &bytes.Buffer{}
resp, err := dcl.SendRequest(ctx, c.Config, "DELETE", u, body, c.Config.RetryProvider)
if err != nil {
return err
}
// wait for object to be deleted.
var o operations.StandardGCPOperation
if err := dcl.ParseResponse(resp.Response, &o); err != nil {
return err
}
if err := o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET"); err != nil {
return err
}
// We saw a race condition where for some successful delete operation, the Get calls returned resources for a short duration.
// This is the reason we are adding retry to handle that case.
retriesRemaining := 10
dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) {
_, err := c.GetFeature(ctx, r)
if dcl.IsNotFound(err) {
return nil, nil
}
if retriesRemaining > 0 {
retriesRemaining--
return &dcl.RetryDetails{}, dcl.OperationNotDone{}
}
return nil, dcl.NotDeletedError{ExistingResource: r}
}, c.Config.RetryProvider)
return nil
}
// Create operations are similar to Update operations, although they do not have
// specific request objects. The Create request object is the json encoding of
// the resource, which is modified by res.marshal to form the base request body.
type createFeatureOperation struct {
response map[string]interface{}
}
func (op *createFeatureOperation) FirstResponse() (map[string]interface{}, bool) {
return op.response, len(op.response) > 0
}
func (op *createFeatureOperation) do(ctx context.Context, r *Feature, c *Client) error {
c.Config.Logger.InfoWithContextf(ctx, "Attempting to create %v", r)
u, err := r.createURL(c.Config.BasePath)
if err != nil {
return err
}
req, err := r.marshal(c)
if err != nil {
return err
}
resp, err := dcl.SendRequest(ctx, c.Config, "POST", u, bytes.NewBuffer(req), c.Config.RetryProvider)
if err != nil {
return err
}
// wait for object to be created.
var o operations.StandardGCPOperation
if err := dcl.ParseResponse(resp.Response, &o); err != nil {
return err
}
if err := o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET"); err != nil {
c.Config.Logger.Warningf("Creation failed after waiting for operation: %v", err)
return err
}
c.Config.Logger.InfoWithContextf(ctx, "Successfully waited for operation")
op.response, _ = o.FirstResponse()
if _, err := c.GetFeature(ctx, r); err != nil {
c.Config.Logger.WarningWithContextf(ctx, "get returned error: %v", err)
return err
}
return nil
}
func (c *Client) getFeatureRaw(ctx context.Context, r *Feature) ([]byte, error) {
u, err := r.getURL(c.Config.BasePath)
if err != nil {
return nil, err
}
resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider)
if err != nil {
return nil, err
}
defer resp.Response.Body.Close()
b, err := ioutil.ReadAll(resp.Response.Body)
if err != nil {
return nil, err
}
return b, nil
}
func (c *Client) featureDiffsForRawDesired(ctx context.Context, rawDesired *Feature, opts ...dcl.ApplyOption) (initial, desired *Feature, diffs []*dcl.FieldDiff, err error) {
c.Config.Logger.InfoWithContext(ctx, "Fetching initial state...")
// First, let us see if the user provided a state hint. If they did, we will start fetching based on that.
var fetchState *Feature
if sh := dcl.FetchStateHint(opts); sh != nil {
if r, ok := sh.(*Feature); !ok {
c.Config.Logger.WarningWithContextf(ctx, "Initial state hint was of the wrong type; expected Feature, got %T", sh)
} else {
fetchState = r
}
}
if fetchState == nil {
fetchState = rawDesired
}
// 1.2: Retrieval of raw initial state from API
rawInitial, err := c.GetFeature(ctx, fetchState)
if rawInitial == nil {
if !dcl.IsNotFound(err) {
c.Config.Logger.WarningWithContextf(ctx, "Failed to retrieve whether a Feature resource already exists: %s", err)
return nil, nil, nil, fmt.Errorf("failed to retrieve Feature resource: %v", err)
}
c.Config.Logger.InfoWithContext(ctx, "Found that Feature resource did not exist.")
// Perform canonicalization to pick up defaults.
desired, err = canonicalizeFeatureDesiredState(rawDesired, rawInitial)
return nil, desired, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Found initial state for Feature: %v", rawInitial)
c.Config.Logger.InfoWithContextf(ctx, "Initial desired state for Feature: %v", rawDesired)
// The Get call applies postReadExtract and so the result may contain fields that are not part of API version.
if err := extractFeatureFields(rawInitial); err != nil {
return nil, nil, nil, err
}
// 1.3: Canonicalize raw initial state into initial state.
initial, err = canonicalizeFeatureInitialState(rawInitial, rawDesired)
if err != nil {
return nil, nil, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalized initial state for Feature: %v", initial)
// 1.4: Canonicalize raw desired state into desired state.
desired, err = canonicalizeFeatureDesiredState(rawDesired, rawInitial, opts...)
if err != nil {
return nil, nil, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalized desired state for Feature: %v", desired)
// 2.1: Comparison of initial and desired state.
diffs, err = diffFeature(c, desired, initial, opts...)
return initial, desired, diffs, err
}
func canonicalizeFeatureInitialState(rawInitial, rawDesired *Feature) (*Feature, error) {
// TODO(magic-modules-eng): write canonicalizer once relevant traits are added.
return rawInitial, nil
}
/*
* Canonicalizers
*
* These are responsible for converting either a user-specified config or a
* GCP API response to a standard format that can be used for difference checking.
* */
func canonicalizeFeatureDesiredState(rawDesired, rawInitial *Feature, opts ...dcl.ApplyOption) (*Feature, error) {
if rawInitial == nil {
// Since the initial state is empty, the desired state is all we have.
// We canonicalize the remaining nested objects with nil to pick up defaults.
rawDesired.ResourceState = canonicalizeFeatureResourceState(rawDesired.ResourceState, nil, opts...)
rawDesired.Spec = canonicalizeFeatureSpec(rawDesired.Spec, nil, opts...)
rawDesired.State = canonicalizeFeatureState(rawDesired.State, nil, opts...)
return rawDesired, nil
}
canonicalDesired := &Feature{}
if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawInitial.Name) {
canonicalDesired.Name = rawInitial.Name
} else {
canonicalDesired.Name = rawDesired.Name
}
if dcl.IsZeroValue(rawDesired.Labels) || (dcl.IsEmptyValueIndirect(rawDesired.Labels) && dcl.IsEmptyValueIndirect(rawInitial.Labels)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
canonicalDesired.Labels = rawInitial.Labels
} else {
canonicalDesired.Labels = rawDesired.Labels
}
canonicalDesired.Spec = canonicalizeFeatureSpec(rawDesired.Spec, rawInitial.Spec, opts...)
if dcl.NameToSelfLink(rawDesired.Project, rawInitial.Project) {
canonicalDesired.Project = rawInitial.Project
} else {
canonicalDesired.Project = rawDesired.Project
}
if dcl.NameToSelfLink(rawDesired.Location, rawInitial.Location) {
canonicalDesired.Location = rawInitial.Location
} else {
canonicalDesired.Location = rawDesired.Location
}
return canonicalDesired, nil
}
func canonicalizeFeatureNewState(c *Client, rawNew, rawDesired *Feature) (*Feature, error) {
if dcl.IsEmptyValueIndirect(rawNew.Name) && dcl.IsEmptyValueIndirect(rawDesired.Name) {
rawNew.Name = rawDesired.Name
} else {
if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawNew.Name) {
rawNew.Name = rawDesired.Name
}
}
if dcl.IsEmptyValueIndirect(rawNew.Labels) && dcl.IsEmptyValueIndirect(rawDesired.Labels) {
rawNew.Labels = rawDesired.Labels
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.ResourceState) && dcl.IsEmptyValueIndirect(rawDesired.ResourceState) {
rawNew.ResourceState = rawDesired.ResourceState
} else {
rawNew.ResourceState = canonicalizeNewFeatureResourceState(c, rawDesired.ResourceState, rawNew.ResourceState)
}
if dcl.IsEmptyValueIndirect(rawNew.Spec) && dcl.IsEmptyValueIndirect(rawDesired.Spec) {
rawNew.Spec = rawDesired.Spec
} else {
rawNew.Spec = canonicalizeNewFeatureSpec(c, rawDesired.Spec, rawNew.Spec)
}
if dcl.IsEmptyValueIndirect(rawNew.State) && dcl.IsEmptyValueIndirect(rawDesired.State) {
rawNew.State = rawDesired.State
} else {
rawNew.State = canonicalizeNewFeatureState(c, rawDesired.State, rawNew.State)
}
if dcl.IsEmptyValueIndirect(rawNew.CreateTime) && dcl.IsEmptyValueIndirect(rawDesired.CreateTime) {
rawNew.CreateTime = rawDesired.CreateTime
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.UpdateTime) && dcl.IsEmptyValueIndirect(rawDesired.UpdateTime) {
rawNew.UpdateTime = rawDesired.UpdateTime
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.DeleteTime) && dcl.IsEmptyValueIndirect(rawDesired.DeleteTime) {
rawNew.DeleteTime = rawDesired.DeleteTime
} else {
}
rawNew.Project = rawDesired.Project
rawNew.Location = rawDesired.Location
return rawNew, nil
}
func canonicalizeFeatureResourceState(des, initial *FeatureResourceState, opts ...dcl.ApplyOption) *FeatureResourceState {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureResourceState{}
return cDes
}
func canonicalizeFeatureResourceStateSlice(des, initial []FeatureResourceState, opts ...dcl.ApplyOption) []FeatureResourceState {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureResourceState, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureResourceState(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureResourceState, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureResourceState(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureResourceState(c *Client, des, nw *FeatureResourceState) *FeatureResourceState {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureResourceState while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.BoolCanonicalize(des.HasResources, nw.HasResources) {
nw.HasResources = des.HasResources
}
return nw
}
func canonicalizeNewFeatureResourceStateSet(c *Client, des, nw []FeatureResourceState) []FeatureResourceState {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureResourceState
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureResourceStateNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureResourceState(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureResourceStateSlice(c *Client, des, nw []FeatureResourceState) []FeatureResourceState {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureResourceState
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureResourceState(c, &d, &n))
}
return items
}
func canonicalizeFeatureSpec(des, initial *FeatureSpec, opts ...dcl.ApplyOption) *FeatureSpec {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureSpec{}
cDes.Multiclusteringress = canonicalizeFeatureSpecMulticlusteringress(des.Multiclusteringress, initial.Multiclusteringress, opts...)
cDes.Cloudauditlogging = canonicalizeFeatureSpecCloudauditlogging(des.Cloudauditlogging, initial.Cloudauditlogging, opts...)
cDes.Fleetobservability = canonicalizeFeatureSpecFleetobservability(des.Fleetobservability, initial.Fleetobservability, opts...)
return cDes
}
func canonicalizeFeatureSpecSlice(des, initial []FeatureSpec, opts ...dcl.ApplyOption) []FeatureSpec {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureSpec, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureSpec(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureSpec, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureSpec(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureSpec(c *Client, des, nw *FeatureSpec) *FeatureSpec {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureSpec while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.Multiclusteringress = canonicalizeNewFeatureSpecMulticlusteringress(c, des.Multiclusteringress, nw.Multiclusteringress)
nw.Cloudauditlogging = canonicalizeNewFeatureSpecCloudauditlogging(c, des.Cloudauditlogging, nw.Cloudauditlogging)
nw.Fleetobservability = canonicalizeNewFeatureSpecFleetobservability(c, des.Fleetobservability, nw.Fleetobservability)
return nw
}
func canonicalizeNewFeatureSpecSet(c *Client, des, nw []FeatureSpec) []FeatureSpec {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureSpec
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureSpecNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureSpec(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureSpecSlice(c *Client, des, nw []FeatureSpec) []FeatureSpec {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureSpec
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureSpec(c, &d, &n))
}
return items
}
func canonicalizeFeatureSpecMulticlusteringress(des, initial *FeatureSpecMulticlusteringress, opts ...dcl.ApplyOption) *FeatureSpecMulticlusteringress {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureSpecMulticlusteringress{}
if dcl.IsZeroValue(des.ConfigMembership) || (dcl.IsEmptyValueIndirect(des.ConfigMembership) && dcl.IsEmptyValueIndirect(initial.ConfigMembership)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.ConfigMembership = initial.ConfigMembership
} else {
cDes.ConfigMembership = des.ConfigMembership
}
return cDes
}
func canonicalizeFeatureSpecMulticlusteringressSlice(des, initial []FeatureSpecMulticlusteringress, opts ...dcl.ApplyOption) []FeatureSpecMulticlusteringress {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureSpecMulticlusteringress, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureSpecMulticlusteringress(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureSpecMulticlusteringress, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureSpecMulticlusteringress(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureSpecMulticlusteringress(c *Client, des, nw *FeatureSpecMulticlusteringress) *FeatureSpecMulticlusteringress {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureSpecMulticlusteringress while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
return nw
}
func canonicalizeNewFeatureSpecMulticlusteringressSet(c *Client, des, nw []FeatureSpecMulticlusteringress) []FeatureSpecMulticlusteringress {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureSpecMulticlusteringress
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureSpecMulticlusteringressNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureSpecMulticlusteringress(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureSpecMulticlusteringressSlice(c *Client, des, nw []FeatureSpecMulticlusteringress) []FeatureSpecMulticlusteringress {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureSpecMulticlusteringress
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureSpecMulticlusteringress(c, &d, &n))
}
return items
}
func canonicalizeFeatureSpecCloudauditlogging(des, initial *FeatureSpecCloudauditlogging, opts ...dcl.ApplyOption) *FeatureSpecCloudauditlogging {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureSpecCloudauditlogging{}
if dcl.StringArrayCanonicalize(des.AllowlistedServiceAccounts, initial.AllowlistedServiceAccounts) {
cDes.AllowlistedServiceAccounts = initial.AllowlistedServiceAccounts
} else {
cDes.AllowlistedServiceAccounts = des.AllowlistedServiceAccounts
}
return cDes
}
func canonicalizeFeatureSpecCloudauditloggingSlice(des, initial []FeatureSpecCloudauditlogging, opts ...dcl.ApplyOption) []FeatureSpecCloudauditlogging {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureSpecCloudauditlogging, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureSpecCloudauditlogging(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureSpecCloudauditlogging, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureSpecCloudauditlogging(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureSpecCloudauditlogging(c *Client, des, nw *FeatureSpecCloudauditlogging) *FeatureSpecCloudauditlogging {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureSpecCloudauditlogging while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringArrayCanonicalize(des.AllowlistedServiceAccounts, nw.AllowlistedServiceAccounts) {
nw.AllowlistedServiceAccounts = des.AllowlistedServiceAccounts
}
return nw
}
func canonicalizeNewFeatureSpecCloudauditloggingSet(c *Client, des, nw []FeatureSpecCloudauditlogging) []FeatureSpecCloudauditlogging {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureSpecCloudauditlogging
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureSpecCloudauditloggingNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureSpecCloudauditlogging(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureSpecCloudauditloggingSlice(c *Client, des, nw []FeatureSpecCloudauditlogging) []FeatureSpecCloudauditlogging {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureSpecCloudauditlogging
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureSpecCloudauditlogging(c, &d, &n))
}
return items
}
func canonicalizeFeatureSpecFleetobservability(des, initial *FeatureSpecFleetobservability, opts ...dcl.ApplyOption) *FeatureSpecFleetobservability {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureSpecFleetobservability{}
cDes.LoggingConfig = canonicalizeFeatureSpecFleetobservabilityLoggingConfig(des.LoggingConfig, initial.LoggingConfig, opts...)
return cDes
}
func canonicalizeFeatureSpecFleetobservabilitySlice(des, initial []FeatureSpecFleetobservability, opts ...dcl.ApplyOption) []FeatureSpecFleetobservability {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureSpecFleetobservability, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureSpecFleetobservability(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureSpecFleetobservability, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureSpecFleetobservability(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureSpecFleetobservability(c *Client, des, nw *FeatureSpecFleetobservability) *FeatureSpecFleetobservability {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureSpecFleetobservability while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.LoggingConfig = canonicalizeNewFeatureSpecFleetobservabilityLoggingConfig(c, des.LoggingConfig, nw.LoggingConfig)
return nw
}
func canonicalizeNewFeatureSpecFleetobservabilitySet(c *Client, des, nw []FeatureSpecFleetobservability) []FeatureSpecFleetobservability {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureSpecFleetobservability
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureSpecFleetobservabilityNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureSpecFleetobservability(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureSpecFleetobservabilitySlice(c *Client, des, nw []FeatureSpecFleetobservability) []FeatureSpecFleetobservability {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureSpecFleetobservability
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureSpecFleetobservability(c, &d, &n))
}
return items
}
func canonicalizeFeatureSpecFleetobservabilityLoggingConfig(des, initial *FeatureSpecFleetobservabilityLoggingConfig, opts ...dcl.ApplyOption) *FeatureSpecFleetobservabilityLoggingConfig {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureSpecFleetobservabilityLoggingConfig{}
cDes.DefaultConfig = canonicalizeFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(des.DefaultConfig, initial.DefaultConfig, opts...)
cDes.FleetScopeLogsConfig = canonicalizeFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(des.FleetScopeLogsConfig, initial.FleetScopeLogsConfig, opts...)
return cDes
}
func canonicalizeFeatureSpecFleetobservabilityLoggingConfigSlice(des, initial []FeatureSpecFleetobservabilityLoggingConfig, opts ...dcl.ApplyOption) []FeatureSpecFleetobservabilityLoggingConfig {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureSpecFleetobservabilityLoggingConfig, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureSpecFleetobservabilityLoggingConfig(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureSpecFleetobservabilityLoggingConfig, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureSpecFleetobservabilityLoggingConfig(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfig(c *Client, des, nw *FeatureSpecFleetobservabilityLoggingConfig) *FeatureSpecFleetobservabilityLoggingConfig {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureSpecFleetobservabilityLoggingConfig while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.DefaultConfig = canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, des.DefaultConfig, nw.DefaultConfig)
nw.FleetScopeLogsConfig = canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, des.FleetScopeLogsConfig, nw.FleetScopeLogsConfig)
return nw
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigSet(c *Client, des, nw []FeatureSpecFleetobservabilityLoggingConfig) []FeatureSpecFleetobservabilityLoggingConfig {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureSpecFleetobservabilityLoggingConfig
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureSpecFleetobservabilityLoggingConfigNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureSpecFleetobservabilityLoggingConfig(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigSlice(c *Client, des, nw []FeatureSpecFleetobservabilityLoggingConfig) []FeatureSpecFleetobservabilityLoggingConfig {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureSpecFleetobservabilityLoggingConfig
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureSpecFleetobservabilityLoggingConfig(c, &d, &n))
}
return items
}
func canonicalizeFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(des, initial *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig, opts ...dcl.ApplyOption) *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{}
if dcl.IsZeroValue(des.Mode) || (dcl.IsEmptyValueIndirect(des.Mode) && dcl.IsEmptyValueIndirect(initial.Mode)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Mode = initial.Mode
} else {
cDes.Mode = des.Mode
}
return cDes
}
func canonicalizeFeatureSpecFleetobservabilityLoggingConfigDefaultConfigSlice(des, initial []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig, opts ...dcl.ApplyOption) []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureSpecFleetobservabilityLoggingConfigDefaultConfig, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureSpecFleetobservabilityLoggingConfigDefaultConfig, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c *Client, des, nw *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureSpecFleetobservabilityLoggingConfigDefaultConfig while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
return nw
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigDefaultConfigSet(c *Client, des, nw []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureSpecFleetobservabilityLoggingConfigDefaultConfigNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigDefaultConfigSlice(c *Client, des, nw []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, &d, &n))
}
return items
}
func canonicalizeFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(des, initial *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, opts ...dcl.ApplyOption) *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{}
if dcl.IsZeroValue(des.Mode) || (dcl.IsEmptyValueIndirect(des.Mode) && dcl.IsEmptyValueIndirect(initial.Mode)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Mode = initial.Mode
} else {
cDes.Mode = des.Mode
}
return cDes
}
func canonicalizeFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigSlice(des, initial []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, opts ...dcl.ApplyOption) []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c *Client, des, nw *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
return nw
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigSet(c *Client, des, nw []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigSlice(c *Client, des, nw []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, &d, &n))
}
return items
}
func canonicalizeFeatureState(des, initial *FeatureState, opts ...dcl.ApplyOption) *FeatureState {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureState{}
return cDes
}
func canonicalizeFeatureStateSlice(des, initial []FeatureState, opts ...dcl.ApplyOption) []FeatureState {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureState, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureState(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureState, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureState(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureState(c *Client, des, nw *FeatureState) *FeatureState {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureState while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.State = canonicalizeNewFeatureStateState(c, des.State, nw.State)
nw.Servicemesh = canonicalizeNewFeatureStateServicemesh(c, des.Servicemesh, nw.Servicemesh)
return nw
}
func canonicalizeNewFeatureStateSet(c *Client, des, nw []FeatureState) []FeatureState {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureState
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureStateNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureState(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureStateSlice(c *Client, des, nw []FeatureState) []FeatureState {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureState
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureState(c, &d, &n))
}
return items
}
func canonicalizeFeatureStateState(des, initial *FeatureStateState, opts ...dcl.ApplyOption) *FeatureStateState {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureStateState{}
return cDes
}
func canonicalizeFeatureStateStateSlice(des, initial []FeatureStateState, opts ...dcl.ApplyOption) []FeatureStateState {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureStateState, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureStateState(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureStateState, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureStateState(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureStateState(c *Client, des, nw *FeatureStateState) *FeatureStateState {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureStateState while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Description, nw.Description) {
nw.Description = des.Description
}
if dcl.StringCanonicalize(des.UpdateTime, nw.UpdateTime) {
nw.UpdateTime = des.UpdateTime
}
return nw
}
func canonicalizeNewFeatureStateStateSet(c *Client, des, nw []FeatureStateState) []FeatureStateState {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureStateState
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureStateStateNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureStateState(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureStateStateSlice(c *Client, des, nw []FeatureStateState) []FeatureStateState {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureStateState
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureStateState(c, &d, &n))
}
return items
}
func canonicalizeFeatureStateServicemesh(des, initial *FeatureStateServicemesh, opts ...dcl.ApplyOption) *FeatureStateServicemesh {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureStateServicemesh{}
return cDes
}
func canonicalizeFeatureStateServicemeshSlice(des, initial []FeatureStateServicemesh, opts ...dcl.ApplyOption) []FeatureStateServicemesh {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureStateServicemesh, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureStateServicemesh(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureStateServicemesh, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureStateServicemesh(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureStateServicemesh(c *Client, des, nw *FeatureStateServicemesh) *FeatureStateServicemesh {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureStateServicemesh while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.AnalysisMessages = canonicalizeNewFeatureStateServicemeshAnalysisMessagesSlice(c, des.AnalysisMessages, nw.AnalysisMessages)
return nw
}
func canonicalizeNewFeatureStateServicemeshSet(c *Client, des, nw []FeatureStateServicemesh) []FeatureStateServicemesh {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureStateServicemesh
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureStateServicemeshNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureStateServicemesh(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureStateServicemeshSlice(c *Client, des, nw []FeatureStateServicemesh) []FeatureStateServicemesh {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureStateServicemesh
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureStateServicemesh(c, &d, &n))
}
return items
}
func canonicalizeFeatureStateServicemeshAnalysisMessages(des, initial *FeatureStateServicemeshAnalysisMessages, opts ...dcl.ApplyOption) *FeatureStateServicemeshAnalysisMessages {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureStateServicemeshAnalysisMessages{}
return cDes
}
func canonicalizeFeatureStateServicemeshAnalysisMessagesSlice(des, initial []FeatureStateServicemeshAnalysisMessages, opts ...dcl.ApplyOption) []FeatureStateServicemeshAnalysisMessages {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureStateServicemeshAnalysisMessages, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureStateServicemeshAnalysisMessages(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureStateServicemeshAnalysisMessages, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureStateServicemeshAnalysisMessages(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessages(c *Client, des, nw *FeatureStateServicemeshAnalysisMessages) *FeatureStateServicemeshAnalysisMessages {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureStateServicemeshAnalysisMessages while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.MessageBase = canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBase(c, des.MessageBase, nw.MessageBase)
if dcl.StringCanonicalize(des.Description, nw.Description) {
nw.Description = des.Description
}
if dcl.StringArrayCanonicalize(des.ResourcePaths, nw.ResourcePaths) {
nw.ResourcePaths = des.ResourcePaths
}
return nw
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessagesSet(c *Client, des, nw []FeatureStateServicemeshAnalysisMessages) []FeatureStateServicemeshAnalysisMessages {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureStateServicemeshAnalysisMessages
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureStateServicemeshAnalysisMessagesNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureStateServicemeshAnalysisMessages(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessagesSlice(c *Client, des, nw []FeatureStateServicemeshAnalysisMessages) []FeatureStateServicemeshAnalysisMessages {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureStateServicemeshAnalysisMessages
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureStateServicemeshAnalysisMessages(c, &d, &n))
}
return items
}
func canonicalizeFeatureStateServicemeshAnalysisMessagesMessageBase(des, initial *FeatureStateServicemeshAnalysisMessagesMessageBase, opts ...dcl.ApplyOption) *FeatureStateServicemeshAnalysisMessagesMessageBase {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureStateServicemeshAnalysisMessagesMessageBase{}
return cDes
}
func canonicalizeFeatureStateServicemeshAnalysisMessagesMessageBaseSlice(des, initial []FeatureStateServicemeshAnalysisMessagesMessageBase, opts ...dcl.ApplyOption) []FeatureStateServicemeshAnalysisMessagesMessageBase {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureStateServicemeshAnalysisMessagesMessageBase, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureStateServicemeshAnalysisMessagesMessageBase(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureStateServicemeshAnalysisMessagesMessageBase, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureStateServicemeshAnalysisMessagesMessageBase(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBase(c *Client, des, nw *FeatureStateServicemeshAnalysisMessagesMessageBase) *FeatureStateServicemeshAnalysisMessagesMessageBase {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureStateServicemeshAnalysisMessagesMessageBase while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.Type = canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBaseType(c, des.Type, nw.Type)
if dcl.StringCanonicalize(des.DocumentationUrl, nw.DocumentationUrl) {
nw.DocumentationUrl = des.DocumentationUrl
}
return nw
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBaseSet(c *Client, des, nw []FeatureStateServicemeshAnalysisMessagesMessageBase) []FeatureStateServicemeshAnalysisMessagesMessageBase {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureStateServicemeshAnalysisMessagesMessageBase
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureStateServicemeshAnalysisMessagesMessageBaseNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBase(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBaseSlice(c *Client, des, nw []FeatureStateServicemeshAnalysisMessagesMessageBase) []FeatureStateServicemeshAnalysisMessagesMessageBase {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureStateServicemeshAnalysisMessagesMessageBase
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBase(c, &d, &n))
}
return items
}
func canonicalizeFeatureStateServicemeshAnalysisMessagesMessageBaseType(des, initial *FeatureStateServicemeshAnalysisMessagesMessageBaseType, opts ...dcl.ApplyOption) *FeatureStateServicemeshAnalysisMessagesMessageBaseType {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &FeatureStateServicemeshAnalysisMessagesMessageBaseType{}
return cDes
}
func canonicalizeFeatureStateServicemeshAnalysisMessagesMessageBaseTypeSlice(des, initial []FeatureStateServicemeshAnalysisMessagesMessageBaseType, opts ...dcl.ApplyOption) []FeatureStateServicemeshAnalysisMessagesMessageBaseType {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]FeatureStateServicemeshAnalysisMessagesMessageBaseType, 0, len(des))
for _, d := range des {
cd := canonicalizeFeatureStateServicemeshAnalysisMessagesMessageBaseType(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]FeatureStateServicemeshAnalysisMessagesMessageBaseType, 0, len(des))
for i, d := range des {
cd := canonicalizeFeatureStateServicemeshAnalysisMessagesMessageBaseType(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBaseType(c *Client, des, nw *FeatureStateServicemeshAnalysisMessagesMessageBaseType) *FeatureStateServicemeshAnalysisMessagesMessageBaseType {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for FeatureStateServicemeshAnalysisMessagesMessageBaseType while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.DisplayName, nw.DisplayName) {
nw.DisplayName = des.DisplayName
}
if dcl.StringCanonicalize(des.Code, nw.Code) {
nw.Code = des.Code
}
return nw
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBaseTypeSet(c *Client, des, nw []FeatureStateServicemeshAnalysisMessagesMessageBaseType) []FeatureStateServicemeshAnalysisMessagesMessageBaseType {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []FeatureStateServicemeshAnalysisMessagesMessageBaseType
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareFeatureStateServicemeshAnalysisMessagesMessageBaseTypeNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBaseType(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBaseTypeSlice(c *Client, des, nw []FeatureStateServicemeshAnalysisMessagesMessageBaseType) []FeatureStateServicemeshAnalysisMessagesMessageBaseType {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []FeatureStateServicemeshAnalysisMessagesMessageBaseType
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewFeatureStateServicemeshAnalysisMessagesMessageBaseType(c, &d, &n))
}
return items
}
// The differ returns a list of diffs, along with a list of operations that should be taken
// to remedy them. Right now, it does not attempt to consolidate operations - if several
// fields can be fixed with a patch update, it will perform the patch several times.
// Diffs on some fields will be ignored if the `desired` state has an empty (nil)
// value. This empty value indicates that the user does not care about the state for
// the field. Empty fields on the actual object will cause diffs.
// TODO(magic-modules-eng): for efficiency in some resources, add batching.
func diffFeature(c *Client, desired, actual *Feature, opts ...dcl.ApplyOption) ([]*dcl.FieldDiff, error) {
if desired == nil || actual == nil {
return nil, fmt.Errorf("nil resource passed to diff - always a programming error: %#v, %#v", desired, actual)
}
c.Config.Logger.Infof("Diff function called with desired state: %v", desired)
c.Config.Logger.Infof("Diff function called with actual state: %v", actual)
var fn dcl.FieldName
var newDiffs []*dcl.FieldDiff
// New style diffs.
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Labels, actual.Labels, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("Labels")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.ResourceState, actual.ResourceState, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareFeatureResourceStateNewStyle, EmptyObject: EmptyFeatureResourceState, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("ResourceState")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Spec, actual.Spec, dcl.DiffInfo{ObjectFunction: compareFeatureSpecNewStyle, EmptyObject: EmptyFeatureSpec, OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("Spec")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.State, actual.State, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareFeatureStateNewStyle, EmptyObject: EmptyFeatureState, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("State")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.CreateTime, actual.CreateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("CreateTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.UpdateTime, actual.UpdateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("UpdateTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.DeleteTime, actual.DeleteTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("DeleteTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Project, actual.Project, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Project")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Location, actual.Location, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Location")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if len(newDiffs) > 0 {
c.Config.Logger.Infof("Diff function found diffs: %v", newDiffs)
}
return newDiffs, nil
}
func compareFeatureResourceStateNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureResourceState)
if !ok {
desiredNotPointer, ok := d.(FeatureResourceState)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureResourceState or *FeatureResourceState", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureResourceState)
if !ok {
actualNotPointer, ok := a.(FeatureResourceState)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureResourceState", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.State, actual.State, dcl.DiffInfo{OutputOnly: true, Type: "EnumType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("State")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.HasResources, actual.HasResources, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("HasResources")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureSpecNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureSpec)
if !ok {
desiredNotPointer, ok := d.(FeatureSpec)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpec or *FeatureSpec", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureSpec)
if !ok {
actualNotPointer, ok := a.(FeatureSpec)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpec", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Multiclusteringress, actual.Multiclusteringress, dcl.DiffInfo{ObjectFunction: compareFeatureSpecMulticlusteringressNewStyle, EmptyObject: EmptyFeatureSpecMulticlusteringress, OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("Multiclusteringress")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Cloudauditlogging, actual.Cloudauditlogging, dcl.DiffInfo{ObjectFunction: compareFeatureSpecCloudauditloggingNewStyle, EmptyObject: EmptyFeatureSpecCloudauditlogging, OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("Cloudauditlogging")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Fleetobservability, actual.Fleetobservability, dcl.DiffInfo{ObjectFunction: compareFeatureSpecFleetobservabilityNewStyle, EmptyObject: EmptyFeatureSpecFleetobservability, OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("Fleetobservability")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureSpecMulticlusteringressNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureSpecMulticlusteringress)
if !ok {
desiredNotPointer, ok := d.(FeatureSpecMulticlusteringress)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecMulticlusteringress or *FeatureSpecMulticlusteringress", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureSpecMulticlusteringress)
if !ok {
actualNotPointer, ok := a.(FeatureSpecMulticlusteringress)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecMulticlusteringress", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.ConfigMembership, actual.ConfigMembership, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("ConfigMembership")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureSpecCloudauditloggingNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureSpecCloudauditlogging)
if !ok {
desiredNotPointer, ok := d.(FeatureSpecCloudauditlogging)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecCloudauditlogging or *FeatureSpecCloudauditlogging", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureSpecCloudauditlogging)
if !ok {
actualNotPointer, ok := a.(FeatureSpecCloudauditlogging)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecCloudauditlogging", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.AllowlistedServiceAccounts, actual.AllowlistedServiceAccounts, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("AllowlistedServiceAccounts")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureSpecFleetobservabilityNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureSpecFleetobservability)
if !ok {
desiredNotPointer, ok := d.(FeatureSpecFleetobservability)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecFleetobservability or *FeatureSpecFleetobservability", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureSpecFleetobservability)
if !ok {
actualNotPointer, ok := a.(FeatureSpecFleetobservability)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecFleetobservability", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.LoggingConfig, actual.LoggingConfig, dcl.DiffInfo{ObjectFunction: compareFeatureSpecFleetobservabilityLoggingConfigNewStyle, EmptyObject: EmptyFeatureSpecFleetobservabilityLoggingConfig, OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("LoggingConfig")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureSpecFleetobservabilityLoggingConfigNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureSpecFleetobservabilityLoggingConfig)
if !ok {
desiredNotPointer, ok := d.(FeatureSpecFleetobservabilityLoggingConfig)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecFleetobservabilityLoggingConfig or *FeatureSpecFleetobservabilityLoggingConfig", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureSpecFleetobservabilityLoggingConfig)
if !ok {
actualNotPointer, ok := a.(FeatureSpecFleetobservabilityLoggingConfig)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecFleetobservabilityLoggingConfig", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.DefaultConfig, actual.DefaultConfig, dcl.DiffInfo{ObjectFunction: compareFeatureSpecFleetobservabilityLoggingConfigDefaultConfigNewStyle, EmptyObject: EmptyFeatureSpecFleetobservabilityLoggingConfigDefaultConfig, OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("DefaultConfig")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.FleetScopeLogsConfig, actual.FleetScopeLogsConfig, dcl.DiffInfo{ObjectFunction: compareFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigNewStyle, EmptyObject: EmptyFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("FleetScopeLogsConfig")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureSpecFleetobservabilityLoggingConfigDefaultConfigNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureSpecFleetobservabilityLoggingConfigDefaultConfig)
if !ok {
desiredNotPointer, ok := d.(FeatureSpecFleetobservabilityLoggingConfigDefaultConfig)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecFleetobservabilityLoggingConfigDefaultConfig or *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureSpecFleetobservabilityLoggingConfigDefaultConfig)
if !ok {
actualNotPointer, ok := a.(FeatureSpecFleetobservabilityLoggingConfigDefaultConfig)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecFleetobservabilityLoggingConfigDefaultConfig", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Mode, actual.Mode, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("Mode")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig)
if !ok {
desiredNotPointer, ok := d.(FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig or *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig)
if !ok {
actualNotPointer, ok := a.(FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Mode, actual.Mode, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateFeatureUpdateFeatureOperation")}, fn.AddNest("Mode")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureStateNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureState)
if !ok {
desiredNotPointer, ok := d.(FeatureState)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureState or *FeatureState", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureState)
if !ok {
actualNotPointer, ok := a.(FeatureState)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureState", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.State, actual.State, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareFeatureStateStateNewStyle, EmptyObject: EmptyFeatureStateState, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("State")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Servicemesh, actual.Servicemesh, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareFeatureStateServicemeshNewStyle, EmptyObject: EmptyFeatureStateServicemesh, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Servicemesh")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureStateStateNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureStateState)
if !ok {
desiredNotPointer, ok := d.(FeatureStateState)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateState or *FeatureStateState", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureStateState)
if !ok {
actualNotPointer, ok := a.(FeatureStateState)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateState", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Code, actual.Code, dcl.DiffInfo{OutputOnly: true, Type: "EnumType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Code")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Description, actual.Description, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Description")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.UpdateTime, actual.UpdateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("UpdateTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureStateServicemeshNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureStateServicemesh)
if !ok {
desiredNotPointer, ok := d.(FeatureStateServicemesh)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateServicemesh or *FeatureStateServicemesh", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureStateServicemesh)
if !ok {
actualNotPointer, ok := a.(FeatureStateServicemesh)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateServicemesh", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.AnalysisMessages, actual.AnalysisMessages, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareFeatureStateServicemeshAnalysisMessagesNewStyle, EmptyObject: EmptyFeatureStateServicemeshAnalysisMessages, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("AnalysisMessages")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureStateServicemeshAnalysisMessagesNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureStateServicemeshAnalysisMessages)
if !ok {
desiredNotPointer, ok := d.(FeatureStateServicemeshAnalysisMessages)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateServicemeshAnalysisMessages or *FeatureStateServicemeshAnalysisMessages", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureStateServicemeshAnalysisMessages)
if !ok {
actualNotPointer, ok := a.(FeatureStateServicemeshAnalysisMessages)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateServicemeshAnalysisMessages", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.MessageBase, actual.MessageBase, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareFeatureStateServicemeshAnalysisMessagesMessageBaseNewStyle, EmptyObject: EmptyFeatureStateServicemeshAnalysisMessagesMessageBase, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("MessageBase")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Description, actual.Description, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Description")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.ResourcePaths, actual.ResourcePaths, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("ResourcePaths")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Args, actual.Args, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Args")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureStateServicemeshAnalysisMessagesMessageBaseNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureStateServicemeshAnalysisMessagesMessageBase)
if !ok {
desiredNotPointer, ok := d.(FeatureStateServicemeshAnalysisMessagesMessageBase)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateServicemeshAnalysisMessagesMessageBase or *FeatureStateServicemeshAnalysisMessagesMessageBase", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureStateServicemeshAnalysisMessagesMessageBase)
if !ok {
actualNotPointer, ok := a.(FeatureStateServicemeshAnalysisMessagesMessageBase)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateServicemeshAnalysisMessagesMessageBase", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Type, actual.Type, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareFeatureStateServicemeshAnalysisMessagesMessageBaseTypeNewStyle, EmptyObject: EmptyFeatureStateServicemeshAnalysisMessagesMessageBaseType, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Type")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Level, actual.Level, dcl.DiffInfo{OutputOnly: true, Type: "EnumType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Level")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.DocumentationUrl, actual.DocumentationUrl, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("DocumentationUrl")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareFeatureStateServicemeshAnalysisMessagesMessageBaseTypeNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*FeatureStateServicemeshAnalysisMessagesMessageBaseType)
if !ok {
desiredNotPointer, ok := d.(FeatureStateServicemeshAnalysisMessagesMessageBaseType)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateServicemeshAnalysisMessagesMessageBaseType or *FeatureStateServicemeshAnalysisMessagesMessageBaseType", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*FeatureStateServicemeshAnalysisMessagesMessageBaseType)
if !ok {
actualNotPointer, ok := a.(FeatureStateServicemeshAnalysisMessagesMessageBaseType)
if !ok {
return nil, fmt.Errorf("obj %v is not a FeatureStateServicemeshAnalysisMessagesMessageBaseType", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.DisplayName, actual.DisplayName, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("DisplayName")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Code, actual.Code, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Code")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
// urlNormalized returns a copy of the resource struct with values normalized
// for URL substitutions. For instance, it converts long-form self-links to
// short-form so they can be substituted in.
func (r *Feature) urlNormalized() *Feature {
normalized := dcl.Copy(*r).(Feature)
normalized.Name = dcl.SelfLinkToName(r.Name)
normalized.Project = dcl.SelfLinkToName(r.Project)
normalized.Location = dcl.SelfLinkToName(r.Location)
return &normalized
}
func (r *Feature) updateURL(userBasePath, updateName string) (string, error) {
nr := r.urlNormalized()
if updateName == "UpdateFeature" {
fields := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
"name": dcl.ValueOrEmptyString(nr.Name),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/features/{{name}}", nr.basePath(), userBasePath, fields), nil
}
return "", fmt.Errorf("unknown update name: %s", updateName)
}
// marshal encodes the Feature resource into JSON for a Create request, and
// performs transformations from the resource schema to the API schema if
// necessary.
func (r *Feature) marshal(c *Client) ([]byte, error) {
m, err := expandFeature(c, r)
if err != nil {
return nil, fmt.Errorf("error marshalling Feature: %w", err)
}
return json.Marshal(m)
}
// unmarshalFeature decodes JSON responses into the Feature resource schema.
func unmarshalFeature(b []byte, c *Client, res *Feature) (*Feature, error) {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
return unmarshalMapFeature(m, c, res)
}
func unmarshalMapFeature(m map[string]interface{}, c *Client, res *Feature) (*Feature, error) {
flattened := flattenFeature(c, m, res)
if flattened == nil {
return nil, fmt.Errorf("attempted to flatten empty json object")
}
return flattened, nil
}
// expandFeature expands Feature into a JSON request object.
func expandFeature(c *Client, f *Feature) (map[string]interface{}, error) {
m := make(map[string]interface{})
res := f
_ = res
if v, err := dcl.DeriveField("projects/%s/locations/%s/features/%s", f.Name, dcl.SelfLinkToName(f.Project), dcl.SelfLinkToName(f.Location), dcl.SelfLinkToName(f.Name)); err != nil {
return nil, fmt.Errorf("error expanding Name into name: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v := f.Labels; dcl.ValueShouldBeSent(v) {
m["labels"] = v
}
if v, err := expandFeatureSpec(c, f.Spec, res); err != nil {
return nil, fmt.Errorf("error expanding Spec into spec: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["spec"] = v
}
if v, err := dcl.EmptyValue(); err != nil {
return nil, fmt.Errorf("error expanding Project into project: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["project"] = v
}
if v, err := dcl.EmptyValue(); err != nil {
return nil, fmt.Errorf("error expanding Location into location: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["location"] = v
}
return m, nil
}
// flattenFeature flattens Feature from a JSON request object into the
// Feature type.
func flattenFeature(c *Client, i interface{}, res *Feature) *Feature {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
if len(m) == 0 {
return nil
}
resultRes := &Feature{}
resultRes.Name = dcl.FlattenString(m["name"])
resultRes.Labels = dcl.FlattenKeyValuePairs(m["labels"])
resultRes.ResourceState = flattenFeatureResourceState(c, m["resourceState"], res)
resultRes.Spec = flattenFeatureSpec(c, m["spec"], res)
resultRes.State = flattenFeatureState(c, m["state"], res)
resultRes.CreateTime = dcl.FlattenString(m["createTime"])
resultRes.UpdateTime = dcl.FlattenString(m["updateTime"])
resultRes.DeleteTime = dcl.FlattenString(m["deleteTime"])
resultRes.Project = dcl.FlattenString(m["project"])
resultRes.Location = dcl.FlattenString(m["location"])
return resultRes
}
// expandFeatureResourceStateMap expands the contents of FeatureResourceState into a JSON
// request object.
func expandFeatureResourceStateMap(c *Client, f map[string]FeatureResourceState, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureResourceState(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureResourceStateSlice expands the contents of FeatureResourceState into a JSON
// request object.
func expandFeatureResourceStateSlice(c *Client, f []FeatureResourceState, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureResourceState(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureResourceStateMap flattens the contents of FeatureResourceState from a JSON
// response object.
func flattenFeatureResourceStateMap(c *Client, i interface{}, res *Feature) map[string]FeatureResourceState {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureResourceState{}
}
if len(a) == 0 {
return map[string]FeatureResourceState{}
}
items := make(map[string]FeatureResourceState)
for k, item := range a {
items[k] = *flattenFeatureResourceState(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureResourceStateSlice flattens the contents of FeatureResourceState from a JSON
// response object.
func flattenFeatureResourceStateSlice(c *Client, i interface{}, res *Feature) []FeatureResourceState {
a, ok := i.([]interface{})
if !ok {
return []FeatureResourceState{}
}
if len(a) == 0 {
return []FeatureResourceState{}
}
items := make([]FeatureResourceState, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureResourceState(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureResourceState expands an instance of FeatureResourceState into a JSON
// request object.
func expandFeatureResourceState(c *Client, f *FeatureResourceState, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
return m, nil
}
// flattenFeatureResourceState flattens an instance of FeatureResourceState from a JSON
// response object.
func flattenFeatureResourceState(c *Client, i interface{}, res *Feature) *FeatureResourceState {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureResourceState{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureResourceState
}
r.State = flattenFeatureResourceStateStateEnum(m["state"])
r.HasResources = dcl.FlattenBool(m["hasResources"])
return r
}
// expandFeatureSpecMap expands the contents of FeatureSpec into a JSON
// request object.
func expandFeatureSpecMap(c *Client, f map[string]FeatureSpec, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureSpec(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureSpecSlice expands the contents of FeatureSpec into a JSON
// request object.
func expandFeatureSpecSlice(c *Client, f []FeatureSpec, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureSpec(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureSpecMap flattens the contents of FeatureSpec from a JSON
// response object.
func flattenFeatureSpecMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpec {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpec{}
}
if len(a) == 0 {
return map[string]FeatureSpec{}
}
items := make(map[string]FeatureSpec)
for k, item := range a {
items[k] = *flattenFeatureSpec(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureSpecSlice flattens the contents of FeatureSpec from a JSON
// response object.
func flattenFeatureSpecSlice(c *Client, i interface{}, res *Feature) []FeatureSpec {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpec{}
}
if len(a) == 0 {
return []FeatureSpec{}
}
items := make([]FeatureSpec, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpec(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureSpec expands an instance of FeatureSpec into a JSON
// request object.
func expandFeatureSpec(c *Client, f *FeatureSpec, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v, err := expandFeatureSpecMulticlusteringress(c, f.Multiclusteringress, res); err != nil {
return nil, fmt.Errorf("error expanding Multiclusteringress into multiclusteringress: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["multiclusteringress"] = v
}
if v, err := expandFeatureSpecCloudauditlogging(c, f.Cloudauditlogging, res); err != nil {
return nil, fmt.Errorf("error expanding Cloudauditlogging into cloudauditlogging: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["cloudauditlogging"] = v
}
if v, err := expandFeatureSpecFleetobservability(c, f.Fleetobservability, res); err != nil {
return nil, fmt.Errorf("error expanding Fleetobservability into fleetobservability: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["fleetobservability"] = v
}
return m, nil
}
// flattenFeatureSpec flattens an instance of FeatureSpec from a JSON
// response object.
func flattenFeatureSpec(c *Client, i interface{}, res *Feature) *FeatureSpec {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureSpec{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureSpec
}
r.Multiclusteringress = flattenFeatureSpecMulticlusteringress(c, m["multiclusteringress"], res)
r.Cloudauditlogging = flattenFeatureSpecCloudauditlogging(c, m["cloudauditlogging"], res)
r.Fleetobservability = flattenFeatureSpecFleetobservability(c, m["fleetobservability"], res)
return r
}
// expandFeatureSpecMulticlusteringressMap expands the contents of FeatureSpecMulticlusteringress into a JSON
// request object.
func expandFeatureSpecMulticlusteringressMap(c *Client, f map[string]FeatureSpecMulticlusteringress, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureSpecMulticlusteringress(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureSpecMulticlusteringressSlice expands the contents of FeatureSpecMulticlusteringress into a JSON
// request object.
func expandFeatureSpecMulticlusteringressSlice(c *Client, f []FeatureSpecMulticlusteringress, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureSpecMulticlusteringress(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureSpecMulticlusteringressMap flattens the contents of FeatureSpecMulticlusteringress from a JSON
// response object.
func flattenFeatureSpecMulticlusteringressMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpecMulticlusteringress {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpecMulticlusteringress{}
}
if len(a) == 0 {
return map[string]FeatureSpecMulticlusteringress{}
}
items := make(map[string]FeatureSpecMulticlusteringress)
for k, item := range a {
items[k] = *flattenFeatureSpecMulticlusteringress(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureSpecMulticlusteringressSlice flattens the contents of FeatureSpecMulticlusteringress from a JSON
// response object.
func flattenFeatureSpecMulticlusteringressSlice(c *Client, i interface{}, res *Feature) []FeatureSpecMulticlusteringress {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpecMulticlusteringress{}
}
if len(a) == 0 {
return []FeatureSpecMulticlusteringress{}
}
items := make([]FeatureSpecMulticlusteringress, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpecMulticlusteringress(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureSpecMulticlusteringress expands an instance of FeatureSpecMulticlusteringress into a JSON
// request object.
func expandFeatureSpecMulticlusteringress(c *Client, f *FeatureSpecMulticlusteringress, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.ConfigMembership; !dcl.IsEmptyValueIndirect(v) {
m["configMembership"] = v
}
return m, nil
}
// flattenFeatureSpecMulticlusteringress flattens an instance of FeatureSpecMulticlusteringress from a JSON
// response object.
func flattenFeatureSpecMulticlusteringress(c *Client, i interface{}, res *Feature) *FeatureSpecMulticlusteringress {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureSpecMulticlusteringress{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureSpecMulticlusteringress
}
r.ConfigMembership = dcl.FlattenString(m["configMembership"])
return r
}
// expandFeatureSpecCloudauditloggingMap expands the contents of FeatureSpecCloudauditlogging into a JSON
// request object.
func expandFeatureSpecCloudauditloggingMap(c *Client, f map[string]FeatureSpecCloudauditlogging, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureSpecCloudauditlogging(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureSpecCloudauditloggingSlice expands the contents of FeatureSpecCloudauditlogging into a JSON
// request object.
func expandFeatureSpecCloudauditloggingSlice(c *Client, f []FeatureSpecCloudauditlogging, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureSpecCloudauditlogging(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureSpecCloudauditloggingMap flattens the contents of FeatureSpecCloudauditlogging from a JSON
// response object.
func flattenFeatureSpecCloudauditloggingMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpecCloudauditlogging {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpecCloudauditlogging{}
}
if len(a) == 0 {
return map[string]FeatureSpecCloudauditlogging{}
}
items := make(map[string]FeatureSpecCloudauditlogging)
for k, item := range a {
items[k] = *flattenFeatureSpecCloudauditlogging(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureSpecCloudauditloggingSlice flattens the contents of FeatureSpecCloudauditlogging from a JSON
// response object.
func flattenFeatureSpecCloudauditloggingSlice(c *Client, i interface{}, res *Feature) []FeatureSpecCloudauditlogging {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpecCloudauditlogging{}
}
if len(a) == 0 {
return []FeatureSpecCloudauditlogging{}
}
items := make([]FeatureSpecCloudauditlogging, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpecCloudauditlogging(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureSpecCloudauditlogging expands an instance of FeatureSpecCloudauditlogging into a JSON
// request object.
func expandFeatureSpecCloudauditlogging(c *Client, f *FeatureSpecCloudauditlogging, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.AllowlistedServiceAccounts; v != nil {
m["allowlistedServiceAccounts"] = v
}
return m, nil
}
// flattenFeatureSpecCloudauditlogging flattens an instance of FeatureSpecCloudauditlogging from a JSON
// response object.
func flattenFeatureSpecCloudauditlogging(c *Client, i interface{}, res *Feature) *FeatureSpecCloudauditlogging {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureSpecCloudauditlogging{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureSpecCloudauditlogging
}
r.AllowlistedServiceAccounts = dcl.FlattenStringSlice(m["allowlistedServiceAccounts"])
return r
}
// expandFeatureSpecFleetobservabilityMap expands the contents of FeatureSpecFleetobservability into a JSON
// request object.
func expandFeatureSpecFleetobservabilityMap(c *Client, f map[string]FeatureSpecFleetobservability, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureSpecFleetobservability(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureSpecFleetobservabilitySlice expands the contents of FeatureSpecFleetobservability into a JSON
// request object.
func expandFeatureSpecFleetobservabilitySlice(c *Client, f []FeatureSpecFleetobservability, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureSpecFleetobservability(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureSpecFleetobservabilityMap flattens the contents of FeatureSpecFleetobservability from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpecFleetobservability {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpecFleetobservability{}
}
if len(a) == 0 {
return map[string]FeatureSpecFleetobservability{}
}
items := make(map[string]FeatureSpecFleetobservability)
for k, item := range a {
items[k] = *flattenFeatureSpecFleetobservability(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureSpecFleetobservabilitySlice flattens the contents of FeatureSpecFleetobservability from a JSON
// response object.
func flattenFeatureSpecFleetobservabilitySlice(c *Client, i interface{}, res *Feature) []FeatureSpecFleetobservability {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpecFleetobservability{}
}
if len(a) == 0 {
return []FeatureSpecFleetobservability{}
}
items := make([]FeatureSpecFleetobservability, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpecFleetobservability(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureSpecFleetobservability expands an instance of FeatureSpecFleetobservability into a JSON
// request object.
func expandFeatureSpecFleetobservability(c *Client, f *FeatureSpecFleetobservability, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v, err := expandFeatureSpecFleetobservabilityLoggingConfig(c, f.LoggingConfig, res); err != nil {
return nil, fmt.Errorf("error expanding LoggingConfig into loggingConfig: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["loggingConfig"] = v
}
return m, nil
}
// flattenFeatureSpecFleetobservability flattens an instance of FeatureSpecFleetobservability from a JSON
// response object.
func flattenFeatureSpecFleetobservability(c *Client, i interface{}, res *Feature) *FeatureSpecFleetobservability {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureSpecFleetobservability{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureSpecFleetobservability
}
r.LoggingConfig = flattenFeatureSpecFleetobservabilityLoggingConfig(c, m["loggingConfig"], res)
return r
}
// expandFeatureSpecFleetobservabilityLoggingConfigMap expands the contents of FeatureSpecFleetobservabilityLoggingConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfigMap(c *Client, f map[string]FeatureSpecFleetobservabilityLoggingConfig, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureSpecFleetobservabilityLoggingConfig(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureSpecFleetobservabilityLoggingConfigSlice expands the contents of FeatureSpecFleetobservabilityLoggingConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfigSlice(c *Client, f []FeatureSpecFleetobservabilityLoggingConfig, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureSpecFleetobservabilityLoggingConfig(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureSpecFleetobservabilityLoggingConfigMap flattens the contents of FeatureSpecFleetobservabilityLoggingConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpecFleetobservabilityLoggingConfig {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpecFleetobservabilityLoggingConfig{}
}
if len(a) == 0 {
return map[string]FeatureSpecFleetobservabilityLoggingConfig{}
}
items := make(map[string]FeatureSpecFleetobservabilityLoggingConfig)
for k, item := range a {
items[k] = *flattenFeatureSpecFleetobservabilityLoggingConfig(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureSpecFleetobservabilityLoggingConfigSlice flattens the contents of FeatureSpecFleetobservabilityLoggingConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigSlice(c *Client, i interface{}, res *Feature) []FeatureSpecFleetobservabilityLoggingConfig {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpecFleetobservabilityLoggingConfig{}
}
if len(a) == 0 {
return []FeatureSpecFleetobservabilityLoggingConfig{}
}
items := make([]FeatureSpecFleetobservabilityLoggingConfig, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpecFleetobservabilityLoggingConfig(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureSpecFleetobservabilityLoggingConfig expands an instance of FeatureSpecFleetobservabilityLoggingConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfig(c *Client, f *FeatureSpecFleetobservabilityLoggingConfig, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v, err := expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, f.DefaultConfig, res); err != nil {
return nil, fmt.Errorf("error expanding DefaultConfig into defaultConfig: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["defaultConfig"] = v
}
if v, err := expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, f.FleetScopeLogsConfig, res); err != nil {
return nil, fmt.Errorf("error expanding FleetScopeLogsConfig into fleetScopeLogsConfig: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["fleetScopeLogsConfig"] = v
}
return m, nil
}
// flattenFeatureSpecFleetobservabilityLoggingConfig flattens an instance of FeatureSpecFleetobservabilityLoggingConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfig(c *Client, i interface{}, res *Feature) *FeatureSpecFleetobservabilityLoggingConfig {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureSpecFleetobservabilityLoggingConfig{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureSpecFleetobservabilityLoggingConfig
}
r.DefaultConfig = flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, m["defaultConfig"], res)
r.FleetScopeLogsConfig = flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, m["fleetScopeLogsConfig"], res)
return r
}
// expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfigMap expands the contents of FeatureSpecFleetobservabilityLoggingConfigDefaultConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfigMap(c *Client, f map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfig, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfigSlice expands the contents of FeatureSpecFleetobservabilityLoggingConfigDefaultConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfigSlice(c *Client, f []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigMap flattens the contents of FeatureSpecFleetobservabilityLoggingConfigDefaultConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfig {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{}
}
if len(a) == 0 {
return map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{}
}
items := make(map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfig)
for k, item := range a {
items[k] = *flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigSlice flattens the contents of FeatureSpecFleetobservabilityLoggingConfigDefaultConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigSlice(c *Client, i interface{}, res *Feature) []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{}
}
if len(a) == 0 {
return []FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{}
}
items := make([]FeatureSpecFleetobservabilityLoggingConfigDefaultConfig, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfig expands an instance of FeatureSpecFleetobservabilityLoggingConfigDefaultConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c *Client, f *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Mode; !dcl.IsEmptyValueIndirect(v) {
m["mode"] = v
}
return m, nil
}
// flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfig flattens an instance of FeatureSpecFleetobservabilityLoggingConfigDefaultConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfig(c *Client, i interface{}, res *Feature) *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureSpecFleetobservabilityLoggingConfigDefaultConfig
}
r.Mode = flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum(m["mode"])
return r
}
// expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigMap expands the contents of FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigMap(c *Client, f map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigSlice expands the contents of FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigSlice(c *Client, f []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigMap flattens the contents of FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{}
}
if len(a) == 0 {
return map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{}
}
items := make(map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig)
for k, item := range a {
items[k] = *flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigSlice flattens the contents of FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigSlice(c *Client, i interface{}, res *Feature) []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{}
}
if len(a) == 0 {
return []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{}
}
items := make([]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig expands an instance of FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig into a JSON
// request object.
func expandFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c *Client, f *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Mode; !dcl.IsEmptyValueIndirect(v) {
m["mode"] = v
}
return m, nil
}
// flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig flattens an instance of FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig(c *Client, i interface{}, res *Feature) *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig
}
r.Mode = flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum(m["mode"])
return r
}
// expandFeatureStateMap expands the contents of FeatureState into a JSON
// request object.
func expandFeatureStateMap(c *Client, f map[string]FeatureState, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureState(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureStateSlice expands the contents of FeatureState into a JSON
// request object.
func expandFeatureStateSlice(c *Client, f []FeatureState, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureState(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureStateMap flattens the contents of FeatureState from a JSON
// response object.
func flattenFeatureStateMap(c *Client, i interface{}, res *Feature) map[string]FeatureState {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureState{}
}
if len(a) == 0 {
return map[string]FeatureState{}
}
items := make(map[string]FeatureState)
for k, item := range a {
items[k] = *flattenFeatureState(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureStateSlice flattens the contents of FeatureState from a JSON
// response object.
func flattenFeatureStateSlice(c *Client, i interface{}, res *Feature) []FeatureState {
a, ok := i.([]interface{})
if !ok {
return []FeatureState{}
}
if len(a) == 0 {
return []FeatureState{}
}
items := make([]FeatureState, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureState(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureState expands an instance of FeatureState into a JSON
// request object.
func expandFeatureState(c *Client, f *FeatureState, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
return m, nil
}
// flattenFeatureState flattens an instance of FeatureState from a JSON
// response object.
func flattenFeatureState(c *Client, i interface{}, res *Feature) *FeatureState {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureState{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureState
}
r.State = flattenFeatureStateState(c, m["state"], res)
r.Servicemesh = flattenFeatureStateServicemesh(c, m["servicemesh"], res)
return r
}
// expandFeatureStateStateMap expands the contents of FeatureStateState into a JSON
// request object.
func expandFeatureStateStateMap(c *Client, f map[string]FeatureStateState, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureStateState(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureStateStateSlice expands the contents of FeatureStateState into a JSON
// request object.
func expandFeatureStateStateSlice(c *Client, f []FeatureStateState, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureStateState(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureStateStateMap flattens the contents of FeatureStateState from a JSON
// response object.
func flattenFeatureStateStateMap(c *Client, i interface{}, res *Feature) map[string]FeatureStateState {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureStateState{}
}
if len(a) == 0 {
return map[string]FeatureStateState{}
}
items := make(map[string]FeatureStateState)
for k, item := range a {
items[k] = *flattenFeatureStateState(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureStateStateSlice flattens the contents of FeatureStateState from a JSON
// response object.
func flattenFeatureStateStateSlice(c *Client, i interface{}, res *Feature) []FeatureStateState {
a, ok := i.([]interface{})
if !ok {
return []FeatureStateState{}
}
if len(a) == 0 {
return []FeatureStateState{}
}
items := make([]FeatureStateState, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureStateState(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureStateState expands an instance of FeatureStateState into a JSON
// request object.
func expandFeatureStateState(c *Client, f *FeatureStateState, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
return m, nil
}
// flattenFeatureStateState flattens an instance of FeatureStateState from a JSON
// response object.
func flattenFeatureStateState(c *Client, i interface{}, res *Feature) *FeatureStateState {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureStateState{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureStateState
}
r.Code = flattenFeatureStateStateCodeEnum(m["code"])
r.Description = dcl.FlattenString(m["description"])
r.UpdateTime = dcl.FlattenString(m["updateTime"])
return r
}
// expandFeatureStateServicemeshMap expands the contents of FeatureStateServicemesh into a JSON
// request object.
func expandFeatureStateServicemeshMap(c *Client, f map[string]FeatureStateServicemesh, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureStateServicemesh(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureStateServicemeshSlice expands the contents of FeatureStateServicemesh into a JSON
// request object.
func expandFeatureStateServicemeshSlice(c *Client, f []FeatureStateServicemesh, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureStateServicemesh(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureStateServicemeshMap flattens the contents of FeatureStateServicemesh from a JSON
// response object.
func flattenFeatureStateServicemeshMap(c *Client, i interface{}, res *Feature) map[string]FeatureStateServicemesh {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureStateServicemesh{}
}
if len(a) == 0 {
return map[string]FeatureStateServicemesh{}
}
items := make(map[string]FeatureStateServicemesh)
for k, item := range a {
items[k] = *flattenFeatureStateServicemesh(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureStateServicemeshSlice flattens the contents of FeatureStateServicemesh from a JSON
// response object.
func flattenFeatureStateServicemeshSlice(c *Client, i interface{}, res *Feature) []FeatureStateServicemesh {
a, ok := i.([]interface{})
if !ok {
return []FeatureStateServicemesh{}
}
if len(a) == 0 {
return []FeatureStateServicemesh{}
}
items := make([]FeatureStateServicemesh, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureStateServicemesh(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureStateServicemesh expands an instance of FeatureStateServicemesh into a JSON
// request object.
func expandFeatureStateServicemesh(c *Client, f *FeatureStateServicemesh, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
return m, nil
}
// flattenFeatureStateServicemesh flattens an instance of FeatureStateServicemesh from a JSON
// response object.
func flattenFeatureStateServicemesh(c *Client, i interface{}, res *Feature) *FeatureStateServicemesh {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureStateServicemesh{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureStateServicemesh
}
r.AnalysisMessages = flattenFeatureStateServicemeshAnalysisMessagesSlice(c, m["analysisMessages"], res)
return r
}
// expandFeatureStateServicemeshAnalysisMessagesMap expands the contents of FeatureStateServicemeshAnalysisMessages into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessagesMap(c *Client, f map[string]FeatureStateServicemeshAnalysisMessages, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureStateServicemeshAnalysisMessages(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureStateServicemeshAnalysisMessagesSlice expands the contents of FeatureStateServicemeshAnalysisMessages into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessagesSlice(c *Client, f []FeatureStateServicemeshAnalysisMessages, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureStateServicemeshAnalysisMessages(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureStateServicemeshAnalysisMessagesMap flattens the contents of FeatureStateServicemeshAnalysisMessages from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMap(c *Client, i interface{}, res *Feature) map[string]FeatureStateServicemeshAnalysisMessages {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureStateServicemeshAnalysisMessages{}
}
if len(a) == 0 {
return map[string]FeatureStateServicemeshAnalysisMessages{}
}
items := make(map[string]FeatureStateServicemeshAnalysisMessages)
for k, item := range a {
items[k] = *flattenFeatureStateServicemeshAnalysisMessages(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureStateServicemeshAnalysisMessagesSlice flattens the contents of FeatureStateServicemeshAnalysisMessages from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesSlice(c *Client, i interface{}, res *Feature) []FeatureStateServicemeshAnalysisMessages {
a, ok := i.([]interface{})
if !ok {
return []FeatureStateServicemeshAnalysisMessages{}
}
if len(a) == 0 {
return []FeatureStateServicemeshAnalysisMessages{}
}
items := make([]FeatureStateServicemeshAnalysisMessages, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureStateServicemeshAnalysisMessages(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureStateServicemeshAnalysisMessages expands an instance of FeatureStateServicemeshAnalysisMessages into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessages(c *Client, f *FeatureStateServicemeshAnalysisMessages, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
return m, nil
}
// flattenFeatureStateServicemeshAnalysisMessages flattens an instance of FeatureStateServicemeshAnalysisMessages from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessages(c *Client, i interface{}, res *Feature) *FeatureStateServicemeshAnalysisMessages {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureStateServicemeshAnalysisMessages{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureStateServicemeshAnalysisMessages
}
r.MessageBase = flattenFeatureStateServicemeshAnalysisMessagesMessageBase(c, m["messageBase"], res)
r.Description = dcl.FlattenString(m["description"])
r.ResourcePaths = dcl.FlattenStringSlice(m["resourcePaths"])
r.Args = dcl.FlattenKeyValuePairs(m["args"])
return r
}
// expandFeatureStateServicemeshAnalysisMessagesMessageBaseMap expands the contents of FeatureStateServicemeshAnalysisMessagesMessageBase into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessagesMessageBaseMap(c *Client, f map[string]FeatureStateServicemeshAnalysisMessagesMessageBase, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureStateServicemeshAnalysisMessagesMessageBase(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureStateServicemeshAnalysisMessagesMessageBaseSlice expands the contents of FeatureStateServicemeshAnalysisMessagesMessageBase into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessagesMessageBaseSlice(c *Client, f []FeatureStateServicemeshAnalysisMessagesMessageBase, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureStateServicemeshAnalysisMessagesMessageBase(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBaseMap flattens the contents of FeatureStateServicemeshAnalysisMessagesMessageBase from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBaseMap(c *Client, i interface{}, res *Feature) map[string]FeatureStateServicemeshAnalysisMessagesMessageBase {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureStateServicemeshAnalysisMessagesMessageBase{}
}
if len(a) == 0 {
return map[string]FeatureStateServicemeshAnalysisMessagesMessageBase{}
}
items := make(map[string]FeatureStateServicemeshAnalysisMessagesMessageBase)
for k, item := range a {
items[k] = *flattenFeatureStateServicemeshAnalysisMessagesMessageBase(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBaseSlice flattens the contents of FeatureStateServicemeshAnalysisMessagesMessageBase from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBaseSlice(c *Client, i interface{}, res *Feature) []FeatureStateServicemeshAnalysisMessagesMessageBase {
a, ok := i.([]interface{})
if !ok {
return []FeatureStateServicemeshAnalysisMessagesMessageBase{}
}
if len(a) == 0 {
return []FeatureStateServicemeshAnalysisMessagesMessageBase{}
}
items := make([]FeatureStateServicemeshAnalysisMessagesMessageBase, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureStateServicemeshAnalysisMessagesMessageBase(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureStateServicemeshAnalysisMessagesMessageBase expands an instance of FeatureStateServicemeshAnalysisMessagesMessageBase into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessagesMessageBase(c *Client, f *FeatureStateServicemeshAnalysisMessagesMessageBase, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
return m, nil
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBase flattens an instance of FeatureStateServicemeshAnalysisMessagesMessageBase from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBase(c *Client, i interface{}, res *Feature) *FeatureStateServicemeshAnalysisMessagesMessageBase {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureStateServicemeshAnalysisMessagesMessageBase{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureStateServicemeshAnalysisMessagesMessageBase
}
r.Type = flattenFeatureStateServicemeshAnalysisMessagesMessageBaseType(c, m["type"], res)
r.Level = flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum(m["level"])
r.DocumentationUrl = dcl.FlattenString(m["documentationUrl"])
return r
}
// expandFeatureStateServicemeshAnalysisMessagesMessageBaseTypeMap expands the contents of FeatureStateServicemeshAnalysisMessagesMessageBaseType into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessagesMessageBaseTypeMap(c *Client, f map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseType, res *Feature) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandFeatureStateServicemeshAnalysisMessagesMessageBaseType(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandFeatureStateServicemeshAnalysisMessagesMessageBaseTypeSlice expands the contents of FeatureStateServicemeshAnalysisMessagesMessageBaseType into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessagesMessageBaseTypeSlice(c *Client, f []FeatureStateServicemeshAnalysisMessagesMessageBaseType, res *Feature) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandFeatureStateServicemeshAnalysisMessagesMessageBaseType(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBaseTypeMap flattens the contents of FeatureStateServicemeshAnalysisMessagesMessageBaseType from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBaseTypeMap(c *Client, i interface{}, res *Feature) map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseType {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseType{}
}
if len(a) == 0 {
return map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseType{}
}
items := make(map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseType)
for k, item := range a {
items[k] = *flattenFeatureStateServicemeshAnalysisMessagesMessageBaseType(c, item.(map[string]interface{}), res)
}
return items
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBaseTypeSlice flattens the contents of FeatureStateServicemeshAnalysisMessagesMessageBaseType from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBaseTypeSlice(c *Client, i interface{}, res *Feature) []FeatureStateServicemeshAnalysisMessagesMessageBaseType {
a, ok := i.([]interface{})
if !ok {
return []FeatureStateServicemeshAnalysisMessagesMessageBaseType{}
}
if len(a) == 0 {
return []FeatureStateServicemeshAnalysisMessagesMessageBaseType{}
}
items := make([]FeatureStateServicemeshAnalysisMessagesMessageBaseType, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureStateServicemeshAnalysisMessagesMessageBaseType(c, item.(map[string]interface{}), res))
}
return items
}
// expandFeatureStateServicemeshAnalysisMessagesMessageBaseType expands an instance of FeatureStateServicemeshAnalysisMessagesMessageBaseType into a JSON
// request object.
func expandFeatureStateServicemeshAnalysisMessagesMessageBaseType(c *Client, f *FeatureStateServicemeshAnalysisMessagesMessageBaseType, res *Feature) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
return m, nil
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBaseType flattens an instance of FeatureStateServicemeshAnalysisMessagesMessageBaseType from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBaseType(c *Client, i interface{}, res *Feature) *FeatureStateServicemeshAnalysisMessagesMessageBaseType {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &FeatureStateServicemeshAnalysisMessagesMessageBaseType{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyFeatureStateServicemeshAnalysisMessagesMessageBaseType
}
r.DisplayName = dcl.FlattenString(m["displayName"])
r.Code = dcl.FlattenString(m["code"])
return r
}
// flattenFeatureResourceStateStateEnumMap flattens the contents of FeatureResourceStateStateEnum from a JSON
// response object.
func flattenFeatureResourceStateStateEnumMap(c *Client, i interface{}, res *Feature) map[string]FeatureResourceStateStateEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureResourceStateStateEnum{}
}
if len(a) == 0 {
return map[string]FeatureResourceStateStateEnum{}
}
items := make(map[string]FeatureResourceStateStateEnum)
for k, item := range a {
items[k] = *flattenFeatureResourceStateStateEnum(item.(interface{}))
}
return items
}
// flattenFeatureResourceStateStateEnumSlice flattens the contents of FeatureResourceStateStateEnum from a JSON
// response object.
func flattenFeatureResourceStateStateEnumSlice(c *Client, i interface{}, res *Feature) []FeatureResourceStateStateEnum {
a, ok := i.([]interface{})
if !ok {
return []FeatureResourceStateStateEnum{}
}
if len(a) == 0 {
return []FeatureResourceStateStateEnum{}
}
items := make([]FeatureResourceStateStateEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureResourceStateStateEnum(item.(interface{})))
}
return items
}
// flattenFeatureResourceStateStateEnum asserts that an interface is a string, and returns a
// pointer to a *FeatureResourceStateStateEnum with the same value as that string.
func flattenFeatureResourceStateStateEnum(i interface{}) *FeatureResourceStateStateEnum {
s, ok := i.(string)
if !ok {
return nil
}
return FeatureResourceStateStateEnumRef(s)
}
// flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnumMap flattens the contents of FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnumMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum{}
}
if len(a) == 0 {
return map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum{}
}
items := make(map[string]FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum)
for k, item := range a {
items[k] = *flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum(item.(interface{}))
}
return items
}
// flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnumSlice flattens the contents of FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnumSlice(c *Client, i interface{}, res *Feature) []FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum{}
}
if len(a) == 0 {
return []FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum{}
}
items := make([]FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum(item.(interface{})))
}
return items
}
// flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum asserts that an interface is a string, and returns a
// pointer to a *FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum with the same value as that string.
func flattenFeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum(i interface{}) *FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum {
s, ok := i.(string)
if !ok {
return nil
}
return FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnumRef(s)
}
// flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnumMap flattens the contents of FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnumMap(c *Client, i interface{}, res *Feature) map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum{}
}
if len(a) == 0 {
return map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum{}
}
items := make(map[string]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum)
for k, item := range a {
items[k] = *flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum(item.(interface{}))
}
return items
}
// flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnumSlice flattens the contents of FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum from a JSON
// response object.
func flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnumSlice(c *Client, i interface{}, res *Feature) []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum {
a, ok := i.([]interface{})
if !ok {
return []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum{}
}
if len(a) == 0 {
return []FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum{}
}
items := make([]FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum(item.(interface{})))
}
return items
}
// flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum asserts that an interface is a string, and returns a
// pointer to a *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum with the same value as that string.
func flattenFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum(i interface{}) *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum {
s, ok := i.(string)
if !ok {
return nil
}
return FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnumRef(s)
}
// flattenFeatureStateStateCodeEnumMap flattens the contents of FeatureStateStateCodeEnum from a JSON
// response object.
func flattenFeatureStateStateCodeEnumMap(c *Client, i interface{}, res *Feature) map[string]FeatureStateStateCodeEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureStateStateCodeEnum{}
}
if len(a) == 0 {
return map[string]FeatureStateStateCodeEnum{}
}
items := make(map[string]FeatureStateStateCodeEnum)
for k, item := range a {
items[k] = *flattenFeatureStateStateCodeEnum(item.(interface{}))
}
return items
}
// flattenFeatureStateStateCodeEnumSlice flattens the contents of FeatureStateStateCodeEnum from a JSON
// response object.
func flattenFeatureStateStateCodeEnumSlice(c *Client, i interface{}, res *Feature) []FeatureStateStateCodeEnum {
a, ok := i.([]interface{})
if !ok {
return []FeatureStateStateCodeEnum{}
}
if len(a) == 0 {
return []FeatureStateStateCodeEnum{}
}
items := make([]FeatureStateStateCodeEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureStateStateCodeEnum(item.(interface{})))
}
return items
}
// flattenFeatureStateStateCodeEnum asserts that an interface is a string, and returns a
// pointer to a *FeatureStateStateCodeEnum with the same value as that string.
func flattenFeatureStateStateCodeEnum(i interface{}) *FeatureStateStateCodeEnum {
s, ok := i.(string)
if !ok {
return nil
}
return FeatureStateStateCodeEnumRef(s)
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnumMap flattens the contents of FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnumMap(c *Client, i interface{}, res *Feature) map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum{}
}
if len(a) == 0 {
return map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum{}
}
items := make(map[string]FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum)
for k, item := range a {
items[k] = *flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum(item.(interface{}))
}
return items
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnumSlice flattens the contents of FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum from a JSON
// response object.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnumSlice(c *Client, i interface{}, res *Feature) []FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum {
a, ok := i.([]interface{})
if !ok {
return []FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum{}
}
if len(a) == 0 {
return []FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum{}
}
items := make([]FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum(item.(interface{})))
}
return items
}
// flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum asserts that an interface is a string, and returns a
// pointer to a *FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum with the same value as that string.
func flattenFeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum(i interface{}) *FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum {
s, ok := i.(string)
if !ok {
return nil
}
return FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnumRef(s)
}
// This function returns a matcher that checks whether a serialized resource matches this resource
// in its parameters (as defined by the fields in a Get, which definitionally define resource
// identity). This is useful in extracting the element from a List call.
func (r *Feature) matcher(c *Client) func([]byte) bool {
return func(b []byte) bool {
cr, err := unmarshalFeature(b, c, r)
if err != nil {
c.Config.Logger.Warning("failed to unmarshal provided resource in matcher.")
return false
}
nr := r.urlNormalized()
ncr := cr.urlNormalized()
c.Config.Logger.Infof("looking for %v\nin %v", nr, ncr)
if nr.Project == nil && ncr.Project == nil {
c.Config.Logger.Info("Both Project fields null - considering equal.")
} else if nr.Project == nil || ncr.Project == nil {
c.Config.Logger.Info("Only one Project field is null - considering unequal.")
return false
} else if *nr.Project != *ncr.Project {
return false
}
if nr.Location == nil && ncr.Location == nil {
c.Config.Logger.Info("Both Location fields null - considering equal.")
} else if nr.Location == nil || ncr.Location == nil {
c.Config.Logger.Info("Only one Location field is null - considering unequal.")
return false
} else if *nr.Location != *ncr.Location {
return false
}
if nr.Name == nil && ncr.Name == nil {
c.Config.Logger.Info("Both Name fields null - considering equal.")
} else if nr.Name == nil || ncr.Name == nil {
c.Config.Logger.Info("Only one Name field is null - considering unequal.")
return false
} else if *nr.Name != *ncr.Name {
return false
}
return true
}
}
type featureDiff struct {
// The diff should include one or the other of RequiresRecreate or UpdateOp.
RequiresRecreate bool
UpdateOp featureApiOperation
FieldName string // used for error logging
}
func convertFieldDiffsToFeatureDiffs(config *dcl.Config, fds []*dcl.FieldDiff, opts []dcl.ApplyOption) ([]featureDiff, error) {
opNamesToFieldDiffs := make(map[string][]*dcl.FieldDiff)
// Map each operation name to the field diffs associated with it.
for _, fd := range fds {
for _, ro := range fd.ResultingOperation {
if fieldDiffs, ok := opNamesToFieldDiffs[ro]; ok {
fieldDiffs = append(fieldDiffs, fd)
opNamesToFieldDiffs[ro] = fieldDiffs
} else {
config.Logger.Infof("%s required due to diff: %v", ro, fd)
opNamesToFieldDiffs[ro] = []*dcl.FieldDiff{fd}
}
}
}
var diffs []featureDiff
// For each operation name, create a featureDiff which contains the operation.
for opName, fieldDiffs := range opNamesToFieldDiffs {
// Use the first field diff's field name for logging required recreate error.
diff := featureDiff{FieldName: fieldDiffs[0].FieldName}
if opName == "Recreate" {
diff.RequiresRecreate = true
} else {
apiOp, err := convertOpNameToFeatureApiOperation(opName, fieldDiffs, opts...)
if err != nil {
return diffs, err
}
diff.UpdateOp = apiOp
}
diffs = append(diffs, diff)
}
return diffs, nil
}
func convertOpNameToFeatureApiOperation(opName string, fieldDiffs []*dcl.FieldDiff, opts ...dcl.ApplyOption) (featureApiOperation, error) {
switch opName {
case "updateFeatureUpdateFeatureOperation":
return &updateFeatureUpdateFeatureOperation{FieldDiffs: fieldDiffs}, nil
default:
return nil, fmt.Errorf("no such operation with name: %v", opName)
}
}
func extractFeatureFields(r *Feature) error {
vResourceState := r.ResourceState
if vResourceState == nil {
// note: explicitly not the empty object.
vResourceState = &FeatureResourceState{}
}
if err := extractFeatureResourceStateFields(r, vResourceState); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vResourceState) {
r.ResourceState = vResourceState
}
vSpec := r.Spec
if vSpec == nil {
// note: explicitly not the empty object.
vSpec = &FeatureSpec{}
}
if err := extractFeatureSpecFields(r, vSpec); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vSpec) {
r.Spec = vSpec
}
vState := r.State
if vState == nil {
// note: explicitly not the empty object.
vState = &FeatureState{}
}
if err := extractFeatureStateFields(r, vState); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vState) {
r.State = vState
}
return nil
}
func extractFeatureResourceStateFields(r *Feature, o *FeatureResourceState) error {
return nil
}
func extractFeatureSpecFields(r *Feature, o *FeatureSpec) error {
vMulticlusteringress := o.Multiclusteringress
if vMulticlusteringress == nil {
// note: explicitly not the empty object.
vMulticlusteringress = &FeatureSpecMulticlusteringress{}
}
if err := extractFeatureSpecMulticlusteringressFields(r, vMulticlusteringress); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vMulticlusteringress) {
o.Multiclusteringress = vMulticlusteringress
}
vCloudauditlogging := o.Cloudauditlogging
if vCloudauditlogging == nil {
// note: explicitly not the empty object.
vCloudauditlogging = &FeatureSpecCloudauditlogging{}
}
if err := extractFeatureSpecCloudauditloggingFields(r, vCloudauditlogging); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vCloudauditlogging) {
o.Cloudauditlogging = vCloudauditlogging
}
vFleetobservability := o.Fleetobservability
if vFleetobservability == nil {
// note: explicitly not the empty object.
vFleetobservability = &FeatureSpecFleetobservability{}
}
if err := extractFeatureSpecFleetobservabilityFields(r, vFleetobservability); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vFleetobservability) {
o.Fleetobservability = vFleetobservability
}
return nil
}
func extractFeatureSpecMulticlusteringressFields(r *Feature, o *FeatureSpecMulticlusteringress) error {
return nil
}
func extractFeatureSpecCloudauditloggingFields(r *Feature, o *FeatureSpecCloudauditlogging) error {
return nil
}
func extractFeatureSpecFleetobservabilityFields(r *Feature, o *FeatureSpecFleetobservability) error {
vLoggingConfig := o.LoggingConfig
if vLoggingConfig == nil {
// note: explicitly not the empty object.
vLoggingConfig = &FeatureSpecFleetobservabilityLoggingConfig{}
}
if err := extractFeatureSpecFleetobservabilityLoggingConfigFields(r, vLoggingConfig); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vLoggingConfig) {
o.LoggingConfig = vLoggingConfig
}
return nil
}
func extractFeatureSpecFleetobservabilityLoggingConfigFields(r *Feature, o *FeatureSpecFleetobservabilityLoggingConfig) error {
vDefaultConfig := o.DefaultConfig
if vDefaultConfig == nil {
// note: explicitly not the empty object.
vDefaultConfig = &FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{}
}
if err := extractFeatureSpecFleetobservabilityLoggingConfigDefaultConfigFields(r, vDefaultConfig); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vDefaultConfig) {
o.DefaultConfig = vDefaultConfig
}
vFleetScopeLogsConfig := o.FleetScopeLogsConfig
if vFleetScopeLogsConfig == nil {
// note: explicitly not the empty object.
vFleetScopeLogsConfig = &FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{}
}
if err := extractFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigFields(r, vFleetScopeLogsConfig); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vFleetScopeLogsConfig) {
o.FleetScopeLogsConfig = vFleetScopeLogsConfig
}
return nil
}
func extractFeatureSpecFleetobservabilityLoggingConfigDefaultConfigFields(r *Feature, o *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) error {
return nil
}
func extractFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigFields(r *Feature, o *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) error {
return nil
}
func extractFeatureStateFields(r *Feature, o *FeatureState) error {
vState := o.State
if vState == nil {
// note: explicitly not the empty object.
vState = &FeatureStateState{}
}
if err := extractFeatureStateStateFields(r, vState); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vState) {
o.State = vState
}
vServicemesh := o.Servicemesh
if vServicemesh == nil {
// note: explicitly not the empty object.
vServicemesh = &FeatureStateServicemesh{}
}
if err := extractFeatureStateServicemeshFields(r, vServicemesh); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vServicemesh) {
o.Servicemesh = vServicemesh
}
return nil
}
func extractFeatureStateStateFields(r *Feature, o *FeatureStateState) error {
return nil
}
func extractFeatureStateServicemeshFields(r *Feature, o *FeatureStateServicemesh) error {
return nil
}
func extractFeatureStateServicemeshAnalysisMessagesFields(r *Feature, o *FeatureStateServicemeshAnalysisMessages) error {
vMessageBase := o.MessageBase
if vMessageBase == nil {
// note: explicitly not the empty object.
vMessageBase = &FeatureStateServicemeshAnalysisMessagesMessageBase{}
}
if err := extractFeatureStateServicemeshAnalysisMessagesMessageBaseFields(r, vMessageBase); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vMessageBase) {
o.MessageBase = vMessageBase
}
return nil
}
func extractFeatureStateServicemeshAnalysisMessagesMessageBaseFields(r *Feature, o *FeatureStateServicemeshAnalysisMessagesMessageBase) error {
vType := o.Type
if vType == nil {
// note: explicitly not the empty object.
vType = &FeatureStateServicemeshAnalysisMessagesMessageBaseType{}
}
if err := extractFeatureStateServicemeshAnalysisMessagesMessageBaseTypeFields(r, vType); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vType) {
o.Type = vType
}
return nil
}
func extractFeatureStateServicemeshAnalysisMessagesMessageBaseTypeFields(r *Feature, o *FeatureStateServicemeshAnalysisMessagesMessageBaseType) error {
return nil
}
func postReadExtractFeatureFields(r *Feature) error {
vResourceState := r.ResourceState
if vResourceState == nil {
// note: explicitly not the empty object.
vResourceState = &FeatureResourceState{}
}
if err := postReadExtractFeatureResourceStateFields(r, vResourceState); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vResourceState) {
r.ResourceState = vResourceState
}
vSpec := r.Spec
if vSpec == nil {
// note: explicitly not the empty object.
vSpec = &FeatureSpec{}
}
if err := postReadExtractFeatureSpecFields(r, vSpec); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vSpec) {
r.Spec = vSpec
}
vState := r.State
if vState == nil {
// note: explicitly not the empty object.
vState = &FeatureState{}
}
if err := postReadExtractFeatureStateFields(r, vState); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vState) {
r.State = vState
}
return nil
}
func postReadExtractFeatureResourceStateFields(r *Feature, o *FeatureResourceState) error {
return nil
}
func postReadExtractFeatureSpecFields(r *Feature, o *FeatureSpec) error {
vMulticlusteringress := o.Multiclusteringress
if vMulticlusteringress == nil {
// note: explicitly not the empty object.
vMulticlusteringress = &FeatureSpecMulticlusteringress{}
}
if err := extractFeatureSpecMulticlusteringressFields(r, vMulticlusteringress); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vMulticlusteringress) {
o.Multiclusteringress = vMulticlusteringress
}
vCloudauditlogging := o.Cloudauditlogging
if vCloudauditlogging == nil {
// note: explicitly not the empty object.
vCloudauditlogging = &FeatureSpecCloudauditlogging{}
}
if err := extractFeatureSpecCloudauditloggingFields(r, vCloudauditlogging); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vCloudauditlogging) {
o.Cloudauditlogging = vCloudauditlogging
}
vFleetobservability := o.Fleetobservability
if vFleetobservability == nil {
// note: explicitly not the empty object.
vFleetobservability = &FeatureSpecFleetobservability{}
}
if err := extractFeatureSpecFleetobservabilityFields(r, vFleetobservability); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vFleetobservability) {
o.Fleetobservability = vFleetobservability
}
return nil
}
func postReadExtractFeatureSpecMulticlusteringressFields(r *Feature, o *FeatureSpecMulticlusteringress) error {
return nil
}
func postReadExtractFeatureSpecCloudauditloggingFields(r *Feature, o *FeatureSpecCloudauditlogging) error {
return nil
}
func postReadExtractFeatureSpecFleetobservabilityFields(r *Feature, o *FeatureSpecFleetobservability) error {
vLoggingConfig := o.LoggingConfig
if vLoggingConfig == nil {
// note: explicitly not the empty object.
vLoggingConfig = &FeatureSpecFleetobservabilityLoggingConfig{}
}
if err := extractFeatureSpecFleetobservabilityLoggingConfigFields(r, vLoggingConfig); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vLoggingConfig) {
o.LoggingConfig = vLoggingConfig
}
return nil
}
func postReadExtractFeatureSpecFleetobservabilityLoggingConfigFields(r *Feature, o *FeatureSpecFleetobservabilityLoggingConfig) error {
vDefaultConfig := o.DefaultConfig
if vDefaultConfig == nil {
// note: explicitly not the empty object.
vDefaultConfig = &FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{}
}
if err := extractFeatureSpecFleetobservabilityLoggingConfigDefaultConfigFields(r, vDefaultConfig); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vDefaultConfig) {
o.DefaultConfig = vDefaultConfig
}
vFleetScopeLogsConfig := o.FleetScopeLogsConfig
if vFleetScopeLogsConfig == nil {
// note: explicitly not the empty object.
vFleetScopeLogsConfig = &FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{}
}
if err := extractFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigFields(r, vFleetScopeLogsConfig); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vFleetScopeLogsConfig) {
o.FleetScopeLogsConfig = vFleetScopeLogsConfig
}
return nil
}
func postReadExtractFeatureSpecFleetobservabilityLoggingConfigDefaultConfigFields(r *Feature, o *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) error {
return nil
}
func postReadExtractFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigFields(r *Feature, o *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) error {
return nil
}
func postReadExtractFeatureStateFields(r *Feature, o *FeatureState) error {
vState := o.State
if vState == nil {
// note: explicitly not the empty object.
vState = &FeatureStateState{}
}
if err := extractFeatureStateStateFields(r, vState); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vState) {
o.State = vState
}
vServicemesh := o.Servicemesh
if vServicemesh == nil {
// note: explicitly not the empty object.
vServicemesh = &FeatureStateServicemesh{}
}
if err := extractFeatureStateServicemeshFields(r, vServicemesh); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vServicemesh) {
o.Servicemesh = vServicemesh
}
return nil
}
func postReadExtractFeatureStateStateFields(r *Feature, o *FeatureStateState) error {
return nil
}
func postReadExtractFeatureStateServicemeshFields(r *Feature, o *FeatureStateServicemesh) error {
return nil
}
func postReadExtractFeatureStateServicemeshAnalysisMessagesFields(r *Feature, o *FeatureStateServicemeshAnalysisMessages) error {
vMessageBase := o.MessageBase
if vMessageBase == nil {
// note: explicitly not the empty object.
vMessageBase = &FeatureStateServicemeshAnalysisMessagesMessageBase{}
}
if err := extractFeatureStateServicemeshAnalysisMessagesMessageBaseFields(r, vMessageBase); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vMessageBase) {
o.MessageBase = vMessageBase
}
return nil
}
func postReadExtractFeatureStateServicemeshAnalysisMessagesMessageBaseFields(r *Feature, o *FeatureStateServicemeshAnalysisMessagesMessageBase) error {
vType := o.Type
if vType == nil {
// note: explicitly not the empty object.
vType = &FeatureStateServicemeshAnalysisMessagesMessageBaseType{}
}
if err := extractFeatureStateServicemeshAnalysisMessagesMessageBaseTypeFields(r, vType); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vType) {
o.Type = vType
}
return nil
}
func postReadExtractFeatureStateServicemeshAnalysisMessagesMessageBaseTypeFields(r *Feature, o *FeatureStateServicemeshAnalysisMessagesMessageBaseType) error {
return nil
}
|
package main
import (
"flag"
"os"
"github.com/gin-gonic/gin"
"github.com/kkurahar/go-gin-lightweight/app"
"github.com/kkurahar/go-gin-lightweight/helpers/config"
)
func showUsage() {
}
func main() {
env := flag.String("env", "development", "applicaiton runtime environment")
flag.Parse()
config.Loads("./config.yml")
switch *env {
case config.EnvDevelopment:
config.SetEnv(config.EnvDevelopment)
case config.EnvProduction:
config.SetEnv(config.EnvProduction)
gin.SetMode(gin.ReleaseMode)
default:
os.Exit(1)
}
app.Start()
}
|
// Copyright (c) 2020 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package starlark
import (
"fmt"
"github.com/pkg/errors"
"github.com/vmware-tanzu/crash-diagnostics/util"
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
)
// KubeConfigFn is built-in starlark function that wraps the kwargs into a dictionary value.
// The result is also added to the thread for other built-in to access.
// Starlark: kube_config(path=kubecf/path, [cluster_context=context_name])
func KubeConfigFn(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var path, clusterCtxName string
var provider *starlarkstruct.Struct
if err := starlark.UnpackArgs(
identifiers.kubeCfg, args, kwargs,
"cluster_context?", &clusterCtxName,
"path?", &path,
"capi_provider?", &provider,
); err != nil {
return starlark.None, fmt.Errorf("%s: %s", identifiers.kubeCfg, err)
}
// check if only one of the two options are present
if (len(path) == 0 && provider == nil) || (len(path) != 0 && provider != nil) {
return starlark.None, errors.New("need either path or capi_provider")
}
if len(path) == 0 {
val := provider.Constructor()
if constructor, ok := val.(starlark.String); ok {
constStr := constructor.GoString()
if constStr != identifiers.capvProvider && constStr != identifiers.capaProvider {
return starlark.None, errors.New("unknown capi provider")
}
}
pathVal, err := provider.Attr("kube_config")
if err != nil {
return starlark.None, errors.Wrap(err, "could not find the kubeconfig attribute")
}
pathStr, ok := pathVal.(starlark.String)
if !ok {
return starlark.None, errors.New("could not fetch kubeconfig")
}
path = pathStr.GoString()
}
path, err := util.ExpandPath(path)
if err != nil {
return starlark.None, err
}
structVal := starlarkstruct.FromStringDict(starlark.String(identifiers.kubeCfg), starlark.StringDict{
"cluster_context": starlark.String(clusterCtxName),
"path": starlark.String(path),
})
return structVal, nil
}
// addDefaultKubeConf initializes a Starlark Dict with default
// KUBECONFIG configuration data
func addDefaultKubeConf(thread *starlark.Thread) error {
args := []starlark.Tuple{
{starlark.String("path"), starlark.String(defaults.kubeconfig)},
}
conf, err := KubeConfigFn(thread, nil, nil, args)
if err != nil {
return err
}
thread.SetLocal(identifiers.kubeCfg, conf)
return nil
}
func getKubeConfigPathFromStruct(kubeConfigStructVal *starlarkstruct.Struct) (string, error) {
kvPathVal, err := kubeConfigStructVal.Attr("path")
if err != nil {
return "", errors.Wrap(err, "failed to extract kubeconfig path")
}
kvPathStrVal, ok := kvPathVal.(starlark.String)
if !ok {
return "", errors.New("failed to extract kubeconfig")
}
return kvPathStrVal.GoString(), nil
}
// getKubeConfigContextNameFromStruct returns the cluster name from the KubeConfig struct
// provided. If filed cluster_context not provided or unable to convert, it is returned
// as an empty context.
func getKubeConfigContextNameFromStruct(kubeConfigStructVal *starlarkstruct.Struct) string {
ctxVal, err := kubeConfigStructVal.Attr("cluster_context")
if err != nil {
return ""
}
ctxName, ok := ctxVal.(starlark.String)
if !ok {
return ""
}
return ctxName.GoString()
}
|
package main
import "github.com/gorilla/mux"
import "net/http"
import "io/ioutil"
import "encoding/json"
import "strconv"
type Request struct {
Url string `json:"url"`
}
type Response struct {
Key string `json:"key"`
}
var shortUrls = make([]string, 0)
func getKey() int {
return len(shortUrls)
}
func AddUrl(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var url Request
body, _ := ioutil.ReadAll(r.Body)
json.Unmarshal(body, &url)
key := getKey()
shortUrls = append(shortUrls, url.Url)
var response Response
response.Key = strconv.Itoa(key)
ans, _ := json.Marshal(response)
w.WriteHeader(http.StatusOK)
w.Write(ans)
}
func GetUrl(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key, _ := strconv.Atoi(vars["key"])
w.Header().Set("Location", shortUrls[key])
w.WriteHeader(http.StatusMovedPermanently)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", AddUrl).Methods("POST")
r.HandleFunc("/{key}", GetUrl).Methods("GET")
http.ListenAndServe(":8082", r)
}
|
package main
import "fmt"
// 1244. 力扣排行榜
// 新一轮的「力扣杯」编程大赛即将启动,为了动态显示参赛者的得分数据,需要设计一个排行榜 Leaderboard。
// 请你帮忙来设计这个 Leaderboard 类,使得它有如下 3 个函数:
// addScore(playerId, score):
// 假如参赛者已经在排行榜上,就给他的当前得分增加 score 点分值并更新排行。
// 假如该参赛者不在排行榜上,就把他添加到榜单上,并且将分数设置为 score。
// top(K):返回前 K 名参赛者的 得分总和。
// reset(playerId):将指定参赛者的成绩清零。题目保证在调用此函数前,该参赛者已有成绩,并且在榜单上。
// 请注意,在初始状态下,排行榜是空的。
// 提示:
// 1 <= playerId, K <= 10000
// 题目保证 K 小于或等于当前参赛者的数量
// 1 <= score <= 100
// 最多进行 1000 次函数调用
// https://leetcode-cn.com/problems/design-a-leaderboard
func main() {
board := Constructor()
board.AddScore(1, 73)
board.AddScore(2, 56)
board.AddScore(3, 39)
board.AddScore(4, 51)
board.AddScore(5, 4)
fmt.Println(board.Top(1))
board.Reset(1)
board.Reset(2)
board.AddScore(2, 51)
fmt.Println(board.Top(3))
}
type Leaderboard struct {
players map[int]int // playerId =>score
scores []int // 排好序的score
}
func Constructor() Leaderboard {
return Leaderboard{
players: make(map[int]int),
}
}
func (this *Leaderboard) AddScore(playerId int, score int) {
if _, exist := this.players[playerId]; exist {
oldScore := this.players[playerId]
this.players[playerId] += score
this.deleteScore(oldScore)
this.insertScore(this.players[playerId])
} else {
this.players[playerId] = score
this.insertScore(score)
}
}
func (this *Leaderboard) Top(K int) (scores int) {
i := len(this.scores) - 1
for K > 0 {
scores += this.scores[i]
i--
K--
}
return scores
}
func (this *Leaderboard) Reset(playerId int) {
this.deleteScore(this.players[playerId])
delete(this.players, playerId)
}
// score总是存在
func (this *Leaderboard) deleteScore(score int) {
i := this.search(score)
this.scores = append(this.scores[:i], this.scores[i+1:]...)
}
func (this Leaderboard) search(score int) (index int) {
index = -1
left, right := 0, len(this.scores)-1
for left <= right {
mid := left + ((right - left) >> 1)
if this.scores[mid] == score {
return mid
} else if this.scores[mid] < score {
left = mid + 1
} else {
right = mid - 1
}
}
return index
}
func (this *Leaderboard) insertScore(score int) {
n := len(this.scores)
if n == 0 || this.scores[n-1] <= score {
this.scores = append(this.scores, score)
return
} else if this.scores[0] >= score {
this.scores = append([]int{score}, this.scores...)
return
}
// 找到小于等于score的最大元素
left, right := 0, n-1
target := -1
for left <= right {
mid := left + ((right - left) >> 1)
if this.scores[mid] <= score {
target = mid
left = mid + 1
} else {
right = mid - 1
}
}
tmp := make([]int, n+1)
copy(tmp, this.scores[:target+1])
tmp[target+1] = score
copy(tmp[target+2:], this.scores[target+1:])
this.scores = tmp
}
|
package g2util
import (
"runtime"
"runtime/debug"
"sync"
"sync/atomic"
"time"
"github.com/andeya/goutil"
"github.com/panjf2000/ants/v2"
)
var goPoolSize = runtime.NumCPU() * 1000
// GoPool ...goroutine pool
type GoPool struct {
LevelLogger LevelLogger `inject:""`
Grace *Graceful `inject:""`
wait *sync.WaitGroup
pool *ants.Pool
mu sync.RWMutex
size atomic.Int32
}
// Constructor ...
func (g *GoPool) Constructor() {
g.wait = new(sync.WaitGroup)
g.pool, _ = ants.NewPool(goPoolSize, ants.WithOptions(ants.Options{
PanicHandler: func(p interface{}) {
panicData := goutil.PanicTrace(4)
g.LevelLogger.Printf("[Goroutine] worker exits from a panic: [%v] \n%s\n\n", p, panicData)
},
}))
g.Grace.RegProcessor(g)
}
// AfterShutdown ...
func (g *GoPool) AfterShutdown() {
TimeoutExecFunc(g.wait.Wait, time.Second*30)
g.pool.Release()
}
// Pool ...
func (g *GoPool) Pool() *ants.Pool { return g.pool }
type goFunc func() (err error)
// goFunc ...
func (g *GoPool) goFuncDo(fn goFunc) {
if e := fn(); e != nil {
//g.LevelLogger.Warnf("Goroutine worker exits with a error: %s\n\n", e.Error())
g.LevelLogger.Errorf("[Goroutine] %s\n%+v\n%s\n", e.Error(), e, debug.Stack())
}
}
// Submit ...
//func (g *GoPool) Submit(fn goFunc) {
// g.wait.Add(1)
// _ = g.pool.Submit(func() {
// defer g.wait.Done()
// g.goFuncDo(fn)
// })
//}
// Go ... 直接执行,不加入wait队列
func (g *GoPool) Go(fn goFunc) {
g.size.Add(1)
g.mu.RLock()
if g.size.Load() >= int32(goPoolSize-10) {
g.LevelLogger.Errorf("[Goroutine] goroutine pool is full, size: %d", g.size.Load())
}
g.mu.RUnlock()
_ = g.pool.Submit(func() {
g.goFuncDo(fn)
g.size.Add(-1)
})
}
|
//go:generate go run github.com/UnnoTed/fileb0x b0x.json
package main
import (
"flag"
"net/http"
"github.com/DigitalOnUs/douk/api"
"github.com/DigitalOnUs/douk/static"
"goji.io"
"goji.io/pat"
)
// APIs
var (
address string
)
func init() {
flag.StringVar(&address, "listen", "localhost:7001", "listen address")
}
func main() {
mux := goji.NewMux()
flag.Parse()
// For debugging replace the static.HTTP to defaultPath
// and _ comment the import for statics pre-compiled in the binary
mux.HandleFunc(pat.Post("/api/consulize"), api.Consulize)
mux.Handle(pat.Get("/*"), http.FileServer(static.HTTP))
//mux.Handle(pat.Get("/*"), http.FileServer(http.Dir("./public")))
http.ListenAndServe(address, mux)
}
|
package bus
import "github.com/scottshotgg/proximity/pkg/listener"
type (
// Bus ...
Bus interface {
Insert(msg *listener.Msg) error
Remove() (*listener.Msg, error)
Close() error
}
)
|
package caaa
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00200101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.002.001.01 Document"`
Message *AcceptorAuthorisationResponseV01 `xml:"AccptrAuthstnRspn"`
}
func (d *Document00200101) AddMessage() *AcceptorAuthorisationResponseV01 {
d.Message = new(AcceptorAuthorisationResponseV01)
return d.Message
}
// Scope
// The AcceptorAuthorisationResponse message is sent by the acquirer to inform the card acceptor of the outcome of the authorisation process. The message can be sent directly to the acceptor or through an agent.
// Usage
// The AcceptorAuthorisationResponse message is used to indicate one of the possible outcomes of an authorisation process:
// - a successful authorisation;
// - a decline from the acquirer for financial reasons;
// - a decline from the acquirer for technical reasons (for instance, a timeout).
type AcceptorAuthorisationResponseV01 struct {
// Authorisation response message management information.
Header *iso20022.Header1 `xml:"Hdr"`
// Information related to the response of the authorisation.
AuthorisationResponse *iso20022.AcceptorAuthorisationResponse1 `xml:"AuthstnRspn"`
// Trailer of the message containing a MAC.
SecurityTrailer *iso20022.ContentInformationType3 `xml:"SctyTrlr"`
}
func (a *AcceptorAuthorisationResponseV01) AddHeader() *iso20022.Header1 {
a.Header = new(iso20022.Header1)
return a.Header
}
func (a *AcceptorAuthorisationResponseV01) AddAuthorisationResponse() *iso20022.AcceptorAuthorisationResponse1 {
a.AuthorisationResponse = new(iso20022.AcceptorAuthorisationResponse1)
return a.AuthorisationResponse
}
func (a *AcceptorAuthorisationResponseV01) AddSecurityTrailer() *iso20022.ContentInformationType3 {
a.SecurityTrailer = new(iso20022.ContentInformationType3)
return a.SecurityTrailer
}
|
package main
import (
"testing"
"github.com/almighty/almighty-core/app/test"
)
func TestAuthorizeLoginOK(t *testing.T) {
controller := LoginController{}
resp := test.AuthorizeLoginOK(t, &controller)
if resp.Token == "" {
t.Error("Token not generated")
}
}
func TestShowVersionOK(t *testing.T) {
controller := VersionController{}
resp := test.ShowVersionOK(t, &controller)
if resp.Commit != "0" {
t.Error("Commit not found")
}
}
var ValidJWTToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NjA4MzUyNzUsInNjb3BlcyI6WyJzeXN0ZW0iXX0.OHsz9bIN9nKemd8Rdm9lYapXOknh5nwvCN8ZD_YIVfCZ54MkoKiIjj_VsGclRMCykDtXD4Omg2mWuiaEDPoP4nHRjlWfup3Us29k78cpImBz6FwfK08J39pKr0Y7s-Qdpq_XGwdTEWx7Hk33nrgyZVdMfE4nRjCulkIWbhOxNDdjKqUSo3zknRQRWzZhVl8a1cMNG6EetFHe-pCEr3WpreeRZcoL948smll_16WYB8r3t2-jtW7CmrJwSx7ZMopD-AvOaAGsiExgNRUd5YcSX0zEl5mjwnSb-rqemQt4_BHs0zgufyDw5MtH0ZG8phNIbyWt3G1VaO3CqDt_Ixxh7Q"
var InValidJWTToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NjA4MzUyNzUsInNjb3BlcyI6WyJzeXN0ZW0iXX0.OHsz9bIN9nKemd8Rdm9lYapXOknh5nwvCN8ZD_YIVfCZ54MkoKiIjj_VsGclRMCykDtXD4Omg2mWuiaEDPoP4nHRjlWfup3Us29k78cpImBz6FwfK08J39pKr0Y7s-Qdpq_XGwdTEWx7Hk33nrgyZVdMfE4nRjCulkIWbhOxNDdjKqUSo3zknRQRWzZhVl8a1cMNG6EetFHe-pCEr3WpreeRZcoL948smll_16WYB8r3t2-jtW7CmrJwSx7ZMopD-AvOaAGsiExgNRUd5YcSX0zEl5mjwnSb-rqemQt4_BHs0zgufyDw5MtH0ZG8phNIbyWt3G1VaO3CqDt_Ixxh7"
|
package main
import (
"errors"
"fmt"
"github.com/J0-nas/drawGraph"
"log"
"math"
"math/rand"
"os"
"sort"
"strconv"
"sync"
"time"
)
type Point struct {
X, Y float64
}
type ByX []Point
func (a ByX) Len() int {
return len(a)
}
func (a ByX) Swap(i, j int) {
pTemp := a[i]
a[i] = a[j]
a[j] = pTemp
// , a[j] = a[j], a[i]
}
func (a ByX) Less(i, j int) bool {
if a[i].X == a[j].X {
return a[i].Y < a[j].Y
}
return a[i].X < a[j].X
}
func main() {
var wG sync.WaitGroup
workChannel := make(chan int)
m := make(map[int]int)
for worker := 0; worker < 100; worker++ {
// Increment the WaitGroup counter.
wG.Add(1)
go func(wChannel <-chan int, id int, waitGrp *sync.WaitGroup) {
defer waitGrp.Done()
completedWork := 0
for i := range wChannel {
//fmt.Println("Worker ", id, " working on ", i)
convex("convexHull_" + strconv.Itoa(i))
completedWork++
}
m[id] = completedWork
//fmt.Println("Done.")
}(workChannel, worker, &wG)
}
wG.Add(1)
go func(wChannel chan int, wGrp *sync.WaitGroup) {
defer wGrp.Done()
for work := 0; work < 10000; work++ {
wChannel <- work
}
//fmt.Println("Create work done.")
close(workChannel)
}(workChannel, &wG)
wG.Wait()
var res []Point
for key, value := range m {
res = append(res, Point{float64(key), float64(value)})
}
sort.Sort(ByX(res))
for _, r := range res {
fmt.Println("Key: ", int(r.X), " computed: ", int(r.Y), " convex hulls")
}
}
func convex(name string) {
height := 1000.0
width := 1000.0
var points []Point
seed := time.Now().UTC().UnixNano()
rand.Seed(seed)
//fmt.Println("seed: ", seed)
for start := 0; start < int(rand.Float64()*1000)+3; start++ {
points = append(points, Point{rand.Float64() * width, rand.Float64() * height})
}
d := drawGraph.NewImage(height, width)
for i := range points {
err := d.AddPoint(points[i].X, points[i].Y)
if err != nil {
log.Println(err)
}
}
convexHull, err := buildConvexHull_2(points)
//convexHull := buildConvexHull_2(points)
if err != nil {
log.Println(err)
}
if len(convexHull) <= 2 {
log.Println("Too few points in convex hull")
os.Exit(1)
}
for j := 0; j <= len(convexHull)-2; j++ {
err := d.AddLine(convexHull[j].X, convexHull[j].Y, convexHull[j+1].X, convexHull[j+1].Y)
if err != nil {
fmt.Println("\n\nError!\n\n")
log.Println(err)
}
}
d.SaveImage(name)
}
func buildConvexHull_2(points []Point) (result []Point, err error) {
sort.Sort(ByX(points))
//fmt.Println("sorted ", points)
if len(points) < 3 {
log.Println(points)
return points, errors.New("Too few points.")
}
origin := points[0]
nextToOrigin := points[1]
currentPoint := origin
nextPoint := nextToOrigin
points = points[2:]
result = []Point{
currentPoint,
nextPoint,
}
left := 0.0
for _, p := range points {
left = ccw(currentPoint, nextPoint, p)
if left < 0.0 {
l := len(result) - 1
if l == 1 { //only 2 elements in result, special treatment
result = append(result[:1], p)
nextPoint = p
} else {
for j := l; j >= 1; j-- {
if ccw(result[j-1], result[j], p) >= 0 {
result = append(result[:j+1], p)
//fmt.Println("new hull: ", result)
currentPoint = result[j]
nextPoint = p
break
}
if j == 1 {
result = append(result[:1], p)
nextPoint = p
currentPoint = result[0]
}
}
}
} else {
result = append(result, p)
currentPoint = nextPoint
nextPoint = p
}
}
currentPoint = origin
nextPoint = nextToOrigin
result_2 := []Point{
currentPoint,
nextPoint,
}
right := 0.0
for _, p := range points {
right = ccw(currentPoint, nextPoint, p)
if right > 0.0 {
l := len(result_2) - 1
if l == 1 { //only 2 elements in result, special treatment
result_2 = append(result_2[:1], p)
nextPoint = p
} else {
for j := l; j >= 1; j-- {
if ccw(result_2[j-1], result_2[j], p) <= 0 {
result_2 = append(result_2[:j+1], p)
//fmt.Println("new hull: ", result_2)
currentPoint = result_2[j]
nextPoint = p
break
}
if j == 1 {
result_2 = append(result_2[:1], p)
nextPoint = p
currentPoint = result_2[0]
}
}
}
} else {
result_2 = append(result_2, p)
currentPoint = nextPoint
nextPoint = p
}
}
for h := len(result_2) - 1; h > 0; h-- {
result = append(result, result_2[h])
}
result = append(result, origin)
return result, nil
}
/*(p1, p2, p3) is counterclockwise iff result > 0 => p3 is on the righthand side*/
func ccw(p1, p2, p3 Point) float64 {
i := (p1.X-p2.X)*(p3.Y-p2.Y) - (p3.X-p2.X)*(p1.Y-p2.Y)
//fmt.Println(i)
return i
}
func buildConvexHull_1(points []Point) []Point {
//fmt.Println(points)
sort.Sort(ByX(points))
//fmt.Println(points)
length := len(points)
currentPoint := points[length-1]
originPoint := points[length-1]
points = points[:(length - 1)]
//fmt.Println(points)
var a, c float64
results := []Point{
originPoint,
}
atOrigin := false
for alpha := math.Pi/2 - 0.001; alpha > -(math.Pi + math.Pi/2 + 0.001); alpha -= 0.001 {
a = -math.Tan(alpha)
c = currentPoint.Y + a*currentPoint.X
for i, p := range points {
if checkPoint(a, c, p) {
currentPoint = p
if currentPoint == originPoint {
atOrigin = true
}
points = append(points[:i], points[i+1:]...)
fmt.Println("Added point... ", p)
results = append(results, p)
break
}
}
if atOrigin {
break
}
}
fmt.Print("Convec Hull: ")
fmt.Println(results)
return results
}
func distance(a, c float64, p Point) float64 {
return math.Abs((a*p.X + p.Y - c) / math.Sqrt(a*a+1))
}
func checkPoint(a, c float64, p Point) bool {
return distance(a, c, p) <= 0.2
}
func (p *Point) Equals(q Point) bool {
return p.X == q.X && p.Y == q.Y
}
/*points = []Point{
{100, 200},
{800, 200},
{600, 300},
{300, 500},
{700, 700},
{700, 100},
{400, 900},
}
result := []Point{
{100, 200},
{600, 300},
{300, 500},
{700, 700},
{400, 900},
}
sort.Sort(ByX(points))
sort.Sort(ByX(result))
fmt.Println(points)
for i, p := range points {
for _, r := range result {
if p.X > r.X {
break
} else if p.Equals(r) {
if i == len(points)-1 {
points = points[:i]
} else if i == 0 {
points = points[1:]
} else {
points = append(points[:i], points[i+1:]...)
}
}
}
}
fmt.Println(result)
fmt.Println(points)*/
|
package dump_test
import (
"os"
"testing"
"github.com/Kretech/xgo/dump"
"github.com/Kretech/xgo/encoding"
)
func ExampleDump() {
// just for testing
dump.ShowFileLine1 = false
dump.DefaultWriter = os.Stdout
a := 1
b := `2`
c := map[string]interface{}{b: a}
dump.Dump(a, b, c)
// Output:
// a => 1
// b => "2"
// c => map[string]interface{} (len=1) {
// "2" => 1
// }
}
func TestDump_Example(t *testing.T) {
t.Run(`base`, func(t *testing.T) {
dump.OptShowUint8sAsString = true
dump.OptShowUint8AsChar = true
aInt := 1
bStr := `sf`
cMap := map[string]interface{}{"name": "z", "age": 14, "bytes": []byte(string(`abc`)), `aByte`: byte('c')}
dArray := []interface{}{&cMap, aInt, bStr}
dump.Dump(aInt, &aInt, &bStr, bStr, cMap, dArray, cMap["name"], dArray[2], dArray[aInt])
})
t.Run(`operator`, func(t *testing.T) {
a := 0.1
b := 0.2
cc := 0.3
dump.Dump(a + b)
dump.Dump(a+b == cc)
dump.Dump(a+b > cc)
dump.Dump(a+b < cc)
})
t.Run(`interface`, func(t *testing.T) {
var err error
var emptyInterface interface{}
var emptyMap map[string]interface{}
var emptySlice []interface{}
dump.Dump(err, emptyInterface, emptyMap, emptySlice, nil)
})
t.Run(`struct`, func(t *testing.T) {
dump.ShowFileLine1 = true
defer func() {
dump.ShowFileLine1 = false
}()
type String string
type car struct {
Speed int
Owner interface{}
}
type Person struct {
Name String
age int
Interests []string
friends [4]*Person
Cars []*car
action []func() string
}
p1 := Person{
Name: "lisan", age: 19, Interests: []string{"a", "b"}, Cars: []*car{{Speed: 120}},
action: []func() string{
func() string { return "sayHi" },
func() string { return "sayBay" },
},
}
p2 := &p1
dump.Dump(p2)
type Person2 Person
p3 := Person2(p1)
dump.Dump(p3)
type Person3 = Person2
p4 := Person3(p1)
dump.Dump(p4)
type Person4 struct {
Person Person
Person2
}
p5 := Person4{p1, p4}
dump.Dump(p5)
})
userId := func() int { return 4 }
dump.Dump(userId())
dump.Dump(userId2())
_s := _S{}
dump.Dump(_s.a())
dump.Dump(_s.b(`t`))
num3 := 3
dump.Dump(`abc`)
dump.Dump(encoding.JsonEncode(`abc`))
dump.Dump(encoding.JsonEncode(map[string]interface{}{"a": num3}))
ch := make(chan bool)
dump.Dump(ch)
}
type _S struct{}
func (this *_S) a() string {
return `_s.a`
}
func (this *_S) b(t string) string {
return `_s.b(` + t + `)`
}
func userId2() int {
return 8
}
|
package musixmatch
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
const (
//BaseURL is the API URL
BaseURL = "http://api.musixmatch.com/ws/1.1"
defaultHTTPTimeout = 30 * time.Second
)
// Key is the MusixMatch API key
var Key string
var httpClient = &http.Client{Timeout: defaultHTTPTimeout}
// BackendService is an interface to be implemented by MusixMatch clients
type BackendService interface {
Call(method string, path string, params string, v *Return) error
}
// Backend holds the user API key and the HTTP client
type Backend struct {
Key string
HTTPClient *http.Client
}
// GetBackend returns a Backend with the default HTTPClient
func GetBackend() Backend {
return Backend{
Key: Key,
HTTPClient: httpClient,
}
}
// SetBackend sets a Backend type with a custom HTTPClient
func SetBackend(client *http.Client) Backend {
return Backend{
Key: Key,
HTTPClient: client,
}
}
// Call is a helper function to execute an API request
func (b Backend) Call(method string, path string, params string, v *Return) error {
if params == "" {
return errors.New("params are required")
}
req, err := http.NewRequest(
method,
fmt.Sprintf("%s/%s?%s&apikey=%s", BaseURL, path, params, b.Key),
nil,
)
if err != nil {
return err
}
resp, err := b.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&v); err != nil {
return err
}
return CheckStatusCode(v.Header.StatusCode)
}
// Return is the type that will hold the response from the API request
type Return struct {
Message `json:"message"`
}
// Message represents the JSON object returned from the API request
type Message struct {
Header Header `json:"header"`
Body *json.RawMessage `json:"body"`
}
// Header contains the Status Code returned from the API request
type Header struct {
StatusCode int `json:"status_code"`
}
// CheckStatusCode checks for response errors
func CheckStatusCode(code int) error {
switch code {
case http.StatusOK:
return nil
case http.StatusBadRequest:
return errors.New("400: bad request")
case http.StatusUnauthorized:
return errors.New("401: authetication failed")
case http.StatusPaymentRequired:
return errors.New("402: usage limit has been reached")
case http.StatusForbidden:
return errors.New("403: not authorized to perform this operation")
case http.StatusNotFound:
return errors.New("404: resource not found")
case http.StatusMethodNotAllowed:
return errors.New("405: requested method not found")
case http.StatusServiceUnavailable:
return errors.New("503: service unavailable")
default:
return errors.New("500: internal server error")
}
}
|
package main
import (
"bufio"
"os"
)
func main() {
file, _ := os.Open("input/day11.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
rows1 := make([][]byte, 0)
for scanner.Scan() {
bytes := make([]byte, 100)
copy(bytes, scanner.Bytes())
rows1 = append(rows1, bytes)
}
rows2 := duplicate(rows1)
for {
changeCount := 0
rows1, changeCount = iteratePart1(rows1)
if changeCount == 0 {
println(countOccupied(rows1))
break
}
}
for {
changeCount := 0
rows2, changeCount = iteratePart2(rows2)
if changeCount == 0 {
println(countOccupied(rows2))
break
}
}
}
func iteratePart1(rows [][]byte) ([][]byte, int) {
result := duplicate(rows)
changeCount := 0
for y := 0; y < len(rows); y += 1 {
for x := 0; x < len(rows[0]); x += 1 {
state := rows[y][x]
neighbors := countNeighbors(rows, y, x)
if state == 'L' && neighbors == 0 {
result[y][x] = '#'
changeCount += 1
} else if state == '#' && neighbors >= 4 {
result[y][x] = 'L'
changeCount += 1
}
}
}
return result, changeCount
}
func iteratePart2(rows [][]byte) ([][]byte, int) {
result := duplicate(rows)
changeCount := 0
for y := 0; y < len(rows); y += 1 {
for x := 0; x < len(rows[0]); x += 1 {
state := rows[y][x]
neighbors := countVisible(rows, y, x)
if state == 'L' && neighbors == 0 {
result[y][x] = '#'
changeCount += 1
} else if state == '#' && neighbors >= 5 {
result[y][x] = 'L'
changeCount += 1
}
}
}
return result, changeCount
}
func countOccupied(rows [][]byte) int {
count := 0
for i := 0; i < len(rows); i++ {
for j := 0; j < len(rows[0]); j++ {
if rows[i][j] == '#' {
count += 1
}
}
}
return count
}
func countVisible(rows [][]byte, r, c int) int {
return isVisibleOccupied(rows, r, c, -1, -1) +
isVisibleOccupied(rows, r, c, -1, 0) +
isVisibleOccupied(rows, r, c, -1, 1) +
isVisibleOccupied(rows, r, c, 0, -1) +
isVisibleOccupied(rows, r, c, 0, 1) +
isVisibleOccupied(rows, r, c, 1, -1) +
isVisibleOccupied(rows, r, c, 1, 0) +
isVisibleOccupied(rows, r, c, 1, 1)
}
func isVisibleOccupied(rows [][]byte, r int, c int, y int, x int) int {
neighborY := r + y
neighborX := c + x
if neighborY > -1 && neighborY < len(rows) {
if neighborX > -1 && neighborX < len(rows[0]) {
val := rows[neighborY][neighborX]
if val == '#' {
return 1
} else if val == 'L' {
return 0
} else if val == '.' {
return isVisibleOccupied(rows, neighborY, neighborX, y, x)
}
}
}
return 0
}
func countNeighbors(rows [][]byte, r, c int) int {
return isOccupied(rows, r, c, -1, -1) +
isOccupied(rows, r, c, -1, 0) +
isOccupied(rows, r, c, -1, 1) +
isOccupied(rows, r, c, 0, -1) +
isOccupied(rows, r, c, 0, 1) +
isOccupied(rows, r, c, 1, -1) +
isOccupied(rows, r, c, 1, 0) +
isOccupied(rows, r, c, 1, 1)
}
func isOccupied(rows [][]byte, r, c, y, x int) int {
neighborY := r + y
neighborX := c + x
if neighborY > -1 && neighborY < len(rows) {
if neighborX > -1 && neighborX < len(rows[0]) {
val := rows[neighborY][neighborX]
if val == '#' {
return 1
}
}
}
return 0
}
func duplicate(rows [][]byte) [][]byte {
n := len(rows)
m := len(rows[0])
duplicate := make([][]byte, n)
for i := range rows {
dupRow := make([]byte, m)
copy(dupRow, rows[i])
duplicate[i] = dupRow
}
return duplicate
}
|
package model
type XmlNamespace struct {
// Name of the XML Namespace reference
Prefix string `json:"prefix,omitempty"`
// Source of the XML Namespace reference
Uri string `json:"uri,omitempty"`
}
|
package handler
import (
"github.com/golang/mock/gomock"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"go.mongodb.org/mongo-driver/bson/primitive"
"mytodoapp/model"
"mytodoapp/repository"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func Test_ShouldReturnEmptyTodoList(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
todos := make([]model.TodoModel, 0)
repo := repository.NewMockRepository(controller)
repo.EXPECT().FindAll().Return(todos).Times(1)
handler := TodoHandler{repo}
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/todos", nil)
req.Header.Set(echo.HeaderAccept, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
ctx := e.NewContext(req, rec)
expected := `[]
`
if assert.NoError(t, handler.HandleGetAll(ctx)) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, expected, rec.Body.String())
}
}
func Test_ShouldFindAllTodos(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
var todos []model.TodoModel
primId, _ := primitive.ObjectIDFromHex("60798540288942e18e737a34")
todos = append(todos, model.TodoModel{
Id: primId,
Title: "example my todo",
})
repo := repository.NewMockRepository(controller)
repo.EXPECT().FindAll().Return(todos).Times(1)
handler := TodoHandler{repo}
expectVal := `[{"id":"60798540288942e18e737a34","title":"example my todo"}]
`
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/todo", nil)
req.Header.Set(echo.HeaderAccept, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
ctx := e.NewContext(req, rec)
if assert.NoError(t, handler.HandleGetAll(ctx)) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, expectVal, rec.Body.String())
}
}
func Test_ShouldCreateTodo(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
primId, _ := primitive.ObjectIDFromHex("60798540288942e18e737a34")
request := model.TodoModel{Id: primId, Title: "example my todo"}
requestAsString := `{"id":"60798540288942e18e737a34","title":"example my todo"}`
repo := repository.NewMockRepository(controller)
handler := TodoHandler{repo}
repo.EXPECT().Create(gomock.Eq(request)).Return(requestAsString).Times(1)
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/todo", strings.NewReader(requestAsString))
req.Header.Set(echo.HeaderAccept, echo.MIMEApplicationJSON)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
ctx := e.NewContext(req, rec)
if assert.NoError(t, handler.HandleCreate(ctx)) {
assert.Equal(t, http.StatusCreated, rec.Code)
}
}
func Test_ShouldDeleteTodo(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repo := repository.NewMockRepository(controller)
repo.EXPECT().Delete(gomock.Eq("60798540288942e18e737a34"))
handler := TodoHandler{repo}
e := echo.New()
req := httptest.NewRequest(http.MethodDelete, "/todos/60798540288942e18e737a34", nil)
rec := httptest.NewRecorder()
ctx := e.NewContext(req, rec)
ctx.SetParamNames("id")
ctx.SetParamValues("60798540288942e18e737a34")
if assert.NoError(t, handler.HandleDelete(ctx)) {
assert.Equal(t, http.StatusNoContent, rec.Code)
}
}
|
package main
import (
"log"
_ "github.com/snapiz/go-vue-starter/services/main/src/db"
"github.com/spf13/cobra"
)
var root = &cobra.Command{
Use: "gvs-main-cli",
Short: "Go vue start main CLI tool",
}
func main() {
if err := root.Execute(); err != nil {
log.Fatal(err)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.