text stringlengths 11 4.05M |
|---|
package main
import (
"bytes"
"compress/gzip"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
)
// ------------------------------------ 获取实时基础数据
func GetDatas() map[string]*GeneralData {
gds := make(map[string]*GeneralData)
// 获取原始数据
initUrl := "http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery112407378636087109598_1528454080519&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&js=(%7Bdata%3A%5B(x)%5D%2CrecordsTotal%3A(tot)%2CrecordsFiltered%3A(tot)%7D)&cmd=C._A&sty=FCOIATC&st=(ChangePercent)&sr=-1&p=1&ps=10000&_=1528454080520"
header := make(map[string]string)
header["Accept"] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
header["Accept-Encoding"] = "gzip, deflate"
header["Accept-Language"] = "zh-CN,zh;q=0.9,en;q=0.8"
header["Cache-Control"] = "n-cache"
header["Connection"] = "keep-alive"
header["Host"] = "nufm.dfcfw.com"
header["Pragma"] = "no-cache"
header["Upgrade-Insecure-Requests"] = "1"
header["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
client := &http.Client{}
req, err := http.NewRequest("GET", initUrl, nil)
if err != nil {
log.Fatal(err)
}
for key, v := range header {
req.Header.Add(key, v)
}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// 读取数据
reader, err := gzip.NewReader(bytes.NewBuffer(body))
if err != nil {
log.Fatal(err)
}
defer reader.Close()
tmpBytes, err := ioutil.ReadAll(reader)
if err != nil {
log.Fatal(err)
}
// 解析数据
str := string(tmpBytes)
ret := strings.Split(strings.Split(str, "data:[\"")[1], "\"],")
strData := ret[0]
datas := strings.Split(strData, "\",\"")
for _, data := range datas {
arr := strings.Split(data, ",")
// 排除长创业版和科创板
if strings.HasPrefix(arr[1], "300") || strings.HasPrefix(arr[1], "688") {
continue
}
// 排除停牌的和ST的
if arr[4] == "-" || strings.HasPrefix(arr[2], "*ST") || strings.HasPrefix(arr[2], "ST") {
continue
}
currentPrice, _ := strconv.ParseFloat(arr[3], 64)
upAndDownRange, _ := strconv.ParseFloat(arr[5], 64)
turnover, _ := strconv.ParseFloat(arr[7], 64)
high, _ := strconv.ParseFloat(arr[9], 64)
low, _ := strconv.ParseFloat(arr[10], 64)
open, _ := strconv.ParseFloat(arr[11], 64)
close, _ := strconv.ParseFloat(arr[12], 64)
min5, _ := strconv.ParseFloat(arr[13], 64)
changehands, _ := strconv.ParseFloat(arr[15], 64)
circulation, _ := strconv.ParseFloat(arr[19], 64)
gds[arr[1]] = &GeneralData{
stockType: arr[0],
stockCode: arr[1],
stockName: arr[2],
currentPrice: currentPrice,
upAndDownRange: upAndDownRange,
turnover: turnover / 100000000,
high: high,
low: low,
open: open,
close: close,
min5: min5,
changehands: changehands,
circulation: circulation / 100000000,
}
}
return gds
}
// ------------------------------------- 获取实时资金数据
func GetMoneyData() map[string]*GeneralData {
gds := GetDatas()
// 获取原始数据
header := make(map[string]string)
header["Accept"] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
header["Accept-Encoding"] = "gzip, deflate"
header["Accept-Language"] = "zh-CN,zh;q=0.9,en;q=0.8"
header["Cache-Control"] = "n-cache"
header["Connection"] = "keep-alive"
header["Host"] = "nufm.dfcfw.com"
header["Pragma"] = "no-cache"
header["Upgrade-Insecure-Requests"] = "1"
header["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
client := &http.Client{}
// 只抓取主力资金流入的前3000支票
req, err := http.NewRequest("GET", "http://push2.eastmoney.com/api/qt/clist/get?pn=1&pz=3000&po=1&np=1&ut=b2884a393a59ad64002292a3e90d46a5&fltt=2&invt=2&fid0=f4001&fid=f62&fs=m:0+t:6+f:!2,m:0+t:13+f:!2,m:0+t:80+f:!2,m:1+t:2+f:!2,m:1+t:23+f:!2,m:0+t:7+f:!2,m:1+t:3+f:!2&stat=1&fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124&rt=52415130&cb=jQuery183019370468044060885_1572453915798&_=1572453916366", nil)
if err != nil {
log.Fatal(err)
}
for key, v := range header {
req.Header.Add(key, v)
}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
reader, err := gzip.NewReader(bytes.NewBuffer(body))
if err != nil {
log.Fatal(err)
}
defer reader.Close()
tmpBytes, err := ioutil.ReadAll(reader)
if err != nil {
log.Fatal(err)
}
// 读取数据
rawDataStr := string(tmpBytes)
originDataStr := strings.Split(strings.Split(rawDataStr, "(")[1], ")")[0]
// 解析数据
var data = make(map[string]interface{})
err = json.Unmarshal([]byte(originDataStr), &data)
if err != nil {
log.Fatal(err)
}
tmpData := data["data"].(map[string]interface{})
list := tmpData["diff"].([]interface{})
// 重组数据
for _, v := range list {
g := v.(map[string]interface{})
if gd, ok := gds[g["f12"].(string)]; ok {
gd.mainV = g["f62"].(float64) / 100000000
gd.cBigV = g["f66"].(float64)
gd.bigV = g["f72"].(float64)
gd.middleV = g["f78"].(float64)
gd.smallV = g["f84"].(float64)
gd.mainP = g["f69"].(float64)
}
}
// 删除无需使用的股
for k, gd := range gds {
if gd.mainV == 0 {
delete(gds, k)
}
}
return gds
}
|
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"../models"
"github.com/gorilla/mux"
)
func CreatePerson(w http.ResponseWriter, r *http.Request) {
person := &models.Person{}
json.NewDecoder(r.Body).Decode(person)
createdPerson := db.Create(person)
var errMessage = createdPerson.Error
if createdPerson.Error != nil {
fmt.Println(errMessage)
}
json.NewEncoder(w).Encode(createdPerson)
}
func UpdatePerson(w http.ResponseWriter, r *http.Request) {
person := &models.Person{}
params := mux.Vars(r)
var id = params["id"]
db.First(&person, id)
json.NewDecoder(r.Body).Decode(person)
db.Save(&person)
json.NewEncoder(w).Encode(&person)
}
func DeletePerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var id = params["id"]
var person models.Person
db.First(&person, id)
db.Delete(&person)
json.NewEncoder(w).Encode("Person deleted")
}
func GetPerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var id = params["id"]
var person models.Person
// var mealsIds []int
db.Preload("MealRatings", "Ate = true").Preload("MealRatings.EatenMeal").Preload("MealRatings.EatenMeal.Meal").First(&person, id)
json.NewEncoder(w).Encode(&person)
}
func GetPeople(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var userID = params["user_id"]
var people []models.Person
db.Where("user_id = ?", userID).Find(&people)
json.NewEncoder(w).Encode(&people)
}
|
package cmd
import (
"fmt"
"strconv"
"github.com/balaji-dongare/gophercises/CLI/task/dbrepository"
"github.com/spf13/cobra"
)
var doTask = dbrepository.MarkTaskAsDone
//DoTask Marks task as completed
var DoTask = &cobra.Command{
Use: "do",
Short: "do is a CLI command to mark task as completed ",
Run: func(cmd *cobra.Command, args []string) {
var ids []int
if len(args) > 0 {
for _, arg := range args {
id, err := strconv.Atoi(arg)
if err != nil {
fmt.Println("Failed to parse Arg:", arg)
} else {
ids = append(ids, id)
}
}
//fmt.Println(ids)
notValidIds, taskdone, err := doTask(ids)
note := ""
if err != nil {
note = "Sorry! Unable to mark as Complete."
fmt.Printf("%v due to : %v", note, err)
} else {
if len(notValidIds) >= 1 {
note = fmt.Sprintf("%v these ids not exist", notValidIds)
} else {
for i, task := range taskdone {
fmt.Printf("%d. %v", i+1, task)
}
}
}
} else {
fmt.Printf("Please provide task id")
}
},
}
func init() {
RootCmd.AddCommand(DoTask)
}
|
package main
import (
"fmt"
"github.com/PieterD/slides/go-training/reverse"
)
func main() {
fmt.Println(reverse.Reverse("!dlrow ,olleH"))
}
|
/*
if you want to know the number of iterations that are going to be executed in advance, you cannot
use the range keyword.
The range keyword also works with Go maps, which makes it pretty
handy and my preferred way of iteration.
One of the biggest problems with arrays is out-of-bounds errors, which means trying to
access an element that does not exist. This is like trying to access the sixth element of an
array with only five elements. The Go compiler considers compiler issues that can be
detected as compiler errors because this helps the development workflow. Therefore, the
Go compiler can detect out-of-bounds array access errors:
./a.go:10: invalid array index -1 (index must be non-negative)
./a.go:10: invalid array index 20 (out of bounds for 2-element array)
for ind, value := range arr{
v : = value
for index,val := range v{
fmt.println(val)
}
}
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
*/
package main
import (
"fmt"
)
func main() {
anArray := [4]int{1, 2, 4, -4}
twoD := [4][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14,
15, 16}}
threeD := [2][2][2]int{{{1, 0}, {-2, 4}}, {{5, -1}, {7, 0}}}
fmt.Println("The length of", anArray, "is", len(anArray))
fmt.Println("The first element of", twoD, "is", twoD[0][0])
fmt.Println("The length of", threeD, "is", len(threeD))
for value := range twoD {
row := value
fmt.Println(row, "sssssssssssss")
// for k := 0; k < len(row); k++ {
// fmt.Println(valuee)
// }
}
for i := 0; i < len(threeD); i++ {
v := threeD[i]
for j := 0; j < len(v); j++ {
m := v[j]
for k := 0; k < len(m); k++ {
fmt.Print(m[k], " ")
}
}
fmt.Println()
}
for _, v := range threeD {
for _, m := range v {
for _, s := range m {
fmt.Print(s, " ")
}
}
fmt.Println()
}
}
|
package geo
import (
"math"
"net"
"github.com/golang/geo/s2"
)
type Provider interface {
HasCountry() (bool, error)
GetCountry(ip net.IP) (country, continent string, netmask int)
HasASN() (bool, error)
GetASN(net.IP) (asn string, netmask int, err error)
HasLocation() (bool, error)
GetLocation(ip net.IP) (location *Location, err error)
}
const MAX_DISTANCE = 360
type Location struct {
Country string
Continent string
RegionGroup string
Region string
Latitude float64
Longitude float64
Netmask int
}
func (l *Location) MaxDistance() float64 {
return MAX_DISTANCE
}
func (l *Location) Distance(to *Location) float64 {
if to == nil {
return MAX_DISTANCE
}
ll1 := s2.LatLngFromDegrees(l.Latitude, l.Longitude)
ll2 := s2.LatLngFromDegrees(to.Latitude, to.Longitude)
angle := ll1.Distance(ll2)
return math.Abs(angle.Degrees())
}
|
package pwd
import (
"flag"
"fmt"
"os"
)
var (
flagSet = flag.NewFlagSet("pwd", flag.PanicOnError)
helpFlag = flagSet.Bool("help", false, "Show this help")
)
//Pwd outputs the current working directory
func Pwd(call []string) error {
e := flagSet.Parse(call[1:])
if e != nil {
return e
}
if flagSet.NArg() > 0 {
fmt.Println("Expected 0 args, got 1")
return nil
}
if *helpFlag {
println("`pwd`")
flagSet.PrintDefaults()
return nil
}
pwd, _ := os.Getwd()
println(pwd)
return nil
}
|
package main
import (
"bufio"
"encoding/csv"
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"math"
"os"
"strconv"
"strings"
"github.com/360EntSecGroup-Skylar/excelize"
)
type report struct {
XMLName xml.Name `xml:"Report"`
Ps []p `xml:"rp>pss>ps"`
}
type p struct {
Number string `xml:"m,attr"`
Price string `xml:"awod,attr"`
}
func xls(a report, b map[string]float64) {
xlsx := excelize.NewFile()
// Create a new sheet.
index := xlsx.NewSheet("Sheet1")
// Set value of a cell.
i := 1
for key, value := range b {
xlsx.SetCellValue("Sheet1", "A"+strconv.Itoa(i), key)
xlsx.SetCellValue("Sheet1", "B"+strconv.Itoa(i), value)
i++
}
xlsx.SetCellValue("Sheet1", "A"+strconv.Itoa(i), "Итого:")
xlsx.SetCellValue("Sheet1", "B"+strconv.Itoa(i), itog(a.Ps))
// Set active sheet of the workbook.
xlsx.SetActiveSheet(index)
// Save xlsx file by the given path.
error := xlsx.SaveAs("./Book1.xlsx")
if error != nil {
fmt.Println(error)
}
}
func itog(f []p) float64 {
var q float64
for _, item := range f {
str := strings.Replace(item.Price, ",", ".", -1)
i, err := strconv.ParseFloat(str, 32)
if err == nil {
q = q + i
}
}
p := math.Round(q*100) / 100
return p
}
func main() {
csvFile, err := os.Open("mvz.csv")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("\nSuccessfully opened file mvz.csv\n")
defer func() {
if err = csvFile.Close(); err != nil {
log.Fatal(err)
}
}()
reader := csv.NewReader(csvFile)
reader.FieldsPerRecord = 2
reader.Comment = '#'
rawCSVdata, err := reader.ReadAll()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
xmlFile, err := os.Open("report.xml")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Successfully opened file report.xml\n\n")
defer func() {
if err = xmlFile.Close(); err != nil {
log.Fatal(err)
}
}()
xmlReadFile, err := ioutil.ReadAll(xmlFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
report := report{}
xml.Unmarshal(xmlReadFile, &report)
var sprav = make(map[string]string)
for _, value := range rawCSVdata {
sprav[value[0]] = value[1]
}
var result = make(map[string]float64)
for _, item := range report.Ps {
st := strings.Replace(item.Price, ",", ".", -1)
strToInt, err := strconv.ParseFloat(st, 64)
if err != nil {
fmt.Println("Error:", err)
return
}
result[sprav[item.Number]] += strToInt
}
for _, orderForNumber := range report.Ps {
fmt.Printf("%+v\n", orderForNumber)
}
xls(report, result)
in := bufio.NewScanner(os.Stdin)
in.Scan()
}
|
package lang
import (
"fmt"
)
type Shape interface {
Draw()
}
type Rectangle struct {
}
func (Rectangle) Draw() {
fmt.Println("inside rectangle::draw()")
}
type Square struct {
}
func (Square) Draw() {
fmt.Println("inside square::draw()")
}
type Circle struct {
}
func (Circle) Draw() {
fmt.Println("inside circle::draw()")
}
type ShapeFactory struct {
}
func (this ShapeFactory) getShape(shapeType string) Shape {
if shapeType == "c" {
return Circle{}
} else if shapeType == "r" {
return Rectangle{}
} else if shapeType == "s" {
return Square{}
}
return nil
}
|
package hutoma
type hutomaChatResponse struct {
ChatID string `json:"chatId"`
Timestamp int64 `json:"timestamp"`
Result struct {
Score float64 `json:"score"`
Query string `json:"query"`
Answer string `json:"answer"`
History string `json:"history"`
ElapsedTime float64 `json:"elapsedTime"`
} `json:"result"`
Status struct {
Code int `json:"code"`
Info string `json:"info"`
} `json:"status"`
}
|
package models
import (
"github.com/astaxie/beego/orm"
"time"
)
//邀请表
func (a *TokenskyUserInvite) TableName() string {
return TokenskyUserInviteTBName()
}
//用户邀请表
type TokenskyUserInvite struct {
Id int `orm:"column(id)"json:"id"form:"id"`
//邀请人
From *TokenskyUser `orm:"rel(fk);column(from)"json:"-"form:"-"`
//被邀请人
To int `orm:"column(to)"json:"-"form:"-"`
//创建时间
CreateTime time.Time `orm:"type(datetime);column(create_time)"json:"-"form:"-"`
//
UserId int `orm:"-"json:"userId"form:"-"`
Count int `orm:"-"json:"count"form:"-"`
}
//
func TokenskyUserInviteFormToAmount()map[int]*TokenskyUserInvite{
o := orm.NewOrm()
query := o.QueryTable(TokenskyUserInviteTBName())
num := 1
count,_ := query.Count()
mapp2 := make(map[int]*TokenskyUserInvite)
for count>0{
data := make([]*TokenskyUserInvite,0)
query.Limit(500,(num-1)*500).All(&data)
count -= 500
num++
for _,obj := range data{
if obj2,found := mapp2[obj.From.UserId];!found{
mapp2[obj.From.UserId] = obj
obj.Count++
obj.UserId = obj.From.UserId
}else {
obj2.Count++
}
}
}
return mapp2
} |
package hal
import (
"bytes"
"encoding/json"
"errors"
"fmt"
)
var (
ErrPropMandatory = errors.New("The href property is mandatory.")
)
type link struct {
// REQUIRED
// Its value is either a URI [RFC3986] or a URI Template [RFC6570].<br>
// If the value is a URI Template then the Link Object SHOULD have a
// "templated" attribute whose value is true.
href string
// OPTIONAL
// Its value is boolean and SHOULD be true when the Link Object's "href"
// property is a URI Template.<br>
// Its value SHOULD be considered false if it is undefined or any other
// value than true.
templated bool
// OPTIONAL
// Its value is a string used as a hint to indicate the media type
// expected when dereferencing the target resource.
mediaType string
// OPTIONAL
// Its presence indicates that the link is to be deprecated (i.e.
// removed) at a future date. Its value is a URL that SHOULD provide
// further information about the deprecation.
// A client SHOULD provide some notification (for example, by logging a
// warning message) whenever it traverses over a link that has this
// property. The notification SHOULD include the deprecation property's
// value so that a client maintainer can easily find information about
// the deprecation.
deprecation string
// OPTIONAL
// Its value MAY be used as a secondary key for selecting Link Objects
// which share the same relation type.
name string
// OPTIONAL
// Its value is a string which is a URI that hints about the profile (as
// defined by [I-D.wilde-profile-link]) of the target resource.
profile string
// OPTIONAL
// Its value is a string and is intended for labelling the link with a
// human-readable identifier (as defined by [RFC5988]).
title string
// OPTIONAL
// Its value is a string and is intended for indicating the language of
// the target resource (as defined by [RFC5988]).
hreflang string
}
type LinkOptionalParam struct {
Templated bool
MediaType string
Deprecation string
Name string
Profile string
Title string
Hreflang string
}
// NewLink create a Link
// params :
// - href string
// optional params :
// - lop LinkOptionalParam
func NewLink(href string, lop LinkOptionalParam) (*link, error) {
href, err := trimSpace(href)
if err != nil {
return nil, err
}
l := link{href, lop.Templated, lop.MediaType, lop.Deprecation, lop.Name, lop.Profile, lop.Title, lop.Hreflang}
return &l, nil
}
// Href get the href link property
func (l *link) Href() string {
return l.href
}
// Templated get the templated link property
func (l *link) Templated() bool {
return l.templated
}
// Type get the mediaType link property
func (l *link) Type() string {
return l.mediaType
}
// Deprecation get the deprecation link property
func (l *link) Deprecation() string {
return l.deprecation
}
// Name get the name link property
func (l *link) Name() string {
return l.name
}
// Profile get the profile link property
func (l *link) Profile() string {
return l.profile
}
// Title get the profile link property
func (l *link) Title() string {
return l.title
}
// Hreflang get the hreflang link property
func (l *link) Hreflang() string {
return l.hreflang
}
// SetHref is setting the href of link property
func (l *link) SetHref(h string) error {
h, err := trimSpace(h)
if err != nil {
return err
}
l.href = h
return nil
}
// SetTemplated is setting the templated of link property
func (l *link) SetTemplated(t bool) {
l.templated = t
}
// SetType is setting the mediaType of link property
func (l *link) SetType(t string) {
l.mediaType = t
}
// SetDeprecation is setting the deprecation of link property
func (l *link) SetDeprecation(d string) {
l.deprecation = d
}
// SetName is setting the name of link property
func (l *link) SetName(n string) {
l.name = n
}
// SetProfile is setting the profile of link property
func (l *link) SetProfile(p string) {
l.profile = p
}
// SetTitle is setting the title of link property
func (l *link) SetTitle(p string) {
l.title = p
}
// SetHreflang is setting the hreflang of link property
func (l *link) SetHreflang(h string) {
l.hreflang = h
}
// NewLinkFromJson is creating a link from a json
// this will trow an error if the JSON is not valid
func NewLinkFromJson(data []byte) (*link, error) {
var aux struct {
Href string `json:"href"`
Templated bool `json:"templated"`
MediaType string `json:"type"`
Deprecation string `json:"deprecation"`
Name string `json:"name"`
Profile string `json:"profile"`
Title string `json:"title"`
Hreflang string `json:"hreflang"`
}
dec := json.NewDecoder(bytes.NewReader(data))
if err := dec.Decode(&aux); err != nil {
return nil, fmt.Errorf("JSON must be a string, an array or an object : ", err)
}
l := link{
aux.Href,
aux.Templated,
aux.MediaType,
aux.Deprecation,
aux.Name,
aux.Profile,
aux.Title,
aux.Hreflang}
return &l, nil
}
// String is using the interface of strings for all usages toString()
func (l *link) String() string {
s := "(href=" + l.href
b := "false"
if l.templated {
b = "true"
}
s += ", temlpated=" + b
if len(l.mediaType) > 0 {
s += ", type=" + l.mediaType
}
if len(l.deprecation) > 0 {
s += ", deprecation=" + l.deprecation
}
if len(l.name) > 0 {
s += ", name=" + l.name
}
if len(l.profile) > 0 {
s += ", profile=" + l.profile
}
if len(l.title) > 0 {
s += ", title=" + l.title
}
if len(l.hreflang) > 0 {
s += ", hreflang=" + l.hreflang
}
s += ")"
return s
}
|
package controllers
import (
"gomongo/src/database"
"gomongo/src/models"
"log"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"golang.org/x/crypto/bcrypt"
)
func Login(c *gin.Context) {
db, client := database.GetDatabase()
collection := db.Collection("Users")
var loginUser models.Login
var user models.User
err := c.ShouldBindJSON(&loginUser)
if err != nil {
c.JSON(400, gin.H{
"error": err.Error(),
})
return
}
collection.FindOne(c, bson.D{
primitive.E{
Key: "email", Value: loginUser.Email,
},
}).Decode(&user)
log.Println()
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginUser.Password))
if err != nil {
c.JSON(400, gin.H{
"error": "Email or password invalid",
})
return
}
client.Disconnect(c)
c.JSON(200, gin.H{
"message": "login sucess!",
})
}
|
// Copyright 2018-2020 Authors of Cilium
//
// 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 k8s
import (
"reflect"
"github.com/cilium/cilium/pkg/annotation"
"github.com/cilium/cilium/pkg/comparator"
cilium_v2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
"github.com/cilium/cilium/pkg/k8s/types"
"github.com/cilium/cilium/pkg/logging/logfields"
v1 "k8s.io/api/core/v1"
"k8s.io/api/discovery/v1beta1"
networkingv1 "k8s.io/api/networking/v1"
"k8s.io/client-go/tools/cache"
)
func CopyObjToV1NetworkPolicy(obj interface{}) *types.NetworkPolicy {
k8sNP, ok := obj.(*types.NetworkPolicy)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid k8s v1 NetworkPolicy")
return nil
}
return k8sNP.DeepCopy()
}
func CopyObjToV1Services(obj interface{}) *types.Service {
svc, ok := obj.(*types.Service)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid k8s v1 Service")
return nil
}
return svc.DeepCopy()
}
func CopyObjToV1Endpoints(obj interface{}) *types.Endpoints {
ep, ok := obj.(*types.Endpoints)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid k8s v1 Endpoints")
return nil
}
return ep.DeepCopy()
}
func CopyObjToV1EndpointSlice(obj interface{}) *types.EndpointSlice {
ep, ok := obj.(*types.EndpointSlice)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid k8s v1 EndpointSlice")
return nil
}
return ep.DeepCopy()
}
func CopyObjToV2CNP(obj interface{}) *types.SlimCNP {
cnp, ok := obj.(*types.SlimCNP)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid k8s v2 CiliumNetworkPolicy")
return nil
}
return cnp.DeepCopy()
}
func CopyObjToV1Pod(obj interface{}) *types.Pod {
pod, ok := obj.(*types.Pod)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid k8s v1 Pod")
return nil
}
return pod.DeepCopy()
}
func CopyObjToV1Node(obj interface{}) *types.Node {
node, ok := obj.(*types.Node)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid k8s v1 Node")
return nil
}
return node.DeepCopy()
}
func CopyObjToV1Namespace(obj interface{}) *types.Namespace {
ns, ok := obj.(*types.Namespace)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid k8s v1 Namespace")
return nil
}
return ns.DeepCopy()
}
func EqualV1NetworkPolicy(np1, np2 *types.NetworkPolicy) bool {
// As Cilium uses all of the Spec from a NP it's not probably not worth
// it to create a dedicated deep equal function to compare both network
// policies.
return np1.Name == np2.Name &&
np1.Namespace == np2.Namespace &&
reflect.DeepEqual(np1.Spec, np2.Spec)
}
func EqualV1Services(k8sSVC1, k8sSVC2 *types.Service) bool {
// Service annotations are used to mark services as global, shared, etc.
if !comparator.MapStringEquals(k8sSVC1.GetAnnotations(), k8sSVC2.GetAnnotations()) {
return false
}
svcID1, svc1 := ParseService(k8sSVC1)
svcID2, svc2 := ParseService(k8sSVC2)
if svcID1 != svcID2 {
return false
}
// Please write all the equalness logic inside the K8sServiceInfo.Equals()
// method.
return svc1.DeepEquals(svc2)
}
func EqualV1Endpoints(ep1, ep2 *types.Endpoints) bool {
// We only care about the Name, Namespace and Subsets of a particular
// endpoint.
return ep1.Name == ep2.Name &&
ep1.Namespace == ep2.Namespace &&
reflect.DeepEqual(ep1.Subsets, ep2.Subsets)
}
func EqualV1EndpointSlice(ep1, ep2 *types.EndpointSlice) bool {
// We only care about the Name, Namespace and Subsets of a particular
// endpoint.
// AddressType is omitted because it's immutable after EndpointSlice's
// creation.
return ep1.Name == ep2.Name &&
ep1.Namespace == ep2.Namespace &&
reflect.DeepEqual(ep1.Endpoints, ep2.Endpoints) &&
reflect.DeepEqual(ep1.Ports, ep2.Ports)
}
func EqualV2CNP(cnp1, cnp2 *types.SlimCNP) bool {
if !(cnp1.Name == cnp2.Name && cnp1.Namespace == cnp2.Namespace) {
return false
}
// Ignore v1.LastAppliedConfigAnnotation annotation
lastAppliedCfgAnnotation1, ok1 := cnp1.GetAnnotations()[v1.LastAppliedConfigAnnotation]
lastAppliedCfgAnnotation2, ok2 := cnp2.GetAnnotations()[v1.LastAppliedConfigAnnotation]
defer func() {
if ok1 && cnp1.GetAnnotations() != nil {
cnp1.GetAnnotations()[v1.LastAppliedConfigAnnotation] = lastAppliedCfgAnnotation1
}
if ok2 && cnp2.GetAnnotations() != nil {
cnp2.GetAnnotations()[v1.LastAppliedConfigAnnotation] = lastAppliedCfgAnnotation2
}
}()
delete(cnp1.GetAnnotations(), v1.LastAppliedConfigAnnotation)
delete(cnp2.GetAnnotations(), v1.LastAppliedConfigAnnotation)
return comparator.MapStringEquals(cnp1.GetAnnotations(), cnp2.GetAnnotations()) &&
reflect.DeepEqual(cnp1.Spec, cnp2.Spec) &&
reflect.DeepEqual(cnp1.Specs, cnp2.Specs)
}
// AnnotationsEqual returns whether the annotation with any key in
// relevantAnnotations is equal in anno1 and anno2.
func AnnotationsEqual(relevantAnnotations []string, anno1, anno2 map[string]string) bool {
for _, an := range relevantAnnotations {
if anno1[an] != anno2[an] {
return false
}
}
return true
}
func EqualV1PodContainers(c1, c2 types.PodContainer) bool {
if c1.Name != c2.Name ||
c1.Image != c2.Image {
return false
}
if len(c1.VolumeMountsPaths) != len(c2.VolumeMountsPaths) {
return false
}
for i, vlmMount1 := range c1.VolumeMountsPaths {
if vlmMount1 != c2.VolumeMountsPaths[i] {
return false
}
}
return true
}
func EqualV1Pod(pod1, pod2 *types.Pod) bool {
// We only care about the HostIP, the PodIP and the labels of the pods.
if pod1.StatusPodIP != pod2.StatusPodIP ||
pod1.StatusHostIP != pod2.StatusHostIP ||
pod1.SpecServiceAccountName != pod2.SpecServiceAccountName ||
pod1.SpecHostNetwork != pod2.SpecHostNetwork {
return false
}
if !AnnotationsEqual([]string{annotation.ProxyVisibility}, pod1.GetAnnotations(), pod2.GetAnnotations()) {
return false
}
oldPodLabels := pod1.GetLabels()
newPodLabels := pod2.GetLabels()
if !comparator.MapStringEquals(oldPodLabels, newPodLabels) {
return false
}
if len(pod1.SpecContainers) != len(pod2.SpecContainers) {
return false
}
for i, c1 := range pod1.SpecContainers {
if !EqualV1PodContainers(c1, pod2.SpecContainers[i]) {
return false
}
}
return true
}
func EqualV1Node(node1, node2 *types.Node) bool {
if node1.GetObjectMeta().GetName() != node2.GetObjectMeta().GetName() {
return false
}
anno1 := node1.GetAnnotations()
anno2 := node2.GetAnnotations()
annotationsWeCareAbout := []string{
annotation.CiliumHostIP,
annotation.CiliumHostIPv6,
annotation.V4HealthName,
annotation.V6HealthName,
}
for _, an := range annotationsWeCareAbout {
if anno1[an] != anno2[an] {
return false
}
}
if len(node1.SpecTaints) != len(node2.SpecTaints) {
return false
}
for i, taint2 := range node2.SpecTaints {
taint1 := node1.SpecTaints[i]
if !taint1.MatchTaint(&taint2) {
return false
}
if taint1.Value != taint2.Value {
return false
}
if !taint1.TimeAdded.Equal(taint2.TimeAdded) {
return false
}
}
return true
}
func EqualV1Namespace(ns1, ns2 *types.Namespace) bool {
// we only care about namespace labels.
return ns1.Name == ns2.Name &&
comparator.MapStringEquals(ns1.GetLabels(), ns2.GetLabels())
}
// ConvertToNetworkPolicy converts a *networkingv1.NetworkPolicy into a
// *types.NetworkPolicy or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.NetworkPolicy in its Obj.
// If the given obj can't be cast into either *networkingv1.NetworkPolicy
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
func ConvertToNetworkPolicy(obj interface{}) interface{} {
// TODO check which fields we really need
switch concreteObj := obj.(type) {
case *networkingv1.NetworkPolicy:
return &types.NetworkPolicy{
NetworkPolicy: concreteObj,
}
case cache.DeletedFinalStateUnknown:
netPol, ok := concreteObj.Obj.(*networkingv1.NetworkPolicy)
if !ok {
return obj
}
return cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.NetworkPolicy{
NetworkPolicy: netPol,
},
}
default:
return obj
}
}
// ConvertToK8sService converts a *v1.Service into a
// *types.Service or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.Service in its Obj.
// If the given obj can't be cast into either *v1.Service
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
func ConvertToK8sService(obj interface{}) interface{} {
// TODO check which fields we really need
switch concreteObj := obj.(type) {
case *v1.Service:
return &types.Service{
Service: concreteObj,
}
case cache.DeletedFinalStateUnknown:
svc, ok := concreteObj.Obj.(*v1.Service)
if !ok {
return obj
}
return cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.Service{
Service: svc,
},
}
default:
return obj
}
}
// ConvertToK8sEndpoints converts a *v1.Endpoints into a
// *types.Endpoints or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.Endpoints in its Obj.
// If the given obj can't be cast into either *v1.Endpoints
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
func ConvertToK8sEndpoints(obj interface{}) interface{} {
// TODO check which fields we really need
switch concreteObj := obj.(type) {
case *v1.Endpoints:
return &types.Endpoints{
Endpoints: concreteObj,
}
case cache.DeletedFinalStateUnknown:
eps, ok := concreteObj.Obj.(*v1.Endpoints)
if !ok {
return obj
}
return cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.Endpoints{
Endpoints: eps,
},
}
default:
return obj
}
}
// ConvertToK8sEndpointSlice converts a *v1beta1.EndpointSlice into a
// *types.Endpoints or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.Endpoints in its Obj.
// If the given obj can't be cast into either *v1.Endpoints
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
func ConvertToK8sEndpointSlice(obj interface{}) interface{} {
// TODO check which fields we really need
switch concreteObj := obj.(type) {
case *v1beta1.EndpointSlice:
return &types.EndpointSlice{
EndpointSlice: concreteObj,
}
case cache.DeletedFinalStateUnknown:
eps, ok := concreteObj.Obj.(*v1beta1.EndpointSlice)
if !ok {
return obj
}
return cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.EndpointSlice{
EndpointSlice: eps,
},
}
default:
return obj
}
}
// ConvertToCCNPWithStatus converts a *cilium_v2.CiliumClusterwideNetworkPolicy
// into *types.SlimCNP or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.SlimCNP in its Obj.
// If the given obj can't be cast into either *cilium_v2.CiliumClusterwideNetworkPolicy
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
func ConvertToCCNPWithStatus(obj interface{}) interface{} {
switch concreteObj := obj.(type) {
case *cilium_v2.CiliumClusterwideNetworkPolicy:
t := &types.SlimCNP{
CiliumNetworkPolicy: concreteObj.CiliumNetworkPolicy,
}
t.Status = concreteObj.Status
return t
case cache.DeletedFinalStateUnknown:
cnp, ok := concreteObj.Obj.(*cilium_v2.CiliumClusterwideNetworkPolicy)
if !ok {
return obj
}
t := &types.SlimCNP{
CiliumNetworkPolicy: cnp.CiliumNetworkPolicy,
}
t.Status = cnp.Status
return cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: t,
}
default:
return obj
}
}
// ConvertToCNPWithStatus converts a *cilium_v2.CiliumNetworkPolicy or a
// *cilium_v2.CiliumClusterwideNetworkPolicy into a
// *types.SlimCNP or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.SlimCNP in its Obj.
// If the given obj can't be cast into either *cilium_v2.CiliumNetworkPolicy
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
func ConvertToCNPWithStatus(obj interface{}) interface{} {
switch concreteObj := obj.(type) {
case *cilium_v2.CiliumNetworkPolicy:
return &types.SlimCNP{
CiliumNetworkPolicy: concreteObj,
}
case cache.DeletedFinalStateUnknown:
cnp, ok := concreteObj.Obj.(*cilium_v2.CiliumNetworkPolicy)
if !ok {
return obj
}
return cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.SlimCNP{
CiliumNetworkPolicy: cnp,
},
}
default:
return obj
}
}
// ConvertToCCNP converts a *cilium_v2.CiliumClusterwideNetworkPolicy into a
// *types.SlimCNP without the Status field of the given CNP, or a
// cache.DeletedFinalStateUnknown into a cache.DeletedFinalStateUnknown with a
// *types.SlimCNP, also without the Status field of the given CNP, in its Obj.
// If the given obj can't be cast into either *cilium_v2.CiliumClusterwideNetworkPolicy
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
// WARNING calling this function will set *all* fields of the given CNP as
// empty.
func ConvertToCCNP(obj interface{}) interface{} {
switch concreteObj := obj.(type) {
case *cilium_v2.CiliumClusterwideNetworkPolicy:
cnp := &types.SlimCNP{
CiliumNetworkPolicy: &cilium_v2.CiliumNetworkPolicy{
TypeMeta: concreteObj.TypeMeta,
ObjectMeta: concreteObj.ObjectMeta,
Spec: concreteObj.Spec,
Specs: concreteObj.Specs,
},
}
*concreteObj = cilium_v2.CiliumClusterwideNetworkPolicy{}
return cnp
case cache.DeletedFinalStateUnknown:
cnp, ok := concreteObj.Obj.(*cilium_v2.CiliumClusterwideNetworkPolicy)
if !ok {
return obj
}
dfsu := cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.SlimCNP{
CiliumNetworkPolicy: &cilium_v2.CiliumNetworkPolicy{
TypeMeta: cnp.TypeMeta,
ObjectMeta: cnp.ObjectMeta,
Spec: cnp.Spec,
Specs: cnp.Specs,
},
},
}
*cnp = cilium_v2.CiliumClusterwideNetworkPolicy{}
return dfsu
default:
return obj
}
}
// ConvertToCNP converts a *cilium_v2.CiliumNetworkPolicy into a
// *types.SlimCNP without the Status field of the given CNP, or a
// cache.DeletedFinalStateUnknown into a cache.DeletedFinalStateUnknown with a
// *types.SlimCNP, also without the Status field of the given CNP, in its Obj.
// If the given obj can't be cast into either *cilium_v2.CiliumNetworkPolicy
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
// WARNING calling this function will set *all* fields of the given CNP as
// empty.
func ConvertToCNP(obj interface{}) interface{} {
switch concreteObj := obj.(type) {
case *cilium_v2.CiliumNetworkPolicy:
cnp := &types.SlimCNP{
CiliumNetworkPolicy: &cilium_v2.CiliumNetworkPolicy{
TypeMeta: concreteObj.TypeMeta,
ObjectMeta: concreteObj.ObjectMeta,
Spec: concreteObj.Spec,
Specs: concreteObj.Specs,
},
}
*concreteObj = cilium_v2.CiliumNetworkPolicy{}
return cnp
case cache.DeletedFinalStateUnknown:
cnp, ok := concreteObj.Obj.(*cilium_v2.CiliumNetworkPolicy)
if !ok {
return obj
}
dfsu := cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.SlimCNP{
CiliumNetworkPolicy: &cilium_v2.CiliumNetworkPolicy{
TypeMeta: cnp.TypeMeta,
ObjectMeta: cnp.ObjectMeta,
Spec: cnp.Spec,
Specs: cnp.Specs,
},
},
}
*cnp = cilium_v2.CiliumNetworkPolicy{}
return dfsu
default:
return obj
}
}
// ConvertToPod converts a *v1.Pod into a
// *types.Pod or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.Pod in its Obj.
// If the given obj can't be cast into either *v1.Pod
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
// WARNING calling this function will set *all* fields of the given Pod as
// empty.
func ConvertToPod(obj interface{}) interface{} {
switch concreteObj := obj.(type) {
case *v1.Pod:
var containers []types.PodContainer
for _, c := range concreteObj.Spec.Containers {
var vmps []string
for _, cvm := range c.VolumeMounts {
vmps = append(vmps, cvm.MountPath)
}
pc := types.PodContainer{
Name: c.Name,
Image: c.Image,
VolumeMountsPaths: vmps,
}
containers = append(containers, pc)
}
p := &types.Pod{
TypeMeta: concreteObj.TypeMeta,
ObjectMeta: concreteObj.ObjectMeta,
StatusPodIP: concreteObj.Status.PodIP,
StatusHostIP: concreteObj.Status.HostIP,
SpecServiceAccountName: concreteObj.Spec.ServiceAccountName,
SpecHostNetwork: concreteObj.Spec.HostNetwork,
SpecContainers: containers,
}
*concreteObj = v1.Pod{}
return p
case cache.DeletedFinalStateUnknown:
pod, ok := concreteObj.Obj.(*v1.Pod)
if !ok {
return obj
}
var containers []types.PodContainer
for _, c := range pod.Spec.Containers {
var vmps []string
for _, cvm := range c.VolumeMounts {
vmps = append(vmps, cvm.MountPath)
}
pc := types.PodContainer{
Name: c.Name,
Image: c.Image,
VolumeMountsPaths: vmps,
}
containers = append(containers, pc)
}
dfsu := cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.Pod{
TypeMeta: pod.TypeMeta,
ObjectMeta: pod.ObjectMeta,
StatusPodIP: pod.Status.PodIP,
StatusHostIP: pod.Status.HostIP,
SpecServiceAccountName: pod.Spec.ServiceAccountName,
SpecHostNetwork: pod.Spec.HostNetwork,
SpecContainers: containers,
},
}
*pod = v1.Pod{}
return dfsu
default:
return obj
}
}
// ConvertToNode converts a *v1.Node into a
// *types.Node or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.Node in its Obj.
// If the given obj can't be cast into either *v1.Node
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
// WARNING calling this function will set *all* fields of the given Node as
// empty.
func ConvertToNode(obj interface{}) interface{} {
switch concreteObj := obj.(type) {
case *v1.Node:
p := &types.Node{
TypeMeta: concreteObj.TypeMeta,
ObjectMeta: concreteObj.ObjectMeta,
StatusAddresses: concreteObj.Status.Addresses,
SpecPodCIDR: concreteObj.Spec.PodCIDR,
SpecPodCIDRs: concreteObj.Spec.PodCIDRs,
SpecTaints: concreteObj.Spec.Taints,
}
*concreteObj = v1.Node{}
return p
case cache.DeletedFinalStateUnknown:
node, ok := concreteObj.Obj.(*v1.Node)
if !ok {
return obj
}
dfsu := cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.Node{
TypeMeta: node.TypeMeta,
ObjectMeta: node.ObjectMeta,
StatusAddresses: node.Status.Addresses,
SpecPodCIDR: node.Spec.PodCIDR,
SpecPodCIDRs: node.Spec.PodCIDRs,
SpecTaints: node.Spec.Taints,
},
}
*node = v1.Node{}
return dfsu
default:
return obj
}
}
// ConvertToNamespace converts a *v1.Namespace into a
// *types.Namespace or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *types.Namespace in its Obj.
// If the given obj can't be cast into either *v1.Namespace
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
// WARNING calling this function will set *all* fields of the given Namespace as
// empty.
func ConvertToNamespace(obj interface{}) interface{} {
switch concreteObj := obj.(type) {
case *v1.Namespace:
p := &types.Namespace{
TypeMeta: concreteObj.TypeMeta,
ObjectMeta: concreteObj.ObjectMeta,
}
*concreteObj = v1.Namespace{}
return p
case cache.DeletedFinalStateUnknown:
namespace, ok := concreteObj.Obj.(*v1.Namespace)
if !ok {
return obj
}
dfsu := cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.Namespace{
TypeMeta: namespace.TypeMeta,
ObjectMeta: namespace.ObjectMeta,
},
}
*namespace = v1.Namespace{}
return dfsu
default:
return obj
}
}
// ConvertToCiliumNode converts a *cilium_v2.CiliumNode into a
// *cilium_v2.CiliumNode or a cache.DeletedFinalStateUnknown into
// a cache.DeletedFinalStateUnknown with a *cilium_v2.CiliumNode in its Obj.
// If the given obj can't be cast into either *cilium_v2.CiliumNode
// nor cache.DeletedFinalStateUnknown, the original obj is returned.
func ConvertToCiliumNode(obj interface{}) interface{} {
// TODO create a slim type of the CiliumNode
switch concreteObj := obj.(type) {
case *cilium_v2.CiliumNode:
return concreteObj
case cache.DeletedFinalStateUnknown:
ciliumNode, ok := concreteObj.Obj.(*cilium_v2.CiliumNode)
if !ok {
return obj
}
return cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: ciliumNode,
}
default:
return obj
}
}
// CopyObjToCiliumNode attempts to cast object to a CiliumNode object and
// returns a deep copy if the castin succeeds. Otherwise, nil is returned.
func CopyObjToCiliumNode(obj interface{}) *cilium_v2.CiliumNode {
cn, ok := obj.(*cilium_v2.CiliumNode)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid CiliumNode")
return nil
}
return cn.DeepCopy()
}
// ConvertToCiliumEndpoint converts a *cilium_v2.CiliumEndpoint into a
// *types.CiliumEndpoint or a cache.DeletedFinalStateUnknown into a
// cache.DeletedFinalStateUnknown with a *types.CiliumEndpoint in its Obj.
// If the given obj can't be cast into either *cilium_v2.CiliumEndpoint nor
// cache.DeletedFinalStateUnknown, the original obj is returned.
func ConvertToCiliumEndpoint(obj interface{}) interface{} {
switch concreteObj := obj.(type) {
case *cilium_v2.CiliumEndpoint:
p := &types.CiliumEndpoint{
TypeMeta: concreteObj.TypeMeta,
ObjectMeta: concreteObj.ObjectMeta,
Encryption: concreteObj.Status.Encryption.DeepCopy(),
Identity: concreteObj.Status.Identity.DeepCopy(),
Networking: concreteObj.Status.Networking.DeepCopy(),
}
*concreteObj = cilium_v2.CiliumEndpoint{}
return p
case cache.DeletedFinalStateUnknown:
ciliumEndpoint, ok := concreteObj.Obj.(*cilium_v2.CiliumEndpoint)
if !ok {
return obj
}
dfsu := cache.DeletedFinalStateUnknown{
Key: concreteObj.Key,
Obj: &types.CiliumEndpoint{
TypeMeta: ciliumEndpoint.TypeMeta,
ObjectMeta: ciliumEndpoint.ObjectMeta,
Encryption: ciliumEndpoint.Status.Encryption.DeepCopy(),
Identity: ciliumEndpoint.Status.Identity.DeepCopy(),
Networking: ciliumEndpoint.Status.Networking.DeepCopy(),
},
}
*ciliumEndpoint = cilium_v2.CiliumEndpoint{}
return dfsu
default:
return obj
}
}
// CopyObjToCiliumEndpoint attempts to cast object to a CiliumEndpoint object
// and returns a deep copy if the castin succeeds. Otherwise, nil is returned.
func CopyObjToCiliumEndpoint(obj interface{}) *types.CiliumEndpoint {
ce, ok := obj.(*types.CiliumEndpoint)
if !ok {
log.WithField(logfields.Object, logfields.Repr(obj)).
Warn("Ignoring invalid CiliumEndpoint")
return nil
}
return ce.DeepCopy()
}
|
// 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 *EndpointPolicy) validate() error {
if err := dcl.Required(r, "name"); err != nil {
return err
}
if err := dcl.Required(r, "type"); err != nil {
return err
}
if err := dcl.Required(r, "endpointMatcher"); err != nil {
return err
}
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.EndpointMatcher) {
if err := r.EndpointMatcher.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.TrafficPortSelector) {
if err := r.TrafficPortSelector.validate(); err != nil {
return err
}
}
return nil
}
func (r *EndpointPolicyEndpointMatcher) validate() error {
if !dcl.IsEmptyValueIndirect(r.MetadataLabelMatcher) {
if err := r.MetadataLabelMatcher.validate(); err != nil {
return err
}
}
return nil
}
func (r *EndpointPolicyEndpointMatcherMetadataLabelMatcher) validate() error {
return nil
}
func (r *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels) validate() error {
if err := dcl.Required(r, "labelName"); err != nil {
return err
}
if err := dcl.Required(r, "labelValue"); err != nil {
return err
}
return nil
}
func (r *EndpointPolicyTrafficPortSelector) validate() error {
return nil
}
func (r *EndpointPolicy) basePath() string {
params := map[string]interface{}{}
return dcl.Nprintf("https://networkservices.googleapis.com/v1alpha1/", params)
}
func (r *EndpointPolicy) getURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := 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}}/endpointPolicies/{{name}}", nr.basePath(), userBasePath, params), nil
}
func (r *EndpointPolicy) listURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/endpointPolicies", nr.basePath(), userBasePath, params), nil
}
func (r *EndpointPolicy) createURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := 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}}/endpointPolicies?endpointPolicyId={{name}}", nr.basePath(), userBasePath, params), nil
}
func (r *EndpointPolicy) deleteURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := 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}}/endpointPolicies/{{name}}", nr.basePath(), userBasePath, params), nil
}
// endpointPolicyApiOperation represents a mutable operation in the underlying REST
// API such as Create, Update, or Delete.
type endpointPolicyApiOperation interface {
do(context.Context, *EndpointPolicy, *Client) error
}
// newUpdateEndpointPolicyUpdateEndpointPolicyRequest creates a request for an
// EndpointPolicy resource's UpdateEndpointPolicy update type by filling in the update
// fields based on the intended state of the resource.
func newUpdateEndpointPolicyUpdateEndpointPolicyRequest(ctx context.Context, f *EndpointPolicy, 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 := f.Type; !dcl.IsEmptyValueIndirect(v) {
req["type"] = v
}
if v := f.AuthorizationPolicy; !dcl.IsEmptyValueIndirect(v) {
req["authorizationPolicy"] = v
}
if v, err := expandEndpointPolicyEndpointMatcher(c, f.EndpointMatcher, res); err != nil {
return nil, fmt.Errorf("error expanding EndpointMatcher into endpointMatcher: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["endpointMatcher"] = v
}
if v, err := expandEndpointPolicyTrafficPortSelector(c, f.TrafficPortSelector, res); err != nil {
return nil, fmt.Errorf("error expanding TrafficPortSelector into trafficPortSelector: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["trafficPortSelector"] = v
}
if v := f.Description; !dcl.IsEmptyValueIndirect(v) {
req["description"] = v
}
if v := f.ServerTlsPolicy; !dcl.IsEmptyValueIndirect(v) {
req["serverTlsPolicy"] = v
}
if v := f.ClientTlsPolicy; !dcl.IsEmptyValueIndirect(v) {
req["clientTlsPolicy"] = v
}
return req, nil
}
// marshalUpdateEndpointPolicyUpdateEndpointPolicyRequest converts the update into
// the final JSON request body.
func marshalUpdateEndpointPolicyUpdateEndpointPolicyRequest(c *Client, m map[string]interface{}) ([]byte, error) {
return json.Marshal(m)
}
type updateEndpointPolicyUpdateEndpointPolicyOperation 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 (op *updateEndpointPolicyUpdateEndpointPolicyOperation) do(ctx context.Context, r *EndpointPolicy, c *Client) error {
_, err := c.GetEndpointPolicy(ctx, r)
if err != nil {
return err
}
u, err := r.updateURL(c.Config.BasePath, "UpdateEndpointPolicy")
if err != nil {
return err
}
req, err := newUpdateEndpointPolicyUpdateEndpointPolicyRequest(ctx, r, c)
if err != nil {
return err
}
c.Config.Logger.InfoWithContextf(ctx, "Created update: %#v", req)
body, err := marshalUpdateEndpointPolicyUpdateEndpointPolicyRequest(c, req)
if err != nil {
return err
}
resp, err := dcl.SendRequest(ctx, c.Config, "PATCH", u, bytes.NewBuffer(body), c.Config.RetryProvider)
if err != nil {
return err
}
var o operations.StandardGCPOperation
if err := dcl.ParseResponse(resp.Response, &o); err != nil {
return err
}
err = o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET")
if err != nil {
return err
}
return nil
}
func (c *Client) listEndpointPolicyRaw(ctx context.Context, r *EndpointPolicy, 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 != EndpointPolicyMaxPage {
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 listEndpointPolicyOperation struct {
EndpointPolicies []map[string]interface{} `json:"endpointPolicies"`
Token string `json:"nextPageToken"`
}
func (c *Client) listEndpointPolicy(ctx context.Context, r *EndpointPolicy, pageToken string, pageSize int32) ([]*EndpointPolicy, string, error) {
b, err := c.listEndpointPolicyRaw(ctx, r, pageToken, pageSize)
if err != nil {
return nil, "", err
}
var m listEndpointPolicyOperation
if err := json.Unmarshal(b, &m); err != nil {
return nil, "", err
}
var l []*EndpointPolicy
for _, v := range m.EndpointPolicies {
res, err := unmarshalMapEndpointPolicy(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) deleteAllEndpointPolicy(ctx context.Context, f func(*EndpointPolicy) bool, resources []*EndpointPolicy) 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.DeleteEndpointPolicy(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 deleteEndpointPolicyOperation struct{}
func (op *deleteEndpointPolicyOperation) do(ctx context.Context, r *EndpointPolicy, c *Client) error {
r, err := c.GetEndpointPolicy(ctx, r)
if err != nil {
if dcl.IsNotFound(err) {
c.Config.Logger.InfoWithContextf(ctx, "EndpointPolicy not found, returning. Original error: %v", err)
return nil
}
c.Config.Logger.WarningWithContextf(ctx, "GetEndpointPolicy 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.GetEndpointPolicy(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 createEndpointPolicyOperation struct {
response map[string]interface{}
}
func (op *createEndpointPolicyOperation) FirstResponse() (map[string]interface{}, bool) {
return op.response, len(op.response) > 0
}
func (op *createEndpointPolicyOperation) do(ctx context.Context, r *EndpointPolicy, 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.GetEndpointPolicy(ctx, r); err != nil {
c.Config.Logger.WarningWithContextf(ctx, "get returned error: %v", err)
return err
}
return nil
}
func (c *Client) getEndpointPolicyRaw(ctx context.Context, r *EndpointPolicy) ([]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) endpointPolicyDiffsForRawDesired(ctx context.Context, rawDesired *EndpointPolicy, opts ...dcl.ApplyOption) (initial, desired *EndpointPolicy, 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 *EndpointPolicy
if sh := dcl.FetchStateHint(opts); sh != nil {
if r, ok := sh.(*EndpointPolicy); !ok {
c.Config.Logger.WarningWithContextf(ctx, "Initial state hint was of the wrong type; expected EndpointPolicy, got %T", sh)
} else {
fetchState = r
}
}
if fetchState == nil {
fetchState = rawDesired
}
// 1.2: Retrieval of raw initial state from API
rawInitial, err := c.GetEndpointPolicy(ctx, fetchState)
if rawInitial == nil {
if !dcl.IsNotFound(err) {
c.Config.Logger.WarningWithContextf(ctx, "Failed to retrieve whether a EndpointPolicy resource already exists: %s", err)
return nil, nil, nil, fmt.Errorf("failed to retrieve EndpointPolicy resource: %v", err)
}
c.Config.Logger.InfoWithContext(ctx, "Found that EndpointPolicy resource did not exist.")
// Perform canonicalization to pick up defaults.
desired, err = canonicalizeEndpointPolicyDesiredState(rawDesired, rawInitial)
return nil, desired, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Found initial state for EndpointPolicy: %v", rawInitial)
c.Config.Logger.InfoWithContextf(ctx, "Initial desired state for EndpointPolicy: %v", rawDesired)
// The Get call applies postReadExtract and so the result may contain fields that are not part of API version.
if err := extractEndpointPolicyFields(rawInitial); err != nil {
return nil, nil, nil, err
}
// 1.3: Canonicalize raw initial state into initial state.
initial, err = canonicalizeEndpointPolicyInitialState(rawInitial, rawDesired)
if err != nil {
return nil, nil, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalized initial state for EndpointPolicy: %v", initial)
// 1.4: Canonicalize raw desired state into desired state.
desired, err = canonicalizeEndpointPolicyDesiredState(rawDesired, rawInitial, opts...)
if err != nil {
return nil, nil, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalized desired state for EndpointPolicy: %v", desired)
// 2.1: Comparison of initial and desired state.
diffs, err = diffEndpointPolicy(c, desired, initial, opts...)
return initial, desired, diffs, err
}
func canonicalizeEndpointPolicyInitialState(rawInitial, rawDesired *EndpointPolicy) (*EndpointPolicy, 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 canonicalizeEndpointPolicyDesiredState(rawDesired, rawInitial *EndpointPolicy, opts ...dcl.ApplyOption) (*EndpointPolicy, 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.EndpointMatcher = canonicalizeEndpointPolicyEndpointMatcher(rawDesired.EndpointMatcher, nil, opts...)
rawDesired.TrafficPortSelector = canonicalizeEndpointPolicyTrafficPortSelector(rawDesired.TrafficPortSelector, nil, opts...)
return rawDesired, nil
}
canonicalDesired := &EndpointPolicy{}
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
}
if dcl.IsZeroValue(rawDesired.Type) || (dcl.IsEmptyValueIndirect(rawDesired.Type) && dcl.IsEmptyValueIndirect(rawInitial.Type)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
canonicalDesired.Type = rawInitial.Type
} else {
canonicalDesired.Type = rawDesired.Type
}
if dcl.IsZeroValue(rawDesired.AuthorizationPolicy) || (dcl.IsEmptyValueIndirect(rawDesired.AuthorizationPolicy) && dcl.IsEmptyValueIndirect(rawInitial.AuthorizationPolicy)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
canonicalDesired.AuthorizationPolicy = rawInitial.AuthorizationPolicy
} else {
canonicalDesired.AuthorizationPolicy = rawDesired.AuthorizationPolicy
}
canonicalDesired.EndpointMatcher = canonicalizeEndpointPolicyEndpointMatcher(rawDesired.EndpointMatcher, rawInitial.EndpointMatcher, opts...)
canonicalDesired.TrafficPortSelector = canonicalizeEndpointPolicyTrafficPortSelector(rawDesired.TrafficPortSelector, rawInitial.TrafficPortSelector, opts...)
if dcl.StringCanonicalize(rawDesired.Description, rawInitial.Description) {
canonicalDesired.Description = rawInitial.Description
} else {
canonicalDesired.Description = rawDesired.Description
}
if dcl.IsZeroValue(rawDesired.ServerTlsPolicy) || (dcl.IsEmptyValueIndirect(rawDesired.ServerTlsPolicy) && dcl.IsEmptyValueIndirect(rawInitial.ServerTlsPolicy)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
canonicalDesired.ServerTlsPolicy = rawInitial.ServerTlsPolicy
} else {
canonicalDesired.ServerTlsPolicy = rawDesired.ServerTlsPolicy
}
if dcl.IsZeroValue(rawDesired.ClientTlsPolicy) || (dcl.IsEmptyValueIndirect(rawDesired.ClientTlsPolicy) && dcl.IsEmptyValueIndirect(rawInitial.ClientTlsPolicy)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
canonicalDesired.ClientTlsPolicy = rawInitial.ClientTlsPolicy
} else {
canonicalDesired.ClientTlsPolicy = rawDesired.ClientTlsPolicy
}
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 canonicalizeEndpointPolicyNewState(c *Client, rawNew, rawDesired *EndpointPolicy) (*EndpointPolicy, 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.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.Labels) && dcl.IsEmptyValueIndirect(rawDesired.Labels) {
rawNew.Labels = rawDesired.Labels
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.Type) && dcl.IsEmptyValueIndirect(rawDesired.Type) {
rawNew.Type = rawDesired.Type
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.AuthorizationPolicy) && dcl.IsEmptyValueIndirect(rawDesired.AuthorizationPolicy) {
rawNew.AuthorizationPolicy = rawDesired.AuthorizationPolicy
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.EndpointMatcher) && dcl.IsEmptyValueIndirect(rawDesired.EndpointMatcher) {
rawNew.EndpointMatcher = rawDesired.EndpointMatcher
} else {
rawNew.EndpointMatcher = canonicalizeNewEndpointPolicyEndpointMatcher(c, rawDesired.EndpointMatcher, rawNew.EndpointMatcher)
}
if dcl.IsEmptyValueIndirect(rawNew.TrafficPortSelector) && dcl.IsEmptyValueIndirect(rawDesired.TrafficPortSelector) {
rawNew.TrafficPortSelector = rawDesired.TrafficPortSelector
} else {
rawNew.TrafficPortSelector = canonicalizeNewEndpointPolicyTrafficPortSelector(c, rawDesired.TrafficPortSelector, rawNew.TrafficPortSelector)
}
if dcl.IsEmptyValueIndirect(rawNew.Description) && dcl.IsEmptyValueIndirect(rawDesired.Description) {
rawNew.Description = rawDesired.Description
} else {
if dcl.StringCanonicalize(rawDesired.Description, rawNew.Description) {
rawNew.Description = rawDesired.Description
}
}
if dcl.IsEmptyValueIndirect(rawNew.ServerTlsPolicy) && dcl.IsEmptyValueIndirect(rawDesired.ServerTlsPolicy) {
rawNew.ServerTlsPolicy = rawDesired.ServerTlsPolicy
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.ClientTlsPolicy) && dcl.IsEmptyValueIndirect(rawDesired.ClientTlsPolicy) {
rawNew.ClientTlsPolicy = rawDesired.ClientTlsPolicy
} else {
}
rawNew.Project = rawDesired.Project
rawNew.Location = rawDesired.Location
return rawNew, nil
}
func canonicalizeEndpointPolicyEndpointMatcher(des, initial *EndpointPolicyEndpointMatcher, opts ...dcl.ApplyOption) *EndpointPolicyEndpointMatcher {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &EndpointPolicyEndpointMatcher{}
cDes.MetadataLabelMatcher = canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcher(des.MetadataLabelMatcher, initial.MetadataLabelMatcher, opts...)
return cDes
}
func canonicalizeEndpointPolicyEndpointMatcherSlice(des, initial []EndpointPolicyEndpointMatcher, opts ...dcl.ApplyOption) []EndpointPolicyEndpointMatcher {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]EndpointPolicyEndpointMatcher, 0, len(des))
for _, d := range des {
cd := canonicalizeEndpointPolicyEndpointMatcher(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]EndpointPolicyEndpointMatcher, 0, len(des))
for i, d := range des {
cd := canonicalizeEndpointPolicyEndpointMatcher(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewEndpointPolicyEndpointMatcher(c *Client, des, nw *EndpointPolicyEndpointMatcher) *EndpointPolicyEndpointMatcher {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for EndpointPolicyEndpointMatcher while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.MetadataLabelMatcher = canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcher(c, des.MetadataLabelMatcher, nw.MetadataLabelMatcher)
return nw
}
func canonicalizeNewEndpointPolicyEndpointMatcherSet(c *Client, des, nw []EndpointPolicyEndpointMatcher) []EndpointPolicyEndpointMatcher {
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 []EndpointPolicyEndpointMatcher
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareEndpointPolicyEndpointMatcherNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewEndpointPolicyEndpointMatcher(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 canonicalizeNewEndpointPolicyEndpointMatcherSlice(c *Client, des, nw []EndpointPolicyEndpointMatcher) []EndpointPolicyEndpointMatcher {
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 []EndpointPolicyEndpointMatcher
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewEndpointPolicyEndpointMatcher(c, &d, &n))
}
return items
}
func canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcher(des, initial *EndpointPolicyEndpointMatcherMetadataLabelMatcher, opts ...dcl.ApplyOption) *EndpointPolicyEndpointMatcherMetadataLabelMatcher {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &EndpointPolicyEndpointMatcherMetadataLabelMatcher{}
if dcl.IsZeroValue(des.MetadataLabelMatchCriteria) || (dcl.IsEmptyValueIndirect(des.MetadataLabelMatchCriteria) && dcl.IsEmptyValueIndirect(initial.MetadataLabelMatchCriteria)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.MetadataLabelMatchCriteria = initial.MetadataLabelMatchCriteria
} else {
cDes.MetadataLabelMatchCriteria = des.MetadataLabelMatchCriteria
}
cDes.MetadataLabels = canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice(des.MetadataLabels, initial.MetadataLabels, opts...)
return cDes
}
func canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcherSlice(des, initial []EndpointPolicyEndpointMatcherMetadataLabelMatcher, opts ...dcl.ApplyOption) []EndpointPolicyEndpointMatcherMetadataLabelMatcher {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]EndpointPolicyEndpointMatcherMetadataLabelMatcher, 0, len(des))
for _, d := range des {
cd := canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcher(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]EndpointPolicyEndpointMatcherMetadataLabelMatcher, 0, len(des))
for i, d := range des {
cd := canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcher(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcher(c *Client, des, nw *EndpointPolicyEndpointMatcherMetadataLabelMatcher) *EndpointPolicyEndpointMatcherMetadataLabelMatcher {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for EndpointPolicyEndpointMatcherMetadataLabelMatcher while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.MetadataLabels = canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice(c, des.MetadataLabels, nw.MetadataLabels)
return nw
}
func canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcherSet(c *Client, des, nw []EndpointPolicyEndpointMatcherMetadataLabelMatcher) []EndpointPolicyEndpointMatcherMetadataLabelMatcher {
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 []EndpointPolicyEndpointMatcherMetadataLabelMatcher
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareEndpointPolicyEndpointMatcherMetadataLabelMatcherNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcher(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 canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcherSlice(c *Client, des, nw []EndpointPolicyEndpointMatcherMetadataLabelMatcher) []EndpointPolicyEndpointMatcherMetadataLabelMatcher {
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 []EndpointPolicyEndpointMatcherMetadataLabelMatcher
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcher(c, &d, &n))
}
return items
}
func canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(des, initial *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, opts ...dcl.ApplyOption) *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels{}
if dcl.StringCanonicalize(des.LabelName, initial.LabelName) || dcl.IsZeroValue(des.LabelName) {
cDes.LabelName = initial.LabelName
} else {
cDes.LabelName = des.LabelName
}
if dcl.StringCanonicalize(des.LabelValue, initial.LabelValue) || dcl.IsZeroValue(des.LabelValue) {
cDes.LabelValue = initial.LabelValue
} else {
cDes.LabelValue = des.LabelValue
}
return cDes
}
func canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice(des, initial []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, opts ...dcl.ApplyOption) []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels {
if des == nil {
return initial
}
if len(des) != len(initial) {
items := make([]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, 0, len(des))
for _, d := range des {
cd := canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, 0, len(des))
for i, d := range des {
cd := canonicalizeEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(c *Client, des, nw *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels) *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.LabelName, nw.LabelName) {
nw.LabelName = des.LabelName
}
if dcl.StringCanonicalize(des.LabelValue, nw.LabelValue) {
nw.LabelValue = des.LabelValue
}
return nw
}
func canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSet(c *Client, des, nw []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels) []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels {
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 []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(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 canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice(c *Client, des, nw []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels) []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels {
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 []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(c, &d, &n))
}
return items
}
func canonicalizeEndpointPolicyTrafficPortSelector(des, initial *EndpointPolicyTrafficPortSelector, opts ...dcl.ApplyOption) *EndpointPolicyTrafficPortSelector {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &EndpointPolicyTrafficPortSelector{}
if dcl.StringArrayCanonicalize(des.Ports, initial.Ports) {
cDes.Ports = initial.Ports
} else {
cDes.Ports = des.Ports
}
return cDes
}
func canonicalizeEndpointPolicyTrafficPortSelectorSlice(des, initial []EndpointPolicyTrafficPortSelector, opts ...dcl.ApplyOption) []EndpointPolicyTrafficPortSelector {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]EndpointPolicyTrafficPortSelector, 0, len(des))
for _, d := range des {
cd := canonicalizeEndpointPolicyTrafficPortSelector(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]EndpointPolicyTrafficPortSelector, 0, len(des))
for i, d := range des {
cd := canonicalizeEndpointPolicyTrafficPortSelector(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewEndpointPolicyTrafficPortSelector(c *Client, des, nw *EndpointPolicyTrafficPortSelector) *EndpointPolicyTrafficPortSelector {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for EndpointPolicyTrafficPortSelector while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringArrayCanonicalize(des.Ports, nw.Ports) {
nw.Ports = des.Ports
}
return nw
}
func canonicalizeNewEndpointPolicyTrafficPortSelectorSet(c *Client, des, nw []EndpointPolicyTrafficPortSelector) []EndpointPolicyTrafficPortSelector {
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 []EndpointPolicyTrafficPortSelector
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareEndpointPolicyTrafficPortSelectorNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewEndpointPolicyTrafficPortSelector(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 canonicalizeNewEndpointPolicyTrafficPortSelectorSlice(c *Client, des, nw []EndpointPolicyTrafficPortSelector) []EndpointPolicyTrafficPortSelector {
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 []EndpointPolicyTrafficPortSelector
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewEndpointPolicyTrafficPortSelector(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 diffEndpointPolicy(c *Client, desired, actual *EndpointPolicy, 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.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.Labels, actual.Labels, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("Labels")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Type, actual.Type, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("Type")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.AuthorizationPolicy, actual.AuthorizationPolicy, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("AuthorizationPolicy")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.EndpointMatcher, actual.EndpointMatcher, dcl.DiffInfo{ObjectFunction: compareEndpointPolicyEndpointMatcherNewStyle, EmptyObject: EmptyEndpointPolicyEndpointMatcher, OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("EndpointMatcher")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.TrafficPortSelector, actual.TrafficPortSelector, dcl.DiffInfo{ObjectFunction: compareEndpointPolicyTrafficPortSelectorNewStyle, EmptyObject: EmptyEndpointPolicyTrafficPortSelector, OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("TrafficPortSelector")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Description, actual.Description, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("Description")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.ServerTlsPolicy, actual.ServerTlsPolicy, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("ServerTlsPolicy")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.ClientTlsPolicy, actual.ClientTlsPolicy, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("ClientTlsPolicy")); 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 compareEndpointPolicyEndpointMatcherNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*EndpointPolicyEndpointMatcher)
if !ok {
desiredNotPointer, ok := d.(EndpointPolicyEndpointMatcher)
if !ok {
return nil, fmt.Errorf("obj %v is not a EndpointPolicyEndpointMatcher or *EndpointPolicyEndpointMatcher", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*EndpointPolicyEndpointMatcher)
if !ok {
actualNotPointer, ok := a.(EndpointPolicyEndpointMatcher)
if !ok {
return nil, fmt.Errorf("obj %v is not a EndpointPolicyEndpointMatcher", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.MetadataLabelMatcher, actual.MetadataLabelMatcher, dcl.DiffInfo{ObjectFunction: compareEndpointPolicyEndpointMatcherMetadataLabelMatcherNewStyle, EmptyObject: EmptyEndpointPolicyEndpointMatcherMetadataLabelMatcher, OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("MetadataLabelMatcher")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareEndpointPolicyEndpointMatcherMetadataLabelMatcherNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*EndpointPolicyEndpointMatcherMetadataLabelMatcher)
if !ok {
desiredNotPointer, ok := d.(EndpointPolicyEndpointMatcherMetadataLabelMatcher)
if !ok {
return nil, fmt.Errorf("obj %v is not a EndpointPolicyEndpointMatcherMetadataLabelMatcher or *EndpointPolicyEndpointMatcherMetadataLabelMatcher", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*EndpointPolicyEndpointMatcherMetadataLabelMatcher)
if !ok {
actualNotPointer, ok := a.(EndpointPolicyEndpointMatcherMetadataLabelMatcher)
if !ok {
return nil, fmt.Errorf("obj %v is not a EndpointPolicyEndpointMatcherMetadataLabelMatcher", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.MetadataLabelMatchCriteria, actual.MetadataLabelMatchCriteria, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("MetadataLabelMatchCriteria")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.MetadataLabels, actual.MetadataLabels, dcl.DiffInfo{ObjectFunction: compareEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsNewStyle, EmptyObject: EmptyEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("MetadataLabels")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels)
if !ok {
desiredNotPointer, ok := d.(EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels)
if !ok {
return nil, fmt.Errorf("obj %v is not a EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels or *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels)
if !ok {
actualNotPointer, ok := a.(EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels)
if !ok {
return nil, fmt.Errorf("obj %v is not a EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.LabelName, actual.LabelName, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("LabelName")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.LabelValue, actual.LabelValue, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("LabelValue")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareEndpointPolicyTrafficPortSelectorNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*EndpointPolicyTrafficPortSelector)
if !ok {
desiredNotPointer, ok := d.(EndpointPolicyTrafficPortSelector)
if !ok {
return nil, fmt.Errorf("obj %v is not a EndpointPolicyTrafficPortSelector or *EndpointPolicyTrafficPortSelector", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*EndpointPolicyTrafficPortSelector)
if !ok {
actualNotPointer, ok := a.(EndpointPolicyTrafficPortSelector)
if !ok {
return nil, fmt.Errorf("obj %v is not a EndpointPolicyTrafficPortSelector", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Ports, actual.Ports, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateEndpointPolicyUpdateEndpointPolicyOperation")}, fn.AddNest("Ports")); 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 *EndpointPolicy) urlNormalized() *EndpointPolicy {
normalized := dcl.Copy(*r).(EndpointPolicy)
normalized.Name = dcl.SelfLinkToName(r.Name)
normalized.AuthorizationPolicy = dcl.SelfLinkToName(r.AuthorizationPolicy)
normalized.Description = dcl.SelfLinkToName(r.Description)
normalized.ServerTlsPolicy = dcl.SelfLinkToName(r.ServerTlsPolicy)
normalized.ClientTlsPolicy = dcl.SelfLinkToName(r.ClientTlsPolicy)
normalized.Project = dcl.SelfLinkToName(r.Project)
normalized.Location = dcl.SelfLinkToName(r.Location)
return &normalized
}
func (r *EndpointPolicy) updateURL(userBasePath, updateName string) (string, error) {
nr := r.urlNormalized()
if updateName == "UpdateEndpointPolicy" {
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}}/endpointPolicies/{{name}}", nr.basePath(), userBasePath, fields), nil
}
return "", fmt.Errorf("unknown update name: %s", updateName)
}
// marshal encodes the EndpointPolicy resource into JSON for a Create request, and
// performs transformations from the resource schema to the API schema if
// necessary.
func (r *EndpointPolicy) marshal(c *Client) ([]byte, error) {
m, err := expandEndpointPolicy(c, r)
if err != nil {
return nil, fmt.Errorf("error marshalling EndpointPolicy: %w", err)
}
return json.Marshal(m)
}
// unmarshalEndpointPolicy decodes JSON responses into the EndpointPolicy resource schema.
func unmarshalEndpointPolicy(b []byte, c *Client, res *EndpointPolicy) (*EndpointPolicy, error) {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
return unmarshalMapEndpointPolicy(m, c, res)
}
func unmarshalMapEndpointPolicy(m map[string]interface{}, c *Client, res *EndpointPolicy) (*EndpointPolicy, error) {
flattened := flattenEndpointPolicy(c, m, res)
if flattened == nil {
return nil, fmt.Errorf("attempted to flatten empty json object")
}
return flattened, nil
}
// expandEndpointPolicy expands EndpointPolicy into a JSON request object.
func expandEndpointPolicy(c *Client, f *EndpointPolicy) (map[string]interface{}, error) {
m := make(map[string]interface{})
res := f
_ = res
if v, err := dcl.DeriveField("projects/*/locations/global/endpointPolicies/%s", f.Name, 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 := f.Type; dcl.ValueShouldBeSent(v) {
m["type"] = v
}
if v := f.AuthorizationPolicy; dcl.ValueShouldBeSent(v) {
m["authorizationPolicy"] = v
}
if v, err := expandEndpointPolicyEndpointMatcher(c, f.EndpointMatcher, res); err != nil {
return nil, fmt.Errorf("error expanding EndpointMatcher into endpointMatcher: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["endpointMatcher"] = v
}
if v, err := expandEndpointPolicyTrafficPortSelector(c, f.TrafficPortSelector, res); err != nil {
return nil, fmt.Errorf("error expanding TrafficPortSelector into trafficPortSelector: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["trafficPortSelector"] = v
}
if v := f.Description; dcl.ValueShouldBeSent(v) {
m["description"] = v
}
if v := f.ServerTlsPolicy; dcl.ValueShouldBeSent(v) {
m["serverTlsPolicy"] = v
}
if v := f.ClientTlsPolicy; dcl.ValueShouldBeSent(v) {
m["clientTlsPolicy"] = 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
}
// flattenEndpointPolicy flattens EndpointPolicy from a JSON request object into the
// EndpointPolicy type.
func flattenEndpointPolicy(c *Client, i interface{}, res *EndpointPolicy) *EndpointPolicy {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
if len(m) == 0 {
return nil
}
resultRes := &EndpointPolicy{}
resultRes.Name = dcl.FlattenString(m["name"])
resultRes.CreateTime = dcl.FlattenString(m["createTime"])
resultRes.UpdateTime = dcl.FlattenString(m["updateTime"])
resultRes.Labels = dcl.FlattenKeyValuePairs(m["labels"])
resultRes.Type = flattenEndpointPolicyTypeEnum(m["type"])
resultRes.AuthorizationPolicy = dcl.FlattenString(m["authorizationPolicy"])
resultRes.EndpointMatcher = flattenEndpointPolicyEndpointMatcher(c, m["endpointMatcher"], res)
resultRes.TrafficPortSelector = flattenEndpointPolicyTrafficPortSelector(c, m["trafficPortSelector"], res)
resultRes.Description = dcl.FlattenString(m["description"])
resultRes.ServerTlsPolicy = dcl.FlattenString(m["serverTlsPolicy"])
resultRes.ClientTlsPolicy = dcl.FlattenString(m["clientTlsPolicy"])
resultRes.Project = dcl.FlattenString(m["project"])
resultRes.Location = dcl.FlattenString(m["location"])
return resultRes
}
// expandEndpointPolicyEndpointMatcherMap expands the contents of EndpointPolicyEndpointMatcher into a JSON
// request object.
func expandEndpointPolicyEndpointMatcherMap(c *Client, f map[string]EndpointPolicyEndpointMatcher, res *EndpointPolicy) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandEndpointPolicyEndpointMatcher(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandEndpointPolicyEndpointMatcherSlice expands the contents of EndpointPolicyEndpointMatcher into a JSON
// request object.
func expandEndpointPolicyEndpointMatcherSlice(c *Client, f []EndpointPolicyEndpointMatcher, res *EndpointPolicy) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandEndpointPolicyEndpointMatcher(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenEndpointPolicyEndpointMatcherMap flattens the contents of EndpointPolicyEndpointMatcher from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMap(c *Client, i interface{}, res *EndpointPolicy) map[string]EndpointPolicyEndpointMatcher {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]EndpointPolicyEndpointMatcher{}
}
if len(a) == 0 {
return map[string]EndpointPolicyEndpointMatcher{}
}
items := make(map[string]EndpointPolicyEndpointMatcher)
for k, item := range a {
items[k] = *flattenEndpointPolicyEndpointMatcher(c, item.(map[string]interface{}), res)
}
return items
}
// flattenEndpointPolicyEndpointMatcherSlice flattens the contents of EndpointPolicyEndpointMatcher from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherSlice(c *Client, i interface{}, res *EndpointPolicy) []EndpointPolicyEndpointMatcher {
a, ok := i.([]interface{})
if !ok {
return []EndpointPolicyEndpointMatcher{}
}
if len(a) == 0 {
return []EndpointPolicyEndpointMatcher{}
}
items := make([]EndpointPolicyEndpointMatcher, 0, len(a))
for _, item := range a {
items = append(items, *flattenEndpointPolicyEndpointMatcher(c, item.(map[string]interface{}), res))
}
return items
}
// expandEndpointPolicyEndpointMatcher expands an instance of EndpointPolicyEndpointMatcher into a JSON
// request object.
func expandEndpointPolicyEndpointMatcher(c *Client, f *EndpointPolicyEndpointMatcher, res *EndpointPolicy) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v, err := expandEndpointPolicyEndpointMatcherMetadataLabelMatcher(c, f.MetadataLabelMatcher, res); err != nil {
return nil, fmt.Errorf("error expanding MetadataLabelMatcher into metadataLabelMatcher: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["metadataLabelMatcher"] = v
}
return m, nil
}
// flattenEndpointPolicyEndpointMatcher flattens an instance of EndpointPolicyEndpointMatcher from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcher(c *Client, i interface{}, res *EndpointPolicy) *EndpointPolicyEndpointMatcher {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &EndpointPolicyEndpointMatcher{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyEndpointPolicyEndpointMatcher
}
r.MetadataLabelMatcher = flattenEndpointPolicyEndpointMatcherMetadataLabelMatcher(c, m["metadataLabelMatcher"], res)
return r
}
// expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMap expands the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcher into a JSON
// request object.
func expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMap(c *Client, f map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcher, res *EndpointPolicy) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandEndpointPolicyEndpointMatcherMetadataLabelMatcher(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandEndpointPolicyEndpointMatcherMetadataLabelMatcherSlice expands the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcher into a JSON
// request object.
func expandEndpointPolicyEndpointMatcherMetadataLabelMatcherSlice(c *Client, f []EndpointPolicyEndpointMatcherMetadataLabelMatcher, res *EndpointPolicy) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandEndpointPolicyEndpointMatcherMetadataLabelMatcher(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMap flattens the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcher from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMap(c *Client, i interface{}, res *EndpointPolicy) map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcher {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcher{}
}
if len(a) == 0 {
return map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcher{}
}
items := make(map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcher)
for k, item := range a {
items[k] = *flattenEndpointPolicyEndpointMatcherMetadataLabelMatcher(c, item.(map[string]interface{}), res)
}
return items
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherSlice flattens the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcher from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherSlice(c *Client, i interface{}, res *EndpointPolicy) []EndpointPolicyEndpointMatcherMetadataLabelMatcher {
a, ok := i.([]interface{})
if !ok {
return []EndpointPolicyEndpointMatcherMetadataLabelMatcher{}
}
if len(a) == 0 {
return []EndpointPolicyEndpointMatcherMetadataLabelMatcher{}
}
items := make([]EndpointPolicyEndpointMatcherMetadataLabelMatcher, 0, len(a))
for _, item := range a {
items = append(items, *flattenEndpointPolicyEndpointMatcherMetadataLabelMatcher(c, item.(map[string]interface{}), res))
}
return items
}
// expandEndpointPolicyEndpointMatcherMetadataLabelMatcher expands an instance of EndpointPolicyEndpointMatcherMetadataLabelMatcher into a JSON
// request object.
func expandEndpointPolicyEndpointMatcherMetadataLabelMatcher(c *Client, f *EndpointPolicyEndpointMatcherMetadataLabelMatcher, res *EndpointPolicy) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.MetadataLabelMatchCriteria; !dcl.IsEmptyValueIndirect(v) {
m["metadataLabelMatchCriteria"] = v
}
if v, err := expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice(c, f.MetadataLabels, res); err != nil {
return nil, fmt.Errorf("error expanding MetadataLabels into metadataLabels: %w", err)
} else if v != nil {
m["metadataLabels"] = v
}
return m, nil
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcher flattens an instance of EndpointPolicyEndpointMatcherMetadataLabelMatcher from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcher(c *Client, i interface{}, res *EndpointPolicy) *EndpointPolicyEndpointMatcherMetadataLabelMatcher {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &EndpointPolicyEndpointMatcherMetadataLabelMatcher{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyEndpointPolicyEndpointMatcherMetadataLabelMatcher
}
r.MetadataLabelMatchCriteria = flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum(m["metadataLabelMatchCriteria"])
r.MetadataLabels = flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice(c, m["metadataLabels"], res)
return r
}
// expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsMap expands the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels into a JSON
// request object.
func expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsMap(c *Client, f map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, res *EndpointPolicy) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice expands the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels into a JSON
// request object.
func expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice(c *Client, f []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, res *EndpointPolicy) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsMap flattens the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsMap(c *Client, i interface{}, res *EndpointPolicy) map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels{}
}
if len(a) == 0 {
return map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels{}
}
items := make(map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels)
for k, item := range a {
items[k] = *flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(c, item.(map[string]interface{}), res)
}
return items
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice flattens the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsSlice(c *Client, i interface{}, res *EndpointPolicy) []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels {
a, ok := i.([]interface{})
if !ok {
return []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels{}
}
if len(a) == 0 {
return []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels{}
}
items := make([]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, 0, len(a))
for _, item := range a {
items = append(items, *flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(c, item.(map[string]interface{}), res))
}
return items
}
// expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels expands an instance of EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels into a JSON
// request object.
func expandEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(c *Client, f *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels, res *EndpointPolicy) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
m := make(map[string]interface{})
if v := f.LabelName; !dcl.IsEmptyValueIndirect(v) {
m["labelName"] = v
}
if v := f.LabelValue; !dcl.IsEmptyValueIndirect(v) {
m["labelValue"] = v
}
return m, nil
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels flattens an instance of EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels(c *Client, i interface{}, res *EndpointPolicy) *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels
}
r.LabelName = dcl.FlattenString(m["labelName"])
r.LabelValue = dcl.FlattenString(m["labelValue"])
return r
}
// expandEndpointPolicyTrafficPortSelectorMap expands the contents of EndpointPolicyTrafficPortSelector into a JSON
// request object.
func expandEndpointPolicyTrafficPortSelectorMap(c *Client, f map[string]EndpointPolicyTrafficPortSelector, res *EndpointPolicy) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandEndpointPolicyTrafficPortSelector(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandEndpointPolicyTrafficPortSelectorSlice expands the contents of EndpointPolicyTrafficPortSelector into a JSON
// request object.
func expandEndpointPolicyTrafficPortSelectorSlice(c *Client, f []EndpointPolicyTrafficPortSelector, res *EndpointPolicy) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandEndpointPolicyTrafficPortSelector(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenEndpointPolicyTrafficPortSelectorMap flattens the contents of EndpointPolicyTrafficPortSelector from a JSON
// response object.
func flattenEndpointPolicyTrafficPortSelectorMap(c *Client, i interface{}, res *EndpointPolicy) map[string]EndpointPolicyTrafficPortSelector {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]EndpointPolicyTrafficPortSelector{}
}
if len(a) == 0 {
return map[string]EndpointPolicyTrafficPortSelector{}
}
items := make(map[string]EndpointPolicyTrafficPortSelector)
for k, item := range a {
items[k] = *flattenEndpointPolicyTrafficPortSelector(c, item.(map[string]interface{}), res)
}
return items
}
// flattenEndpointPolicyTrafficPortSelectorSlice flattens the contents of EndpointPolicyTrafficPortSelector from a JSON
// response object.
func flattenEndpointPolicyTrafficPortSelectorSlice(c *Client, i interface{}, res *EndpointPolicy) []EndpointPolicyTrafficPortSelector {
a, ok := i.([]interface{})
if !ok {
return []EndpointPolicyTrafficPortSelector{}
}
if len(a) == 0 {
return []EndpointPolicyTrafficPortSelector{}
}
items := make([]EndpointPolicyTrafficPortSelector, 0, len(a))
for _, item := range a {
items = append(items, *flattenEndpointPolicyTrafficPortSelector(c, item.(map[string]interface{}), res))
}
return items
}
// expandEndpointPolicyTrafficPortSelector expands an instance of EndpointPolicyTrafficPortSelector into a JSON
// request object.
func expandEndpointPolicyTrafficPortSelector(c *Client, f *EndpointPolicyTrafficPortSelector, res *EndpointPolicy) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Ports; v != nil {
m["ports"] = v
}
return m, nil
}
// flattenEndpointPolicyTrafficPortSelector flattens an instance of EndpointPolicyTrafficPortSelector from a JSON
// response object.
func flattenEndpointPolicyTrafficPortSelector(c *Client, i interface{}, res *EndpointPolicy) *EndpointPolicyTrafficPortSelector {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &EndpointPolicyTrafficPortSelector{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyEndpointPolicyTrafficPortSelector
}
r.Ports = dcl.FlattenStringSlice(m["ports"])
return r
}
// flattenEndpointPolicyTypeEnumMap flattens the contents of EndpointPolicyTypeEnum from a JSON
// response object.
func flattenEndpointPolicyTypeEnumMap(c *Client, i interface{}, res *EndpointPolicy) map[string]EndpointPolicyTypeEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]EndpointPolicyTypeEnum{}
}
if len(a) == 0 {
return map[string]EndpointPolicyTypeEnum{}
}
items := make(map[string]EndpointPolicyTypeEnum)
for k, item := range a {
items[k] = *flattenEndpointPolicyTypeEnum(item.(interface{}))
}
return items
}
// flattenEndpointPolicyTypeEnumSlice flattens the contents of EndpointPolicyTypeEnum from a JSON
// response object.
func flattenEndpointPolicyTypeEnumSlice(c *Client, i interface{}, res *EndpointPolicy) []EndpointPolicyTypeEnum {
a, ok := i.([]interface{})
if !ok {
return []EndpointPolicyTypeEnum{}
}
if len(a) == 0 {
return []EndpointPolicyTypeEnum{}
}
items := make([]EndpointPolicyTypeEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenEndpointPolicyTypeEnum(item.(interface{})))
}
return items
}
// flattenEndpointPolicyTypeEnum asserts that an interface is a string, and returns a
// pointer to a *EndpointPolicyTypeEnum with the same value as that string.
func flattenEndpointPolicyTypeEnum(i interface{}) *EndpointPolicyTypeEnum {
s, ok := i.(string)
if !ok {
return nil
}
return EndpointPolicyTypeEnumRef(s)
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnumMap flattens the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnumMap(c *Client, i interface{}, res *EndpointPolicy) map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum{}
}
if len(a) == 0 {
return map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum{}
}
items := make(map[string]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum)
for k, item := range a {
items[k] = *flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum(item.(interface{}))
}
return items
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnumSlice flattens the contents of EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum from a JSON
// response object.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnumSlice(c *Client, i interface{}, res *EndpointPolicy) []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum {
a, ok := i.([]interface{})
if !ok {
return []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum{}
}
if len(a) == 0 {
return []EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum{}
}
items := make([]EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum(item.(interface{})))
}
return items
}
// flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum asserts that an interface is a string, and returns a
// pointer to a *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum with the same value as that string.
func flattenEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum(i interface{}) *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnum {
s, ok := i.(string)
if !ok {
return nil
}
return EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelMatchCriteriaEnumRef(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 *EndpointPolicy) matcher(c *Client) func([]byte) bool {
return func(b []byte) bool {
cr, err := unmarshalEndpointPolicy(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 endpointPolicyDiff struct {
// The diff should include one or the other of RequiresRecreate or UpdateOp.
RequiresRecreate bool
UpdateOp endpointPolicyApiOperation
FieldName string // used for error logging
}
func convertFieldDiffsToEndpointPolicyDiffs(config *dcl.Config, fds []*dcl.FieldDiff, opts []dcl.ApplyOption) ([]endpointPolicyDiff, 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 []endpointPolicyDiff
// For each operation name, create a endpointPolicyDiff which contains the operation.
for opName, fieldDiffs := range opNamesToFieldDiffs {
// Use the first field diff's field name for logging required recreate error.
diff := endpointPolicyDiff{FieldName: fieldDiffs[0].FieldName}
if opName == "Recreate" {
diff.RequiresRecreate = true
} else {
apiOp, err := convertOpNameToEndpointPolicyApiOperation(opName, fieldDiffs, opts...)
if err != nil {
return diffs, err
}
diff.UpdateOp = apiOp
}
diffs = append(diffs, diff)
}
return diffs, nil
}
func convertOpNameToEndpointPolicyApiOperation(opName string, fieldDiffs []*dcl.FieldDiff, opts ...dcl.ApplyOption) (endpointPolicyApiOperation, error) {
switch opName {
case "updateEndpointPolicyUpdateEndpointPolicyOperation":
return &updateEndpointPolicyUpdateEndpointPolicyOperation{FieldDiffs: fieldDiffs}, nil
default:
return nil, fmt.Errorf("no such operation with name: %v", opName)
}
}
func extractEndpointPolicyFields(r *EndpointPolicy) error {
vEndpointMatcher := r.EndpointMatcher
if vEndpointMatcher == nil {
// note: explicitly not the empty object.
vEndpointMatcher = &EndpointPolicyEndpointMatcher{}
}
if err := extractEndpointPolicyEndpointMatcherFields(r, vEndpointMatcher); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vEndpointMatcher) {
r.EndpointMatcher = vEndpointMatcher
}
vTrafficPortSelector := r.TrafficPortSelector
if vTrafficPortSelector == nil {
// note: explicitly not the empty object.
vTrafficPortSelector = &EndpointPolicyTrafficPortSelector{}
}
if err := extractEndpointPolicyTrafficPortSelectorFields(r, vTrafficPortSelector); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vTrafficPortSelector) {
r.TrafficPortSelector = vTrafficPortSelector
}
return nil
}
func extractEndpointPolicyEndpointMatcherFields(r *EndpointPolicy, o *EndpointPolicyEndpointMatcher) error {
vMetadataLabelMatcher := o.MetadataLabelMatcher
if vMetadataLabelMatcher == nil {
// note: explicitly not the empty object.
vMetadataLabelMatcher = &EndpointPolicyEndpointMatcherMetadataLabelMatcher{}
}
if err := extractEndpointPolicyEndpointMatcherMetadataLabelMatcherFields(r, vMetadataLabelMatcher); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vMetadataLabelMatcher) {
o.MetadataLabelMatcher = vMetadataLabelMatcher
}
return nil
}
func extractEndpointPolicyEndpointMatcherMetadataLabelMatcherFields(r *EndpointPolicy, o *EndpointPolicyEndpointMatcherMetadataLabelMatcher) error {
return nil
}
func extractEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsFields(r *EndpointPolicy, o *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels) error {
return nil
}
func extractEndpointPolicyTrafficPortSelectorFields(r *EndpointPolicy, o *EndpointPolicyTrafficPortSelector) error {
return nil
}
func postReadExtractEndpointPolicyFields(r *EndpointPolicy) error {
vEndpointMatcher := r.EndpointMatcher
if vEndpointMatcher == nil {
// note: explicitly not the empty object.
vEndpointMatcher = &EndpointPolicyEndpointMatcher{}
}
if err := postReadExtractEndpointPolicyEndpointMatcherFields(r, vEndpointMatcher); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vEndpointMatcher) {
r.EndpointMatcher = vEndpointMatcher
}
vTrafficPortSelector := r.TrafficPortSelector
if vTrafficPortSelector == nil {
// note: explicitly not the empty object.
vTrafficPortSelector = &EndpointPolicyTrafficPortSelector{}
}
if err := postReadExtractEndpointPolicyTrafficPortSelectorFields(r, vTrafficPortSelector); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vTrafficPortSelector) {
r.TrafficPortSelector = vTrafficPortSelector
}
return nil
}
func postReadExtractEndpointPolicyEndpointMatcherFields(r *EndpointPolicy, o *EndpointPolicyEndpointMatcher) error {
vMetadataLabelMatcher := o.MetadataLabelMatcher
if vMetadataLabelMatcher == nil {
// note: explicitly not the empty object.
vMetadataLabelMatcher = &EndpointPolicyEndpointMatcherMetadataLabelMatcher{}
}
if err := extractEndpointPolicyEndpointMatcherMetadataLabelMatcherFields(r, vMetadataLabelMatcher); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vMetadataLabelMatcher) {
o.MetadataLabelMatcher = vMetadataLabelMatcher
}
return nil
}
func postReadExtractEndpointPolicyEndpointMatcherMetadataLabelMatcherFields(r *EndpointPolicy, o *EndpointPolicyEndpointMatcherMetadataLabelMatcher) error {
return nil
}
func postReadExtractEndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabelsFields(r *EndpointPolicy, o *EndpointPolicyEndpointMatcherMetadataLabelMatcherMetadataLabels) error {
return nil
}
func postReadExtractEndpointPolicyTrafficPortSelectorFields(r *EndpointPolicy, o *EndpointPolicyTrafficPortSelector) error {
return nil
}
|
package names
import (
"fmt"
"net"
"strconv"
"strings"
"github.com/pkg/errors"
)
func GetLocalClusterName(port uint32) string {
return fmt.Sprintf("localhost:%d", port)
}
func GetSplitClusterName(service string, idx int) string {
return fmt.Sprintf("%s-_%d_", service, idx)
}
func GetPortForLocalClusterName(cluster string) (uint32, error) {
parts := strings.Split(cluster, ":")
if len(parts) != 2 {
return 0, errors.Errorf("failed to parse local cluster name: %s", cluster)
}
port, err := strconv.ParseUint(parts[1], 10, 32)
if err != nil {
return 0, err
}
return uint32(port), nil
}
func GetInboundListenerName(address string, port uint32) string {
return fmt.Sprintf("inbound:%s",
net.JoinHostPort(address, strconv.FormatUint(uint64(port), 10)))
}
func GetOutboundListenerName(address string, port uint32) string {
return fmt.Sprintf("outbound:%s",
net.JoinHostPort(address, strconv.FormatUint(uint64(port), 10)))
}
func GetInboundRouteName(service string) string {
return fmt.Sprintf("inbound:%s", service)
}
func GetOutboundRouteName(service string) string {
return fmt.Sprintf("outbound:%s", service)
}
func GetEnvoyAdminClusterName() string {
return "kuma:envoy:admin"
}
func GetMetricsHijackerClusterName() string {
return "kuma:metrics:hijacker"
}
func GetPrometheusListenerName() string {
return "kuma:metrics:prometheus"
}
func GetAdminListenerName() string {
return "kuma:envoy:admin"
}
func GetTracingClusterName(backendName string) string {
return fmt.Sprintf("tracing:%s", backendName)
}
func GetDNSListenerName() string {
return "kuma:dns"
}
func GetGatewayListenerName(gatewayName string, protoName string, port uint32) string {
return strings.Join([]string{gatewayName, protoName, strconv.Itoa(int(port))}, ":")
}
|
package amqp
import (
"context"
"errors"
"sync"
"testing"
"github.com/Azure/go-amqp"
"github.com/brigadecore/brigade/v2/apiserver/internal/lib/queue"
myamqp "github.com/brigadecore/brigade/v2/internal/amqp"
"github.com/stretchr/testify/require"
)
func TestNewWriterFactory(t *testing.T) {
const testAddress = "foo"
wf, ok := NewWriterFactory(
WriterFactoryConfig{
Address: testAddress,
},
).(*writerFactory)
require.True(t, ok)
require.Equal(t, testAddress, wf.address)
require.NotEmpty(t, wf.dialOpts)
// Assert we're not connected yet. (It connects lazily.)
require.Nil(t, wf.amqpClient)
require.NotNil(t, wf.amqpClientMu)
require.NotNil(t, wf.connectFn)
}
func TestWriterFactoryNewWriter(t *testing.T) {
const testQueueName = "foo"
wf := &writerFactory{
amqpClient: &mockAMQPClient{
NewSessionFn: func(opts ...amqp.SessionOption) (myamqp.Session, error) {
return &mockAMQPSession{
NewSenderFn: func(opts ...amqp.LinkOption) (myamqp.Sender, error) {
return &mockAMQPSender{}, nil
},
}, nil
},
},
amqpClientMu: &sync.Mutex{},
}
w, err := wf.NewWriter(testQueueName)
require.NoError(t, err)
writer, ok := w.(*writer)
require.True(t, ok)
require.Equal(t, testQueueName, writer.queueName)
require.NotNil(t, writer.amqpSession)
require.NotNil(t, writer.amqpSender)
}
func TestWriterFactoryClose(t *testing.T) {
testCases := []struct {
name string
writerFactory queue.WriterFactory
assertions func(error)
}{
{
name: "error closing underlying amqp connection",
writerFactory: &writerFactory{
amqpClient: &mockAMQPClient{
CloseFn: func() error {
return errors.New("something went wrong")
},
},
},
assertions: func(err error) {
require.Error(t, err)
require.Contains(t, err.Error(), "something went wrong")
require.Contains(t, err.Error(), "error closing AMQP client")
},
},
{
name: "success",
writerFactory: &writerFactory{
amqpClient: &mockAMQPClient{
CloseFn: func() error {
return nil
},
},
},
assertions: func(err error) {
require.NoError(t, err)
},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := testCase.writerFactory.Close(context.Background())
testCase.assertions(err)
})
}
}
func TestWriterWrite(t *testing.T) {
testCases := []struct {
name string
writer queue.Writer
assertions func(error)
}{
{
name: "error sending message",
writer: &writer{
amqpSender: &mockAMQPSender{
SendFn: func(context.Context, *amqp.Message) error {
return errors.New("something went wrong")
},
},
},
assertions: func(err error) {
require.Error(t, err)
require.Contains(t, err.Error(), "something went wrong")
require.Contains(t, err.Error(), "error sending amqp message")
},
},
{
name: "success",
writer: &writer{
amqpSender: &mockAMQPSender{
SendFn: func(ctx context.Context, msg *amqp.Message) error {
if msg.Header.Durable != false {
return errors.New("message persistence not as expected")
}
return nil
},
},
},
assertions: func(err error) {
require.NoError(t, err)
},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := testCase.writer.Write(
context.Background(),
"message in a bottle",
&queue.MessageOptions{},
)
testCase.assertions(err)
})
}
}
func TestWriterWrite_MessageOpts(t *testing.T) {
t.Run("nil opts", func(t *testing.T) {
writer := &writer{
amqpSender: &mockAMQPSender{
SendFn: func(ctx context.Context, msg *amqp.Message) error {
if msg.Header.Durable != false {
return errors.New("message persistence not as expected")
}
return nil
},
},
}
err := writer.Write(
context.Background(),
"message in a bottle",
nil,
)
require.NoError(t, err)
})
t.Run("non-nil opts", func(t *testing.T) {
writer := &writer{
amqpSender: &mockAMQPSender{
SendFn: func(ctx context.Context, msg *amqp.Message) error {
if msg.Header.Durable != true {
return errors.New("message persistence not as expected")
}
return nil
},
},
}
err := writer.Write(
context.Background(),
"message in a bottle",
&queue.MessageOptions{Durable: true},
)
require.NoError(t, err)
})
}
func TestWriterClose(t *testing.T) {
testCases := []struct {
name string
writer queue.Writer
assertions func(error)
}{
{
name: "error closing underlying sender",
writer: &writer{
amqpSender: &mockAMQPSender{
CloseFn: func(ctx context.Context) error {
return errors.New("something went wrong")
},
},
},
assertions: func(err error) {
require.Error(t, err)
require.Contains(t, err.Error(), "something went wrong")
require.Contains(t, err.Error(), "error closing AMQP sender")
},
},
{
name: "error closing underlying session",
writer: &writer{
amqpSender: &mockAMQPSender{
CloseFn: func(ctx context.Context) error {
return nil
},
},
amqpSession: &mockAMQPSession{
CloseFn: func(ctx context.Context) error {
return errors.New("something went wrong")
},
},
},
assertions: func(err error) {
require.Error(t, err)
require.Contains(t, err.Error(), "something went wrong")
require.Contains(t, err.Error(), "error closing AMQP session")
},
},
{
name: "success",
writer: &writer{
amqpSender: &mockAMQPSender{
CloseFn: func(ctx context.Context) error {
return nil
},
},
amqpSession: &mockAMQPSession{
CloseFn: func(ctx context.Context) error {
return nil
},
},
},
assertions: func(err error) {
require.NoError(t, err)
},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := testCase.writer.Close(context.Background())
testCase.assertions(err)
})
}
}
type mockAMQPClient struct {
NewSessionFn func(opts ...amqp.SessionOption) (myamqp.Session, error)
CloseFn func() error
}
func (m *mockAMQPClient) NewSession(
opts ...amqp.SessionOption,
) (myamqp.Session, error) {
return m.NewSessionFn(opts...)
}
func (m *mockAMQPClient) Close() error {
return m.CloseFn()
}
type mockAMQPSession struct {
NewSenderFn func(opts ...amqp.LinkOption) (myamqp.Sender, error)
NewReceiverFn func(opts ...amqp.LinkOption) (myamqp.Receiver, error)
CloseFn func(ctx context.Context) error
}
func (m *mockAMQPSession) NewSender(
opts ...amqp.LinkOption,
) (myamqp.Sender, error) {
return m.NewSenderFn(opts...)
}
func (m *mockAMQPSession) NewReceiver(
opts ...amqp.LinkOption,
) (myamqp.Receiver, error) {
return m.NewReceiverFn(opts...)
}
func (m *mockAMQPSession) Close(ctx context.Context) error {
return m.CloseFn(ctx)
}
type mockAMQPSender struct {
SendFn func(ctx context.Context, msg *amqp.Message) error
CloseFn func(ctx context.Context) error
}
func (m *mockAMQPSender) Send(ctx context.Context, msg *amqp.Message) error {
return m.SendFn(ctx, msg)
}
func (m *mockAMQPSender) Close(ctx context.Context) error {
return m.CloseFn(ctx)
}
|
package postgress
import (
"github.com/aleale2121/Golang-TODO-Hex-DDD/internal/constant/model"
"github.com/jinzhu/gorm"
)
type NoteRepository struct {
conn *gorm.DB
}
func NewNoteRepository(db *gorm.DB) *NoteRepository {
return &NoteRepository{db}
}
func (noteRepo *NoteRepository) Notes() ([]model.Note, []error) {
var notes []model.Note
errs := noteRepo.conn.Find(¬es).GetErrors()
if len(errs) > 0 {
return nil, errs
}
return notes, errs
}
func (noteRepo *NoteRepository) Note(id uint32) (*model.Note, []error) {
note := model.Note{}
errs := noteRepo.conn.First(¬e, id).GetErrors()
if len(errs) > 0 {
return nil, errs
}
return ¬e, errs
}
func (noteRepo *NoteRepository) UpdateNote(note *model.Note) (*model.Note, []error) {
errs := noteRepo.conn.Save(note).GetErrors()
if len(errs) > 0 {
return nil, errs
}
return note, errs
}
func (noteRepo *NoteRepository) DeleteNote(id uint32) (*model.Note, []error) {
note, errs := noteRepo.Note(id)
if len(errs) > 0 {
return nil, errs
}
errs = noteRepo.conn.Delete(note, id).GetErrors()
if len(errs) > 0 {
return nil, errs
}
return note, errs
}
func (noteRepo *NoteRepository) StoreNote(note *model.Note) (*model.Note, []error) {
errs := noteRepo.conn.Create(note).GetErrors()
if len(errs) > 0 {
return nil, errs
}
return note, errs
}
|
package lib
import "fmt"
var (
Age int
Name string
)
func init() {
fmt.Println("lib init")
Age = 100
Name = "hello"
}
|
package gogit
import (
"encoding/json"
"fmt"
"github.com/NavenduDuari/goinfo/gogit/utils"
)
func getCommit(userName string) []utils.CommitStruct {
var commitStructArr []utils.CommitStruct
repos := getRepos(userName)
go func() {
for _, repo := range repos {
commitURL := getCommitURL(userName, repo.Name)
fmt.Println("Commit URL: ", commitURL)
go getInfo(commitURL)
}
}()
for i := 1; i <= len(repos); i++ {
rawCommitInfo, ok := <-utils.RawInfo
if !ok {
continue
}
var commitStruct utils.CommitStruct
json.Unmarshal([]byte(rawCommitInfo), &commitStruct)
commitStructArr = append(commitStructArr, commitStruct)
}
return commitStructArr
}
func GetCommitCount(userName string) int {
var totalCommit int
commitStructArr := getCommit(userName)
for _, commitStruct := range commitStructArr {
totalCommit += len(commitStruct)
}
// utils.GetCommit <- totalCommit
return totalCommit
}
|
package functions
func argMax(x []float64) int {
maxIndex := 0
for i, v := range x {
if v > x[maxIndex] {
maxIndex = i
}
}
return maxIndex
}
|
package main
import (
"fmt"
"log"
)
type wallet struct{ balance float64 }
func newWallet() *wallet { return &wallet{} }
func (w *wallet) creditBalance(amount float64) {
w.balance += amount
log.Println("wallet balance added successfully")
}
func (w *wallet) debitBalance(amount float64) error {
if w.balance < amount {
return fmt.Errorf("is not sufficient balance in wallet")
}
w.balance -= amount
log.Println("successfully debited")
return nil
}
|
package main
import (
"fmt"
)
func main() {
fmt.Println(maxSubArray([]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}))
fmt.Println(maxSubArray([]int{-1}))
}
func maxSubArray(nums []int) int {
max := func(arr ...int) int {
mm := arr[0]
for _, v := range arr {
if v > mm {
mm = v
}
}
return mm
}
dp := make([]int, len(nums))
dp[0] = nums[0]
for i := 1; i < len(nums); i++ {
dp[i] = nums[i] + max(dp[i-1], 0) // 左边的哥们能给我贡献多少,不能贡献那我就算自己的
}
ans := nums[0]
for _, v := range dp {
ans = max(ans, v) // 看一下最大值
}
return ans
}
|
package main
import (
"fmt"
"sync"
"time"
)
var ch2 = make(chan int, 3)
var wg sync.WaitGroup
func main() {
wg.Add(2)
go productor()
go consumer()
wg.Wait()
}
func productor() {
defer wg.Done()
for i := 0; i < 10; i++ {
ch2 <- i
fmt.Printf("生产%d\n", i)
}
close(ch2) //不再发送数据到ch
}
func consumer() {
defer wg.Done()
time.Sleep(time.Second * 5)
for v := range ch2 {
fmt.Printf("消费 %d\t\n", v)
}
}
|
/*
‘…’ 其实是go的一种语法糖。
它的第一个用法主要是用于函数有多个不定参数的情况,可以接受多个不确定数量的参数。
第二个用法是slice可以被打散进行传递。
形参的参数前的三个点,表示可以传0到多个参数
变量后三个点表示将一个切片或数组变成一个一个的元素,即打散.
*/
//生成md5
md5 := md5.New()
io.WriteString(md5, "学生注册实验自动生成账户")
MD5Str := hex.EncodeToString(md5.Sum(nil))
fmt.Println(MD5Str)
arg := "https://share.todoen.com/mtopic/guide3.html?utm_source=baidu&utm_medium=sem&utm_device=mobile&utm_campaign=318&utm_group=11&utm_keyword=58938&renqun_youhua=1851573&bd_vid=11348576986599726827"
params, _ := url.Parse(arg)
m, _ := url.ParseQuery(params.RawQuery)
fmt.Println(m["utm_keyword"][0])
fmt.Println(m["utm_campaign"][0])
fmt.Println(m["utm_group"][0])
fmt.Println(m.Get("utm_group"))
fmt.Println(m.Get("utm_keyword"))
hans := "中国人"
a := pinyin.NewArgs()
fmt.Println(pinyin.Pinyin(hans, a))
fmt.Println(pinyin.Convert("世界", nil))
//Convert 跟 Pinyin 的唯一区别就是 a 参数可以是 nil
//range方法的index和value是值复制
for index, dashArr := range dashUserAccMap {
//遍历删除slice用for循环
for i := 0; i < len(dashArr); {
for acckey := range dashArr[i].AccountIds {
if accIdsMap[acckey] {
delete(dashArr[i].AccountIds, acckey)
}
}
if len(dashArr[i].AccountIds) == 0 {
dashArr = append(dashArr[:i], dashArr[i+1:]...)
} else {
i++
}
}
dashUserAccMap[index] = dashArr
if len(dashArr) == 0 {
delete(dashUserAccMap, index)
}
}
// make出来的是切片 指针类型
// []int这种new出来的是数组 非指针类型
// copy(a,b)
// a此时必须有值!!!!!否则复制出来的a依旧为空
// 如果b的长度大于a a的长度不会发生改变 且 a改变的是与b位置相对应的位置的值
// 总结:copy不对a扩容 只会用a原本的容量
// append出来的是一个新的切片
eg: a := make([]int, 1)
f := func(t []int) {
t = append(t, 1)
//t[0] = 1
}
f(a)
fmt.Println(a)
slice := append([]int{1,2,3},4,5,6)
fmt.Println(slice) //[1 2 3 4 5 6]
//第二个参数也可以直接写另一个切片,将它里面所有元素拷贝追加到第一个切片后面。要注意的是,这种用法函数的参数只能接收两个slice,并且末尾要加三个点
//这种切片的复制 用的是同一个数组底
slice1 := make([]int, 5, 5)
slice2 := slice1
slice2[2] = 1
fmt.Println(slice1) //[0 1 0 0 0]
fmt.Println(slice2) //[0 1 0 0 0]
//正则表达式
f, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(f)
r, _ := regexp.Compile("p([a-z]+)ch")
fmt.Println(r.MatchString("peach"))
test := "Hello 世界!123 Go."
reg := regexp.MustCompile(`[a-z]+`)
fmt.Println(reg.FindAllString(test, -1))
//eval包用法 计算string的计算表达式
str := "22.056*2+3.28*(6.7-1)/2"
r, err := evaler.Eval(str)
if err != nil {
fmt.Println(err.Error())
} else {
value := evaler.BigratToFloat(r)
fmt.Println(value)
}
fmt.Println(22.056*2 + 3.28*(6.7-1)/2)
//flag的用法
//使用方式 --filepath ""
var file = flag.String("filepath", "", "目标文件名: ../test.csv")
//不给值 默认是8
var a = flag.Int("b", 8, "")
//给任意值 都是true 不给值就是false
var b = flag.Bool("c", false, "")
flag.Parse()
//如果空 或者 0就报错
if *file == "" || *a == 0 {
flag.PrintDefaults()
os.Exit(1)
}
|
package _98_Validate_Binary_Search_Tree
import "math"
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isValidBST(root *TreeNode) bool {
return isValidBSTRecursion(root, math.MinInt64, math.MaxInt64)
}
func isValidBSTRecursion(node *TreeNode, min, max int) bool {
if node == nil {
return true
}
if node.Val <= min || node.Val >= max {
return false
}
return isValidBSTRecursion(node.Left, min, node.Val) && isValidBSTRecursion(node.Right, node.Val, max)
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//684. Redundant Connection
//In this problem, a tree is an undirected graph that is connected and has no cycles.
//The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
//The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.
//Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.
//Example 1:
//Input: [[1,2], [1,3], [2,3]]
//Output: [2,3]
//Explanation: The given undirected graph will be like this:
// 1
// / \
//2 - 3
//Example 2:
//Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
//Output: [1,4]
//Explanation: The given undirected graph will be like this:
//5 - 1 - 2
// | |
// 4 - 3
//Note:
//The size of the input 2D-array will be between 3 and 1000.
//Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.
//Update (2017-09-26):
//We have overhauled the problem description + test cases and specified clearly the graph is an undirected graph. For the directed graph follow up please see Redundant Connection II). We apologize for any inconvenience caused.
//func findRedundantConnection(edges [][]int) []int {
//}
// Time Is Money |
/**
* @Author : henry
* @Data: 2020-08-13 15:40
* @Note:
**/
package routers
import (
"github.com/gin-gonic/gin"
"github.com/vouchersAPI/app"
"net/http"
)
type Voucher interface {
AddVoucher()
SelectVoucher() Voucher
}
var logger = app.Logger
type kisUV struct{}
func AddVoucher(c *gin.Context) {
// 绑定参数
c.JSON(http.StatusOK, "Hello")
}
|
/*
If you don't know what a queen is in chess, it doesn't matter much; it's just a name :)
Your input will be a square of arbitrary width and height containing some amount of queens. The input board will look like this (this board has a width and height of 8):
...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q..
There are 8 queens on this board. If there were, say, 7, or 1, or 10 on here, the board wouldn't be valid.
Here we use a . for an empty space, and a Q for a queen. You may, alternatively, use any non-whitespace character you wish instead.
This input can be verified as valid, and you should print (or return) a truthy value (if it is was not valid, you should print (or return) a falsy value). It is valid because no queen is in the same row, column, diagonal or anti-diagonal as another.
Examples (don't output things in brackets):
...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q..
1
...Q.
Q....
.Q...
....Q
..Q..
0
Q.
Q.
0
..Q
...
.Q.
0 (this is 0 because there are only 2 queens on a 3x3 board)
..Q.
Q...
...Q
.Q..
1
Q
1 (this is valid, because the board is only 1x1, so there's no queen that can take another)
Let me stress that an input is only valid, if no queen is in the same row, column, diagonal or anti-diagonal as another.
Rules
You will never receive an empty input
If the input contains fewer queens than the sqaure root of the area of the board, it is not valid.
Note there are no valid solutions for a 2x2 or 3x3 board, but there is a solution for every other size square board, where the width and height is a natural number.
The input may be in any reasonable format, as per PPCG rules
The input will always be a sqaure
I used 1 and 0 in the examples, but you may use any truthy or falsy values (such as Why yes, sir, that is indeed the case and Why no, sir, that is not the case)
As this is code-golf, the shortest code wins!
*/
package main
func main() {
assert(satisfy([]string{
"...Q....",
"......Q.",
"..Q.....",
".......Q",
".Q......",
"....Q...",
"Q.......",
".....Q..",
}) == true)
assert(satisfy([]string{
"...Q.",
"Q....",
".Q...",
"....Q",
"..Q..",
}) == false)
assert(satisfy([]string{
"Q.",
"Q.",
}) == false)
assert(satisfy([]string{
"..Q",
"...",
".Q.",
}) == false)
assert(satisfy([]string{
"..Q.",
"Q...",
"...Q",
".Q..",
}) == true)
assert(satisfy([]string{
"Q",
}) == true)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func satisfy(s []string) bool {
dirs := [][2]int{
{-1, 0},
{1, 0},
{0, -1},
{0, 1},
{-1, -1},
{1, 1},
{-1, 1},
{1, -1},
}
i, n := 0, len(s)
for y := 0; y < n; y++ {
for x := 0; x < n; x++ {
if s[y][x] != 'Q' {
continue
}
for _, d := range dirs {
if !check(s, x, y, n, n, d[0], d[1]) {
return false
}
}
i += 1
}
}
return i == n
}
func check(s []string, x, y, w, h, dx, dy int) bool {
x, y = x+dx, y+dy
for {
if x < 0 || y < 0 || x >= w || y >= h {
break
}
if s[y][x] == 'Q' {
return false
}
x, y = x+dx, y+dy
}
return true
}
|
package models
import "github.com/jinzhu/gorm"
type Subreddit struct {
gorm.Model
Name string
Subreddit string
Posts []Post
}
|
package v1stable
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type Pet struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec PetSpec `json:"spec"`
}
type PetSpec struct {
PetSpec string `json:"petSpec"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type PetList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Pet `json:"items"`
}
|
package config
import (
"os"
"log"
"github.com/go-pg/pg/v10"
"github.com/joho/godotenv"
)
func ConnectToDB() *pg.DB {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
db := pg.Connect(&pg.Options{
User: os.Getenv("DB_USERNAME"),
Password: os.Getenv("DB_PASSWORD"),
Addr: os.Getenv("DB_HOST") + ":" + os.Getenv("DB_PORT"),
Database: "postgres",
})
return db
} |
package main
import (
"flag"
"fmt"
"github.com/clbanning/mxj"
"launchpad.net/xmlpath"
"os"
"path/filepath"
"reflect"
)
var myStack = &stack{}
var root *xmlpath.Node
var report *os.File
var matched = make([]string, 50)
var skipped = make([]string, 50)
var unmatched = make([]string, 50)
func main() {
sourceFilePath := flag.String("source-file-path", "", "source file path")
targetDirPath := flag.String("target-dir-path", "", "target dir path")
verbose := flag.Bool("verbose", false, "verbose")
flag.Parse()
if *sourceFilePath == "" || *targetDirPath == "" {
flag.PrintDefaults()
os.Exit(2)
}
var err error
report, err = os.Create("report.txt")
if err != nil {
panic(err)
}
defer report.Close()
f, err := os.Open(*sourceFilePath)
if err != nil {
panic(err)
}
defer f.Close()
root, err = xmlpath.Parse(f)
if err != nil {
panic(err)
}
filepath.Walk(*targetDirPath, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if filepath.Base(*sourceFilePath) == filepath.Base(path) {
fmt.Printf("CHECKING... %s\n", path)
fmt.Fprintf(report, "\n\nSOURCE : %s\n", *sourceFilePath)
fmt.Fprintf(report, "TARGET : %s\n", path)
f, err := os.Open(path)
if err != nil {
fmt.Println(err)
fmt.Fprintln(report, err)
return nil
}
defer f.Close()
m, err := mxj.NewMapXmlReader(f)
if err != nil {
fmt.Println(err)
fmt.Fprintln(report, err)
return nil
}
matched = matched[:0]
skipped = skipped[:0]
unmatched = unmatched[:0]
lookupMap(m)
if len(unmatched) != 0 {
fmt.Fprintf(report, "\n...UNMATCHED...\n")
for _, s := range unmatched {
fmt.Fprintf(report, "%s\n", s)
}
}
if len(skipped) != 0 {
fmt.Fprintf(report, "\n...skipped...\n")
for _, s := range skipped {
fmt.Fprintf(report, "%s\n", s)
}
}
if *verbose && len(matched) != 0 {
fmt.Fprintf(report, "\n...matched...\n")
for _, s := range matched {
fmt.Fprintf(report, "%s\n", s)
}
}
}
return nil
})
fmt.Println("DONE... report.txt")
}
func lookupMap(m map[string]interface{}) {
for n, v := range m {
myStack.push(n)
switch v2 := v.(type) {
case string:
xpath := xmlpath.MustCompile(myStack.String())
if xpath.Exists(root) {
itr := xpath.Iter(root)
isMatched := false
var srcStr string
for itr.Next() {
node := itr.Node()
srcStr = node.String()
if v2 == srcStr {
s := fmt.Sprintf("%s\t[%s]", myStack, v2)
matched = append(matched, s)
isMatched = true
break
}
}
if !isMatched {
s := fmt.Sprintf("%s, source: [%s], target: [%s]", myStack, srcStr, v2)
unmatched = append(unmatched, s)
}
} else {
s := fmt.Sprintf("%s\t[%s]", myStack, v2)
skipped = append(skipped, s)
}
case map[string]interface{}:
lookupMap(v2)
case []interface{}:
lookupSlice(v2)
default:
panic(reflect.TypeOf(v))
}
myStack.pop()
}
}
func lookupSlice(l []interface{}) {
for _, v := range l {
switch v2 := v.(type) {
case string:
panic(v2)
case map[string]interface{}:
lookupMap(v2)
default:
panic(reflect.TypeOf(v))
}
}
}
type stack struct {
nodes []string
count int
}
func (s *stack) push(n string) {
s.nodes = append(s.nodes[:s.count], n)
s.count++
}
func (s *stack) pop() string {
if s.count == 0 {
return ""
}
s.count--
return s.nodes[s.count]
}
func (s *stack) String() (ret string) {
for _, n := range s.nodes {
ret += "/" + n
}
return
}
|
package main
import (
"main/api"
"time"
"github.com/gin-gonic/gin"
cors "github.com/itsjamie/gin-cors"
)
func main(){
router := gin.Default()
//setup CORS midleware Option
config := cors.Config{
Origins: "*",
Methods: "GET, PUT, POST, DELETE",
RequestHeaders: "Origin, Authorization, Content-Type",
ExposedHeaders: "",
MaxAge: 1 * time.Minute,
Credentials: true,
ValidateHeaders: false,
}
router.Use(cors.Middleware(config))
api.Setup(router)
router.Run(":8081")
} |
package grpcDemo
import (
"encoding/json"
"fmt"
"testing"
"time"
"github.com/golang/protobuf/proto"
)
type (
Person struct {
ID int32 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
}
)
var high = int32(1000000)
func (p *Person) Reset() {
p = &Person{}
}
func (p *Person) String() string {
return proto.CompactTextString(p)
}
func (p Person) ProtoMessage() {}
func Test_proto_buffer(t *testing.T) {
t0 := time.Now()
ii := 0
for i := int32(0); i < high; i++ {
bean := &Person{
ID: i,
Name: fmt.Sprint("aa", i),
}
if buffer, err := proto.Marshal(bean); err == nil {
ii = len(buffer)
p := new(Person)
proto.Unmarshal(buffer, p)
//fmt.Println("len: ", len(buffer))
} else {
fmt.Println("error:", err)
}
}
fmt.Println("all time:", time.Since(t0), " ", ii)
}
func Test_json(t *testing.T) {
t0 := time.Now()
ii := 0
for i := int32(0); i < high; i++ {
bean := &Person{
ID: i,
Name: fmt.Sprint("aa", i),
}
if buffer, err := json.Marshal(bean); err == nil {
ii = len(buffer)
p := new(Person)
json.Unmarshal(buffer, p)
} else {
fmt.Println("error:", err)
}
}
fmt.Println("all time:", time.Since(t0), " ", ii)
}
func Test_empty_noAction(t *testing.T) {
t0 := time.Now()
j := int32(0)
for i := int32(0); i < high; i++ {
bean := &Person{
ID: i,
Name: fmt.Sprint("aa", i),
}
j = bean.ID
}
fmt.Println("all time:", time.Since(t0), " // ", j)
}
|
package main
import (
"net/http"
Bootstrapper "./source/container"
"./source/api"
)
func main() {
var kubeService = Bootstrapper.Initialize()
srv := api.New(kubeService)
http.ListenAndServe(":8081", srv)
}
|
package collections
import (
"testing"
"github.com/iotaledger/wasp/packages/kv/dict"
"github.com/stretchr/testify/assert"
)
func TestBasicArray(t *testing.T) {
vars := dict.New()
arr := NewArray(vars, "testArray")
d1 := []byte("datum1")
d2 := []byte("datum2")
d3 := []byte("datum3")
d4 := []byte("datum4")
arr.MustPush(d1)
assert.EqualValues(t, 1, arr.MustLen())
v := arr.MustGetAt(0)
assert.EqualValues(t, d1, v)
assert.Panics(t, func() {
arr.MustGetAt(1)
})
arr.MustPush(d2)
assert.EqualValues(t, 2, arr.MustLen())
arr.MustPush(d3)
assert.EqualValues(t, 3, arr.MustLen())
arr.MustPush(d4)
assert.EqualValues(t, 4, arr.MustLen())
arr2 := NewArray(vars, "testArray2")
assert.EqualValues(t, 0, arr2.MustLen())
arr2.MustExtend(arr.Immutable())
assert.EqualValues(t, arr.MustLen(), arr2.MustLen())
arr2.MustPush(d4)
assert.EqualValues(t, arr.MustLen()+1, arr2.MustLen())
}
func TestConcurrentAccess(t *testing.T) {
vars := dict.New()
a1 := NewArray(vars, "test")
a2 := NewArray(vars, "test")
a1.MustPush([]byte{1})
assert.EqualValues(t, a1.MustLen(), 1)
assert.EqualValues(t, a2.MustLen(), 1)
}
|
package rs
import (
"math/rand"
"reflect"
"github.com/renproject/secp256k1"
"github.com/renproject/shamir/eea"
"github.com/renproject/shamir/poly"
"github.com/renproject/surge"
)
// Generate implements the quick.Generator interface.
func (dec Decoder) Generate(rand *rand.Rand, size int) reflect.Value {
n := rand.Int31()
k := rand.Int31()
indices := make([]secp256k1.Fn, size/10)
for i := range indices {
indices[i] = secp256k1.RandomFn()
}
interpolator := poly.Interpolator{}.Generate(rand, size).Interface().(poly.Interpolator)
eea := eea.Stepper{}.Generate(rand, size).Interface().(eea.Stepper)
g0 := poly.Poly{}.Generate(rand, size).Interface().(poly.Poly)
interpPoly := poly.Poly{}.Generate(rand, size).Interface().(poly.Poly)
f1 := poly.Poly{}.Generate(rand, size).Interface().(poly.Poly)
r := poly.Poly{}.Generate(rand, size).Interface().(poly.Poly)
errors := make([]secp256k1.Fn, size/10)
for i := range errors {
errors[i] = secp256k1.RandomFn()
}
errorsComputed := rand.Int()&1 == 1
decoder := Decoder{
n: int(n), k: int(k),
indices: indices,
interpolator: interpolator,
eea: eea,
g0: g0,
interpPoly: interpPoly,
f1: f1, r: r,
errors: errors,
errorsComputed: errorsComputed,
}
return reflect.ValueOf(decoder)
}
// SizeHint implements the surge.SizeHinter interface.
func (dec Decoder) SizeHint() int {
return surge.SizeHintI32 +
surge.SizeHintI32 +
surge.SizeHint(dec.indices) +
dec.interpolator.SizeHint() +
dec.eea.SizeHint() +
dec.g0.SizeHint() +
dec.interpPoly.SizeHint() +
dec.f1.SizeHint() +
dec.r.SizeHint() +
surge.SizeHint(dec.errors) +
surge.SizeHint(dec.errorsComputed)
}
// Marshal implements the surge.Marshaler interface.
func (dec Decoder) Marshal(buf []byte, rem int) ([]byte, int, error) {
buf, rem, err := surge.MarshalI32(int32(dec.n), buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = surge.MarshalI32(int32(dec.k), buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = surge.Marshal(dec.indices, buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.interpolator.Marshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.eea.Marshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.g0.Marshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.interpPoly.Marshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.f1.Marshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.r.Marshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = surge.Marshal(dec.errors, buf, rem)
if err != nil {
return buf, rem, err
}
return surge.Marshal(dec.errorsComputed, buf, rem)
}
// Unmarshal implements the surge.Unmarshaler interface.
func (dec *Decoder) Unmarshal(buf []byte, rem int) ([]byte, int, error) {
var tmp int32
buf, rem, err := surge.UnmarshalI32(&tmp, buf, rem)
if err != nil {
return buf, rem, err
}
dec.n = int(tmp)
buf, rem, err = surge.UnmarshalI32(&tmp, buf, rem)
if err != nil {
return buf, rem, err
}
dec.k = int(tmp)
buf, rem, err = surge.Unmarshal(&dec.indices, buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.interpolator.Unmarshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.eea.Unmarshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.g0.Unmarshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.interpPoly.Unmarshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.f1.Unmarshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = dec.r.Unmarshal(buf, rem)
if err != nil {
return buf, rem, err
}
buf, rem, err = surge.Unmarshal(&dec.errors, buf, rem)
if err != nil {
return buf, rem, err
}
return surge.Unmarshal(&dec.errorsComputed, buf, rem)
}
|
package models
import (
"github.com/astaxie/beego/orm"
"time"
"tokensky_bg_admin/utils"
)
func (a *TokenskyJiguangRegistrationid) TableName() string {
return TokenskyJiguangRegistrationidTBName()
}
//极光地址表
type TokenskyJiguangRegistrationid struct {
Id int `orm:"pk;column(id)"json:"id"form:"id"`
UserId int `orm:"column(user_id)"json:"userId"form:"userId"`
RegistrationId string `orm:"column(registration_id)"json:"registrationId"form:"registrationId"`
//创建时间
CretaeTime time.Time `orm:"type(datetime);column(cretae_time)"json:"cretaeTime"form:"cretaeTime"`
//更新时间
UpdateTime time.Time `orm:"auto_now;type(datetime);column(update_time)"json:"updateTime"form:"updateTime"`
}
//获取极光地址
func TokenskyJiguangRegistrationidGetRegistrationId(uid int)(registrationId string){
o := orm.NewOrm()
obj := &TokenskyJiguangRegistrationid{}
err := o.QueryTable(TokenskyJiguangRegistrationidTBName()).Filter("user_id__exact",uid).One(obj,"user_id","registration_id")
if err ==nil{
registrationId = obj.RegistrationId
}
return registrationId
}
func TokenskyJiguangRegistrationidGetRegistrationIds(ids []int)(mapp map[int]string){
mapp = make(map[int]string,len(ids))
if len(ids)>0{
o := orm.NewOrm()
data := make([]*TokenskyJiguangRegistrationid,0)
_,err := o.QueryTable(TokenskyJiguangRegistrationidTBName()).Filter("user_id__in",ids).All(&data,"user_id","registration_id")
if err != nil{
return mapp
}
for _,obj := range data{
mapp[obj.Id]= obj.RegistrationId
}
}
return mapp
}
//对单人极光推送
func TokenskyJiguangRegistrationidSendByOne(uid int, alertTitle, alertContent, title, content string) {
if addr := TokenskyJiguangRegistrationidGetRegistrationId(uid);addr != ""{
utils.JiGuangSendByAddr(addr,alertTitle,alertContent,title,content)
}
}
//对多人极光推送
func TokenskyJiguangRegistrationidSendByIds(ids []int, alertTitle, alertContent, title, content string) {
addrs := TokenskyJiguangRegistrationidGetRegistrationIds(ids)
list := make([]string,0)
for _,addr := range addrs{
list = append(list, addr)
}
if len(addrs) >0{
utils.JiGuangSendByAddrs(list,alertTitle,alertContent,title,content)
}
} |
package main
import (
"fmt"
"log"
proto "github.com/nicholasjackson/building-microservices-in-go/chapter6/grpc/proto"
context "golang.org/x/net/context"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial("127.0.0.1:9000", grpc.WithInsecure())
if err != nil {
log.Fatal("Unable to create connection to server: ", err)
}
client := proto.NewKittensClient(conn)
response, err := client.Hello(context.Background(), &proto.Request{Name: "Nic"})
if err != nil {
log.Fatal("Error calling service: ", err)
}
fmt.Println(response.Msg)
}
|
package main
import (
"fmt"
"log"
"time"
)
type car struct {
letter byte
plan plan
trips chan *trip // new-trip commands arrive on this channel
eventTimer *time.Timer
nextEvent event
lastStop int // current or latest floor stopped at
lastStopTime time.Time // time at which the car left, or will leave, the laststop
}
func newCar(letter byte) *car {
c := &car{
letter: letter,
trips: make(chan *trip),
eventTimer: time.NewTimer(time.Hour),
lastStop: 1,
}
c.eventTimer.Stop()
return c
}
func (c *car) run() {
for {
select {
case t := <-c.trips:
c.logf("adding trip %s", t)
c.add(t)
case <-c.eventTimer.C:
switch c.nextEvent {
case doorClose:
c.logf("door closed")
floors := abs(c.plan[0].floor - c.lastStop)
c.nextEvent = arrive
c.eventTimer.Reset(time.Duration(int64(floors) * int64(floorDur)))
case arrive:
c.logf("arrived at %d", c.plan[0].floor)
c.lastStop = c.plan[0].floor
c.plan = c.plan[1:]
if len(c.plan) > 0 {
c.nextEvent = doorClose
c.eventTimer.Reset(doorDur)
c.lastStopTime = time.Now().Add(doorDur)
}
default:
// xxx error!
}
}
}
}
func (c *car) add(t *trip) {
var (
wasIdle = len(c.plan) == 0
lastStopTime = c.lastStopTime
nextStop int
)
if wasIdle {
lastStopTime = time.Now().Add(doorDur)
} else {
nextStop = c.plan[0].floor
}
c.plan.add(c.lastStop, lastStopTime, t)
if wasIdle {
c.lastStopTime = lastStopTime
c.nextEvent = doorClose
c.eventTimer.Reset(doorDur)
} else if nextStop != c.plan[0].floor {
// there's a new nextStop
floors := abs(c.plan[0].floor - c.lastStop)
arriveTime := lastStopTime.Add(time.Duration(int64(floors) * int64(floorDur)))
c.eventTimer.Reset(arriveTime.Sub(time.Now()))
}
}
func (c *car) logf(format string, args ...interface{}) {
format = fmt.Sprintf("car %c: %s %s", c.letter, format, c.plan)
log.Printf(format, args...)
}
|
package main
import (
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"log"
"sync"
)
var db *sqlx.DB
var dbonce sync.Once
func InitDB() {
dbonce.Do(func() {
db = sqlx.MustOpen("sqlite3", "awesomego.db")
// 创建表 awesome_go_info,先判断库中是否已存在该表
tableCount := 0
db.Get(&tableCount, `select count(*) from sqlite_master where type = 'table' and name = 'awesome_go_info'`)
if tableCount == 0{
log.Println("创建表: awesome_go_info")
db.MustExec(awesome_go_info_schema)
}
log.Println("数据库初始化成功")
})
}
const awesome_go_info_schema = `
create table awesome_go_info
(
id integer
primary key autoincrement,
repo_name varchar(50) default '',
repo_full_name varchar(100) default '',
repo_owner varchar(50) default '',
repo_html_url varchar(500) default '',
repo_description varchar(1000) default '',
repo_created_at datetime,
repo_pushed_at datetime,
repo_homepage varchar(500) default '',
repo_size integer default 0,
repo_forks_count integer default 0,
repo_stargazers_count integer default 0,
repo_subscribers_count integer default 0,
repo_open_issues_count integer default 0,
repo_license_name varchar(100) default '',
repo_license_spdx_id varchar(50) default '',
repo_license_url varchar(500) default '',
parent_id integer default 0,
repo bool default false,
category bool default false,
name varchar(50) default '',
description varchar(1000) default '',
homepage varchar(500) default '',
category_html_id varchar(100) default '',
created_at datetime,
updated_at datetime
);
` |
package ipns
import (
"fmt"
"math/rand"
"strings"
"testing"
"time"
pb "gx/ipfs/QmVpC4PPSaoqZzWYEnQURnsQagimcWEzNKZouZyd7sNJdZ/go-ipns/pb"
ci "gx/ipfs/QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s/go-libp2p-crypto"
u "gx/ipfs/QmNohiVssaPw3KVLZik59DBVGTSm2dGvYT9eoXt5DQ36Yz/go-ipfs-util"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
pstore "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore"
pstoremem "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore/pstoremem"
proto "gx/ipfs/QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8/gogo-protobuf/proto"
)
func testValidatorCase(t *testing.T, priv ci.PrivKey, kbook pstore.KeyBook, key string, val []byte, eol time.Time, exp error) {
t.Helper()
match := func(t *testing.T, err error) {
t.Helper()
if err != exp {
params := fmt.Sprintf("key: %s\neol: %s\n", key, eol)
if exp == nil {
t.Fatalf("Unexpected error %s for params %s", err, params)
} else if err == nil {
t.Fatalf("Expected error %s but there was no error for params %s", exp, params)
} else {
t.Fatalf("Expected error %s but got %s for params %s", exp, err, params)
}
}
}
testValidatorCaseMatchFunc(t, priv, kbook, key, val, eol, match)
}
func testValidatorCaseMatchFunc(t *testing.T, priv ci.PrivKey, kbook pstore.KeyBook, key string, val []byte, eol time.Time, matchf func(*testing.T, error)) {
t.Helper()
validator := Validator{kbook}
data := val
if data == nil {
p := []byte("/ipfs/QmfM2r8seH2GiRaC4esTjeraXEachRt8ZsSeGaWTPLyMoG")
entry, err := Create(priv, p, 1, eol)
if err != nil {
t.Fatal(err)
}
data, err = proto.Marshal(entry)
if err != nil {
t.Fatal(err)
}
}
matchf(t, validator.Validate(key, data))
}
func TestValidator(t *testing.T) {
ts := time.Now()
priv, id, _ := genKeys(t)
priv2, id2, _ := genKeys(t)
kbook := pstoremem.NewPeerstore()
kbook.AddPubKey(id, priv.GetPublic())
emptyKbook := pstoremem.NewPeerstore()
testValidatorCase(t, priv, kbook, "/ipns/"+string(id), nil, ts.Add(time.Hour), nil)
testValidatorCase(t, priv, kbook, "/ipns/"+string(id), nil, ts.Add(time.Hour*-1), ErrExpiredRecord)
testValidatorCase(t, priv, kbook, "/ipns/"+string(id), []byte("bad data"), ts.Add(time.Hour), ErrBadRecord)
testValidatorCase(t, priv, kbook, "/ipns/"+"bad key", nil, ts.Add(time.Hour), ErrKeyFormat)
testValidatorCase(t, priv, emptyKbook, "/ipns/"+string(id), nil, ts.Add(time.Hour), ErrPublicKeyNotFound)
testValidatorCase(t, priv2, kbook, "/ipns/"+string(id2), nil, ts.Add(time.Hour), ErrPublicKeyNotFound)
testValidatorCase(t, priv2, kbook, "/ipns/"+string(id), nil, ts.Add(time.Hour), ErrSignature)
testValidatorCase(t, priv, kbook, "//"+string(id), nil, ts.Add(time.Hour), ErrInvalidPath)
testValidatorCase(t, priv, kbook, "/wrong/"+string(id), nil, ts.Add(time.Hour), ErrInvalidPath)
}
func mustMarshal(t *testing.T, entry *pb.IpnsEntry) []byte {
t.Helper()
data, err := proto.Marshal(entry)
if err != nil {
t.Fatal(err)
}
return data
}
func TestEmbeddedPubKeyValidate(t *testing.T) {
goodeol := time.Now().Add(time.Hour)
kbook := pstoremem.NewPeerstore()
pth := []byte("/ipfs/QmfM2r8seH2GiRaC4esTjeraXEachRt8ZsSeGaWTPLyMoG")
priv, _, ipnsk := genKeys(t)
entry, err := Create(priv, pth, 1, goodeol)
if err != nil {
t.Fatal(err)
}
testValidatorCase(t, priv, kbook, ipnsk, mustMarshal(t, entry), goodeol, ErrPublicKeyNotFound)
pubkb, err := priv.GetPublic().Bytes()
if err != nil {
t.Fatal(err)
}
entry.PubKey = pubkb
testValidatorCase(t, priv, kbook, ipnsk, mustMarshal(t, entry), goodeol, nil)
entry.PubKey = []byte("probably not a public key")
testValidatorCaseMatchFunc(t, priv, kbook, ipnsk, mustMarshal(t, entry), goodeol, func(t *testing.T, err error) {
if !strings.Contains(err.Error(), "unmarshaling pubkey in record:") {
t.Fatal("expected pubkey unmarshaling to fail")
}
})
opriv, _, _ := genKeys(t)
wrongkeydata, err := opriv.GetPublic().Bytes()
if err != nil {
t.Fatal(err)
}
entry.PubKey = wrongkeydata
testValidatorCase(t, priv, kbook, ipnsk, mustMarshal(t, entry), goodeol, ErrPublicKeyMismatch)
}
func TestPeerIDPubKeyValidate(t *testing.T) {
t.Skip("disabled until libp2p/go-libp2p-crypto#51 is fixed")
goodeol := time.Now().Add(time.Hour)
kbook := pstoremem.NewPeerstore()
pth := []byte("/ipfs/QmfM2r8seH2GiRaC4esTjeraXEachRt8ZsSeGaWTPLyMoG")
sk, pk, err := ci.GenerateEd25519Key(rand.New(rand.NewSource(42)))
if err != nil {
t.Fatal(err)
}
pid, err := peer.IDFromPublicKey(pk)
if err != nil {
t.Fatal(err)
}
ipnsk := "/ipns/" + string(pid)
entry, err := Create(sk, pth, 1, goodeol)
if err != nil {
t.Fatal(err)
}
dataNoKey, err := proto.Marshal(entry)
if err != nil {
t.Fatal(err)
}
testValidatorCase(t, sk, kbook, ipnsk, dataNoKey, goodeol, nil)
}
func genKeys(t *testing.T) (ci.PrivKey, peer.ID, string) {
sr := u.NewTimeSeededRand()
priv, _, err := ci.GenerateKeyPairWithReader(ci.RSA, 1024, sr)
if err != nil {
t.Fatal(err)
}
// Create entry with expiry in one hour
pid, err := peer.IDFromPrivateKey(priv)
if err != nil {
t.Fatal(err)
}
ipnsKey := RecordKey(pid)
return priv, pid, ipnsKey
}
|
package main;
import(
"github.com/zznop/sploit"
"encoding/hex"
"fmt"
)
func main() {
instrs := "mov rcx, r12\n" +
"mov rdx, r13\n" +
"mov r8, 0x1f\n" +
"xor r9, r9\n" +
"sub rsp, 0x8\n" +
"mov qword [rsp+0x20], rax\n"
arch := &sploit.Processor {
Architecture: sploit.ArchX8664,
Endian: sploit.LittleEndian,
}
opcode, _ := sploit.Asm(arch, instrs)
fmt.Printf("Opcode bytes:\n%s\n", hex.Dump(opcode))
}
|
package services
import (
"errors"
"fmt"
"github.com/mrdulin/go-rpc-cnode/models"
"github.com/mrdulin/go-rpc-cnode/utils/http"
)
var (
ErrGetUserByLoginname = errors.New("get user by login name")
ErrValidateAccessToken = errors.New("Validate accessToken")
)
type (
GetUserByLoginnameArgs struct {
Loginname string
}
ValidateAccessTokenArgs struct {
AccessToken string
}
validateAccessTokenRequestPayload struct {
AccessToken string `json:"accesstoken"`
}
)
type userService struct {
HttpClient http.Client
BaseURL string
}
type UserService interface {
GetUserByLoginname(args *GetUserByLoginnameArgs, res *models.UserDetail) error
ValidateAccessToken(args *ValidateAccessTokenArgs, res *models.UserEntity) error
}
func NewUserService(httpClient http.Client, baseURL string) *userService {
return &userService{HttpClient: httpClient, BaseURL: baseURL}
}
func (u *userService) GetUserByLoginname(args *GetUserByLoginnameArgs, res *models.UserDetail) error {
endpoint := u.BaseURL + "/user/" + args.Loginname
err := u.HttpClient.Get(endpoint, &res)
if err != nil {
fmt.Println(err)
return ErrGetUserByLoginname
}
return nil
}
func (u *userService) ValidateAccessToken(args *ValidateAccessTokenArgs, res *models.UserEntity) error {
url := u.BaseURL + "/accesstoken"
err := u.HttpClient.Post(url, &validateAccessTokenRequestPayload{AccessToken: args.AccessToken}, &res)
if err != nil {
fmt.Println(err)
return ErrValidateAccessToken
}
return nil
}
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findFrequentTreeSum(root *TreeNode) []int {
m:=make(map[int]int)
find(root,m,0)
res:=[]int{}
max:=0
for k,v:=range m{
if v>max{
max = v
res = []int{k}
}else if v==max{
res = append(res,k)
}
}
return res
}
func find(node *TreeNode, m map[int]int,sum int)int{
if node==nil{return 0}
sum=find(node.Left,m,sum)+find(node.Right,m,sum)+node.Val
m[sum]+=1
return sum
}
|
// This file was generated for SObject ContentVersion, API Version v43.0 at 2018-07-30 03:47:31.168644141 -0400 EDT m=+17.511907673
package sobjects
import (
"fmt"
"strings"
)
type ContentVersion struct {
BaseSObject
Checksum string `force:",omitempty"`
ContentBodyId string `force:",omitempty"`
ContentDocumentId string `force:",omitempty"`
ContentLocation string `force:",omitempty"`
ContentModifiedById string `force:",omitempty"`
ContentModifiedDate string `force:",omitempty"`
ContentSize int `force:",omitempty"`
ContentUrl string `force:",omitempty"`
CreatedById string `force:",omitempty"`
CreatedDate string `force:",omitempty"`
Description string `force:",omitempty"`
ExternalDataSourceId string `force:",omitempty"`
ExternalDocumentInfo1 string `force:",omitempty"`
ExternalDocumentInfo2 string `force:",omitempty"`
FeaturedContentBoost int `force:",omitempty"`
FeaturedContentDate string `force:",omitempty"`
FileExtension string `force:",omitempty"`
FileType string `force:",omitempty"`
FirstPublishLocationId string `force:",omitempty"`
Id string `force:",omitempty"`
IsAssetEnabled bool `force:",omitempty"`
IsDeleted bool `force:",omitempty"`
IsLatest bool `force:",omitempty"`
IsMajorVersion bool `force:",omitempty"`
LastModifiedById string `force:",omitempty"`
LastModifiedDate string `force:",omitempty"`
NegativeRatingCount int `force:",omitempty"`
Origin string `force:",omitempty"`
OwnerId string `force:",omitempty"`
PathOnClient string `force:",omitempty"`
PositiveRatingCount int `force:",omitempty"`
PublishStatus string `force:",omitempty"`
RatingCount int `force:",omitempty"`
ReasonForChange string `force:",omitempty"`
SharingOption string `force:",omitempty"`
SharingPrivacy string `force:",omitempty"`
SystemModstamp string `force:",omitempty"`
TagCsv string `force:",omitempty"`
TextPreview string `force:",omitempty"`
Title string `force:",omitempty"`
VersionData string `force:",omitempty"`
VersionNumber string `force:",omitempty"`
}
func (t *ContentVersion) ApiName() string {
return "ContentVersion"
}
func (t *ContentVersion) String() string {
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("ContentVersion #%s - %s\n", t.Id, t.Name))
builder.WriteString(fmt.Sprintf("\tChecksum: %v\n", t.Checksum))
builder.WriteString(fmt.Sprintf("\tContentBodyId: %v\n", t.ContentBodyId))
builder.WriteString(fmt.Sprintf("\tContentDocumentId: %v\n", t.ContentDocumentId))
builder.WriteString(fmt.Sprintf("\tContentLocation: %v\n", t.ContentLocation))
builder.WriteString(fmt.Sprintf("\tContentModifiedById: %v\n", t.ContentModifiedById))
builder.WriteString(fmt.Sprintf("\tContentModifiedDate: %v\n", t.ContentModifiedDate))
builder.WriteString(fmt.Sprintf("\tContentSize: %v\n", t.ContentSize))
builder.WriteString(fmt.Sprintf("\tContentUrl: %v\n", t.ContentUrl))
builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById))
builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate))
builder.WriteString(fmt.Sprintf("\tDescription: %v\n", t.Description))
builder.WriteString(fmt.Sprintf("\tExternalDataSourceId: %v\n", t.ExternalDataSourceId))
builder.WriteString(fmt.Sprintf("\tExternalDocumentInfo1: %v\n", t.ExternalDocumentInfo1))
builder.WriteString(fmt.Sprintf("\tExternalDocumentInfo2: %v\n", t.ExternalDocumentInfo2))
builder.WriteString(fmt.Sprintf("\tFeaturedContentBoost: %v\n", t.FeaturedContentBoost))
builder.WriteString(fmt.Sprintf("\tFeaturedContentDate: %v\n", t.FeaturedContentDate))
builder.WriteString(fmt.Sprintf("\tFileExtension: %v\n", t.FileExtension))
builder.WriteString(fmt.Sprintf("\tFileType: %v\n", t.FileType))
builder.WriteString(fmt.Sprintf("\tFirstPublishLocationId: %v\n", t.FirstPublishLocationId))
builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id))
builder.WriteString(fmt.Sprintf("\tIsAssetEnabled: %v\n", t.IsAssetEnabled))
builder.WriteString(fmt.Sprintf("\tIsDeleted: %v\n", t.IsDeleted))
builder.WriteString(fmt.Sprintf("\tIsLatest: %v\n", t.IsLatest))
builder.WriteString(fmt.Sprintf("\tIsMajorVersion: %v\n", t.IsMajorVersion))
builder.WriteString(fmt.Sprintf("\tLastModifiedById: %v\n", t.LastModifiedById))
builder.WriteString(fmt.Sprintf("\tLastModifiedDate: %v\n", t.LastModifiedDate))
builder.WriteString(fmt.Sprintf("\tNegativeRatingCount: %v\n", t.NegativeRatingCount))
builder.WriteString(fmt.Sprintf("\tOrigin: %v\n", t.Origin))
builder.WriteString(fmt.Sprintf("\tOwnerId: %v\n", t.OwnerId))
builder.WriteString(fmt.Sprintf("\tPathOnClient: %v\n", t.PathOnClient))
builder.WriteString(fmt.Sprintf("\tPositiveRatingCount: %v\n", t.PositiveRatingCount))
builder.WriteString(fmt.Sprintf("\tPublishStatus: %v\n", t.PublishStatus))
builder.WriteString(fmt.Sprintf("\tRatingCount: %v\n", t.RatingCount))
builder.WriteString(fmt.Sprintf("\tReasonForChange: %v\n", t.ReasonForChange))
builder.WriteString(fmt.Sprintf("\tSharingOption: %v\n", t.SharingOption))
builder.WriteString(fmt.Sprintf("\tSharingPrivacy: %v\n", t.SharingPrivacy))
builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp))
builder.WriteString(fmt.Sprintf("\tTagCsv: %v\n", t.TagCsv))
builder.WriteString(fmt.Sprintf("\tTextPreview: %v\n", t.TextPreview))
builder.WriteString(fmt.Sprintf("\tTitle: %v\n", t.Title))
builder.WriteString(fmt.Sprintf("\tVersionData: %v\n", t.VersionData))
builder.WriteString(fmt.Sprintf("\tVersionNumber: %v\n", t.VersionNumber))
return builder.String()
}
type ContentVersionQueryResponse struct {
BaseQuery
Records []ContentVersion `json:"Records" force:"records"`
}
|
package main
import (
"encoding/binary"
"log"
)
func main() {
tryLittleEndian()
tryBigEndian()
tryLittleEndianAppendUint32()
}
// learnt:
// 1. we can print value in hexadecimal using #
func tryLittleEndian() {
buf := make([]byte, 4)
x := 31
log.Printf("%x %X %#x %#X", x, x, x, x)
val := 16909060
log.Printf("16909060 in hex: %#x", val)
binary.LittleEndian.PutUint32(buf, uint32(val))
log.Printf("%#v", buf)
}
func tryBigEndian() {
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, uint32(16909060))
log.Printf("%#v", buf)
}
func tryLittleEndianAppendUint32() {
num := uint32(16909060) // 0x01020304 in hexadecimal
var buf []byte
buf = binary.LittleEndian.AppendUint32(buf, num)
log.Printf("%#v\n", buf)
newNum := binary.LittleEndian.Uint32(buf)
log.Printf("%v", num == newNum)
}
|
package etcd
import (
"context"
"go.etcd.io/etcd/clientv3"
"time"
)
/*
ETCD服务注册
*/
type EtcdRegister struct {
client *clientv3.Client
lease clientv3.Lease
leaseResp *clientv3.LeaseGrantResponse
keepAliveChan <-chan *clientv3.LeaseKeepAliveResponse
cancelFunc func() // 关闭续租回调
}
/* 创建服务注册实例 */
func NewEtcdRegister(addrs []string, leaseTime int64) (*EtcdRegister, error) {
client, err := clientv3.New(clientv3.Config{
Endpoints: addrs,
DialTimeout: 5 * time.Second,
})
if err != nil {
return nil, err
}
reg := &EtcdRegister{client: client}
// 设置租约
if rst, err := reg.setLease(leaseTime); !rst {
return nil, err
}
return reg, nil
}
/* 以租约方式注册服务 */
func (e *EtcdRegister) Register(key string, val string) (bool, error) {
kv := clientv3.NewKV(e.client)
_, err := kv.Put(context.TODO(), key, val, clientv3.WithLease(e.leaseResp.ID))
if err != nil {
return false, err
}
return true, nil
}
/* 撤销租约 */
func (e *EtcdRegister) RevokeLease() (bool, error) {
e.cancelFunc()
time.Sleep(1 * time.Second)
_, err := e.lease.Revoke(context.TODO(), e.leaseResp.ID)
if err != nil {
return false, err
}
return true, nil
}
/* 监听续租情况 */
func (e *EtcdRegister) AddLeaseListener(invokeHandler func(resp clientv3.LeaseKeepAliveResponse)) {
go func() {
for {
select {
case rsp := <-e.keepAliveChan:
invokeHandler(*rsp)
// 续约失败退出
if rsp == nil {
goto END
}
}
time.Sleep(1 * time.Second)
}
END:
}()
}
/* 释放资源 */
func (e *EtcdRegister) Destroy() (bool, error) {
err := e.client.Close()
if err != nil {
return false, err
}
return true, err
}
// 设置租约
func (e *EtcdRegister) setLease(leaseTime int64) (bool, error) {
lease := clientv3.NewLease(e.client)
// 设置租约时间
leaseResp, err := lease.Grant(context.TODO(), leaseTime)
if err != nil {
return false, err
}
ctx, cancelFunc := context.WithCancel(context.TODO())
// 自动续租
keepAliveChan, err := lease.KeepAlive(ctx, leaseResp.ID)
if err != nil {
return false, err
}
e.lease = lease
e.leaseResp = leaseResp
e.cancelFunc = cancelFunc
e.keepAliveChan = keepAliveChan
return true, nil
}
|
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package android
import (
"fmt"
"reflect"
"strings"
"testing"
"github.com/google/blueprint"
"github.com/google/blueprint/proptools"
)
type mutatorTestModule struct {
ModuleBase
props struct {
Deps_missing_deps []string
Mutator_missing_deps []string
}
missingDeps []string
}
func mutatorTestModuleFactory() Module {
module := &mutatorTestModule{}
module.AddProperties(&module.props)
InitAndroidModule(module)
return module
}
func (m *mutatorTestModule) GenerateAndroidBuildActions(ctx ModuleContext) {
ctx.Build(pctx, BuildParams{
Rule: Touch,
Output: PathForModuleOut(ctx, "output"),
})
m.missingDeps = ctx.GetMissingDependencies()
}
func (m *mutatorTestModule) DepsMutator(ctx BottomUpMutatorContext) {
ctx.AddDependency(ctx.Module(), nil, m.props.Deps_missing_deps...)
}
func addMissingDependenciesMutator(ctx TopDownMutatorContext) {
ctx.AddMissingDependencies(ctx.Module().(*mutatorTestModule).props.Mutator_missing_deps)
}
func TestMutatorAddMissingDependencies(t *testing.T) {
bp := `
test {
name: "foo",
deps_missing_deps: ["regular_missing_dep"],
mutator_missing_deps: ["added_missing_dep"],
}
`
config := TestConfig(buildDir, nil, bp, nil)
config.TestProductVariables.Allow_missing_dependencies = proptools.BoolPtr(true)
ctx := NewTestContext()
ctx.SetAllowMissingDependencies(true)
ctx.RegisterModuleType("test", mutatorTestModuleFactory)
ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
ctx.TopDown("add_missing_dependencies", addMissingDependenciesMutator)
})
ctx.Register(config)
_, errs := ctx.ParseFileList(".", []string{"Android.bp"})
FailIfErrored(t, errs)
_, errs = ctx.PrepareBuildActions(config)
FailIfErrored(t, errs)
foo := ctx.ModuleForTests("foo", "").Module().(*mutatorTestModule)
if g, w := foo.missingDeps, []string{"added_missing_dep", "regular_missing_dep"}; !reflect.DeepEqual(g, w) {
t.Errorf("want foo missing deps %q, got %q", w, g)
}
}
func TestModuleString(t *testing.T) {
ctx := NewTestContext()
var moduleStrings []string
ctx.PreArchMutators(func(ctx RegisterMutatorsContext) {
ctx.BottomUp("pre_arch", func(ctx BottomUpMutatorContext) {
moduleStrings = append(moduleStrings, ctx.Module().String())
ctx.CreateVariations("a", "b")
})
ctx.TopDown("rename_top_down", func(ctx TopDownMutatorContext) {
moduleStrings = append(moduleStrings, ctx.Module().String())
ctx.Rename(ctx.Module().base().Name() + "_renamed1")
})
})
ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
ctx.BottomUp("pre_deps", func(ctx BottomUpMutatorContext) {
moduleStrings = append(moduleStrings, ctx.Module().String())
ctx.CreateVariations("c", "d")
})
})
ctx.PostDepsMutators(func(ctx RegisterMutatorsContext) {
ctx.BottomUp("post_deps", func(ctx BottomUpMutatorContext) {
moduleStrings = append(moduleStrings, ctx.Module().String())
ctx.CreateLocalVariations("e", "f")
})
ctx.BottomUp("rename_bottom_up", func(ctx BottomUpMutatorContext) {
moduleStrings = append(moduleStrings, ctx.Module().String())
ctx.Rename(ctx.Module().base().Name() + "_renamed2")
})
ctx.BottomUp("final", func(ctx BottomUpMutatorContext) {
moduleStrings = append(moduleStrings, ctx.Module().String())
})
})
ctx.RegisterModuleType("test", mutatorTestModuleFactory)
bp := `
test {
name: "foo",
}
`
config := TestConfig(buildDir, nil, bp, nil)
ctx.Register(config)
_, errs := ctx.ParseFileList(".", []string{"Android.bp"})
FailIfErrored(t, errs)
_, errs = ctx.PrepareBuildActions(config)
FailIfErrored(t, errs)
want := []string{
// Initial name.
"foo{}",
// After pre_arch (reversed because rename_top_down is TopDown so it visits in reverse order).
"foo{pre_arch:b}",
"foo{pre_arch:a}",
// After rename_top_down.
"foo_renamed1{pre_arch:a}",
"foo_renamed1{pre_arch:b}",
// After pre_deps.
"foo_renamed1{pre_arch:a,pre_deps:c}",
"foo_renamed1{pre_arch:a,pre_deps:d}",
"foo_renamed1{pre_arch:b,pre_deps:c}",
"foo_renamed1{pre_arch:b,pre_deps:d}",
// After post_deps.
"foo_renamed1{pre_arch:a,pre_deps:c,post_deps:e}",
"foo_renamed1{pre_arch:a,pre_deps:c,post_deps:f}",
"foo_renamed1{pre_arch:a,pre_deps:d,post_deps:e}",
"foo_renamed1{pre_arch:a,pre_deps:d,post_deps:f}",
"foo_renamed1{pre_arch:b,pre_deps:c,post_deps:e}",
"foo_renamed1{pre_arch:b,pre_deps:c,post_deps:f}",
"foo_renamed1{pre_arch:b,pre_deps:d,post_deps:e}",
"foo_renamed1{pre_arch:b,pre_deps:d,post_deps:f}",
// After rename_bottom_up.
"foo_renamed2{pre_arch:a,pre_deps:c,post_deps:e}",
"foo_renamed2{pre_arch:a,pre_deps:c,post_deps:f}",
"foo_renamed2{pre_arch:a,pre_deps:d,post_deps:e}",
"foo_renamed2{pre_arch:a,pre_deps:d,post_deps:f}",
"foo_renamed2{pre_arch:b,pre_deps:c,post_deps:e}",
"foo_renamed2{pre_arch:b,pre_deps:c,post_deps:f}",
"foo_renamed2{pre_arch:b,pre_deps:d,post_deps:e}",
"foo_renamed2{pre_arch:b,pre_deps:d,post_deps:f}",
}
if !reflect.DeepEqual(moduleStrings, want) {
t.Errorf("want module String() values:\n%q\ngot:\n%q", want, moduleStrings)
}
}
func TestFinalDepsPhase(t *testing.T) {
ctx := NewTestContext()
finalGot := map[string]int{}
dep1Tag := struct {
blueprint.BaseDependencyTag
}{}
dep2Tag := struct {
blueprint.BaseDependencyTag
}{}
ctx.PostDepsMutators(func(ctx RegisterMutatorsContext) {
ctx.BottomUp("far_deps_1", func(ctx BottomUpMutatorContext) {
if !strings.HasPrefix(ctx.ModuleName(), "common_dep") {
ctx.AddFarVariationDependencies([]blueprint.Variation{}, dep1Tag, "common_dep_1")
}
})
ctx.BottomUp("variant", func(ctx BottomUpMutatorContext) {
ctx.CreateLocalVariations("a", "b")
})
})
ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
ctx.BottomUp("far_deps_2", func(ctx BottomUpMutatorContext) {
if !strings.HasPrefix(ctx.ModuleName(), "common_dep") {
ctx.AddFarVariationDependencies([]blueprint.Variation{}, dep2Tag, "common_dep_2")
}
})
ctx.BottomUp("final", func(ctx BottomUpMutatorContext) {
finalGot[ctx.Module().String()] += 1
ctx.VisitDirectDeps(func(mod Module) {
finalGot[fmt.Sprintf("%s -> %s", ctx.Module().String(), mod)] += 1
})
})
})
ctx.RegisterModuleType("test", mutatorTestModuleFactory)
bp := `
test {
name: "common_dep_1",
}
test {
name: "common_dep_2",
}
test {
name: "foo",
}
`
config := TestConfig(buildDir, nil, bp, nil)
ctx.Register(config)
_, errs := ctx.ParseFileList(".", []string{"Android.bp"})
FailIfErrored(t, errs)
_, errs = ctx.PrepareBuildActions(config)
FailIfErrored(t, errs)
finalWant := map[string]int{
"common_dep_1{variant:a}": 1,
"common_dep_1{variant:b}": 1,
"common_dep_2{variant:a}": 1,
"common_dep_2{variant:b}": 1,
"foo{variant:a}": 1,
"foo{variant:a} -> common_dep_1{variant:a}": 1,
"foo{variant:a} -> common_dep_2{variant:a}": 1,
"foo{variant:b}": 1,
"foo{variant:b} -> common_dep_1{variant:b}": 1,
"foo{variant:b} -> common_dep_2{variant:a}": 1,
}
if !reflect.DeepEqual(finalWant, finalGot) {
t.Errorf("want:\n%q\ngot:\n%q", finalWant, finalGot)
}
}
func TestNoCreateVariationsInFinalDeps(t *testing.T) {
ctx := NewTestContext()
checkErr := func() {
if err := recover(); err == nil || !strings.Contains(fmt.Sprintf("%s", err), "not allowed in FinalDepsMutators") {
panic("Expected FinalDepsMutators consistency check to fail")
}
}
ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
ctx.BottomUp("vars", func(ctx BottomUpMutatorContext) {
defer checkErr()
ctx.CreateVariations("a", "b")
})
ctx.BottomUp("local_vars", func(ctx BottomUpMutatorContext) {
defer checkErr()
ctx.CreateLocalVariations("a", "b")
})
})
ctx.RegisterModuleType("test", mutatorTestModuleFactory)
config := TestConfig(buildDir, nil, `test {name: "foo"}`, nil)
ctx.Register(config)
_, errs := ctx.ParseFileList(".", []string{"Android.bp"})
FailIfErrored(t, errs)
_, errs = ctx.PrepareBuildActions(config)
FailIfErrored(t, errs)
}
|
package main
import (
"flag"
"fmt"
"os"
"github.com/ikaven1024/bolt-cli/cli"
"github.com/ikaven1024/bolt-cli/db"
"github.com/ikaven1024/bolt-cli/version"
)
var (
pPath = flag.String("path", "", "path of db file")
pWeb = flag.Bool("web", false, "support web if set")
pVersion = flag.Bool("version", false, "print version and exit")
)
func main() {
flag.Parse()
if *pVersion {
fmt.Print(version.Version)
os.Exit(0)
}
if len(*pPath) == 0 {
fmt.Println("path is not set")
os.Exit(1)
}
db, err := db.New(*pPath)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if *pWeb {
panic("Not Implement")
} else {
cli.Run(db)
}
}
|
package 排序
import "sort"
func kWeakestRows(mat [][]int, k int) []int {
units := make([]*Unit, 0)
for i := 0; i < len(mat); i++ {
units = append(units, &Unit{
Row: i,
CountOfSoldier: getCountOfOne(mat[i]),
})
}
sort.Slice(units, func(i, t int) bool {
if units[i].CountOfSoldier == units[t].CountOfSoldier {
return units[i].Row < units[t].Row
}
return units[i].CountOfSoldier < units[t].CountOfSoldier
})
result := make([]int, 0)
for i := 0; i < k; i++ {
result = append(result, units[i].Row)
}
return result
}
func getCountOfOne(arr []int) int {
left, right := 0, len(arr)-1
for left <= right {
mid := (left + right) / 2
if arr[mid] == 0 {
right = mid - 1
} else {
left = mid + 1
}
}
return right + 1
}
type Unit struct {
Row int
CountOfSoldier int
}
/*
题目链接: https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix/
*/
|
package main
import (
"bytes"
"encoding/json"
"net/http"
"github.com/NYTimes/gziphandler"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/fiatjaf/lightningd-gjson-rpc/plugin"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/rs/cors"
)
var err error
var scookie = securecookie.New(securecookie.GenerateRandomKey(32), nil)
var accessKey string
var manifestKey string
var login string
var ee chan event
var keys Keys
var httpPublic = &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "spark-wallet/client/dist/"}
const DEFAULTPORT = "9737"
func main() {
p := plugin.Plugin{
Name: "sparko",
Version: "v2.1",
Options: []plugin.Option{
{"sparko-host", "string", "127.0.0.1", "http(s) server listen address"},
{"sparko-port", "string", DEFAULTPORT, "http(s) server port"},
{"sparko-login", "string", nil, "http basic auth login, \"username:password\" format"},
{"sparko-keys", "string", nil, "semicolon-separated list of key-permissions pairs"},
{"sparko-tls-path", "string", nil, "directory to read/store key.pem and cert.pem for TLS (relative to your lightning directory)"},
{"sparko-letsencrypt-email", "string", nil, "email in which LetsEncrypt will notify you and other things"},
{"sparko-allow-cors", "bool", false, "allow CORS"},
},
RPCMethods: []plugin.RPCMethod{
InvoiceWithDescriptionHashMethod,
},
Subscriptions: []plugin.Subscription{
{
"invoice_payment",
func(p *plugin.Plugin, params plugin.Params) {
// serve both events
// our generic one
subscribeSSE("invoice_payment").Handler(p, params)
// and the one spark wants
label := params.Get("invoice_payment.label").String()
inv, err := p.Client.Call("waitinvoice", label)
if err != nil {
p.Logf("Failed to get invoice on inv-paid notification: %s", err)
return
}
ee <- event{typ: "inv-paid", data: inv.String()}
},
},
subscribeSSE("channel_opened"),
subscribeSSE("connect"),
subscribeSSE("disconnect"),
subscribeSSE("warning"),
subscribeSSE("forward_event"),
subscribeSSE("sendpay_success"),
subscribeSSE("sendpay_failure"),
subscribeSSE("sendpay_success"),
},
OnInit: func(p *plugin.Plugin) {
// compute access key
login, _ = p.Args.String("sparko-login")
if login != "" {
accessKey = hmacStr(login, "access-key")
manifestKey = hmacStr(accessKey, "manifest-key")
p.Log("Login credentials read: " + login + " (full-access key: " + accessKey + ")")
}
// permissions
if keypermissions, err := p.Args.String("sparko-keys"); err == nil {
keys, err = readPermissionsConfig(keypermissions)
if err != nil {
p.Log("Error reading permissions config: " + err.Error())
return
}
message, nkeys := keys.Summary()
p.Logf("%d keys read: %s", nkeys, message)
if nkeys == 0 {
p.Log("DANGER: All methods are free for anyone to call without authorization.")
}
}
// start eventsource thing
es := startStreams(p)
// declare routes
router := mux.NewRouter()
router.Use(authMiddleware)
router.Use(gziphandler.GzipHandler)
router.Path("/stream").Methods("GET").Handler(
checkStreamPermission(es),
)
router.Path("/rpc").Methods("POST").Handler(http.HandlerFunc(handleRPC))
if login != "" {
// web ui
router.Path("/").Methods("GET").HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
indexb, err := Asset("spark-wallet/client/dist/index.html")
if err != nil {
w.WriteHeader(404)
return
}
indexb = bytes.Replace(indexb, []byte("{{accessKey}}"), []byte(accessKey), -1)
indexb = bytes.Replace(indexb, []byte("{{manifestKey}}"), []byte(manifestKey), -1)
w.Header().Set("Content-Type", "text/html")
w.Write(indexb)
return
})
router.PathPrefix("/").Methods("GET").Handler(http.FileServer(httpPublic))
}
// start server
if p.Args.Get("sparko-allow-cors").Bool() {
listen(p, cors.AllowAll().Handler(router))
} else {
listen(p, router)
}
},
}
p.Run()
}
func subscribeSSE(kind string) plugin.Subscription {
return plugin.Subscription{
kind,
func(p *plugin.Plugin, params plugin.Params) {
j, _ := json.Marshal(params)
ee <- event{typ: kind, data: string(j)}
},
}
}
|
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
var _ sdk.Msg = &MsgCreateOrchestratorAddress{}
func NewMsgCreateOrchestratorAddress(validator string, orchestrator string, ethAddress string) *MsgCreateOrchestratorAddress {
return &MsgCreateOrchestratorAddress{
Validator: validator,
Orchestrator: orchestrator,
EthAddress: ethAddress,
}
}
func (msg *MsgCreateOrchestratorAddress) Route() string {
return RouterKey
}
func (msg *MsgCreateOrchestratorAddress) Type() string {
return "CreateOrchestratorAddress"
}
func (msg *MsgCreateOrchestratorAddress) GetSigners() []sdk.AccAddress {
creator, err := sdk.AccAddressFromBech32(msg.Orchestrator)
if err != nil {
panic(err)
}
return []sdk.AccAddress{creator}
}
func (msg *MsgCreateOrchestratorAddress) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(msg)
return sdk.MustSortJSON(bz)
}
func (msg *MsgCreateOrchestratorAddress) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Orchestrator)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err)
}
return nil
}
var _ sdk.Msg = &MsgUpdateOrchestratorAddress{}
func NewMsgUpdateOrchestratorAddress(creator string, id uint64, validator string, orchestrator string, ethAddress string) *MsgUpdateOrchestratorAddress {
return &MsgUpdateOrchestratorAddress{
Id: id,
Creator: creator,
Validator: validator,
Orchestrator: orchestrator,
EthAddress: ethAddress,
}
}
func (msg *MsgUpdateOrchestratorAddress) Route() string {
return RouterKey
}
func (msg *MsgUpdateOrchestratorAddress) Type() string {
return "UpdateOrchestratorAddress"
}
func (msg *MsgUpdateOrchestratorAddress) GetSigners() []sdk.AccAddress {
creator, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
panic(err)
}
return []sdk.AccAddress{creator}
}
func (msg *MsgUpdateOrchestratorAddress) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(msg)
return sdk.MustSortJSON(bz)
}
func (msg *MsgUpdateOrchestratorAddress) 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 = &MsgCreateOrchestratorAddress{}
func NewMsgDeleteOrchestratorAddress(creator string, id uint64) *MsgDeleteOrchestratorAddress {
return &MsgDeleteOrchestratorAddress{
Id: id,
Creator: creator,
}
}
func (msg *MsgDeleteOrchestratorAddress) Route() string {
return RouterKey
}
func (msg *MsgDeleteOrchestratorAddress) Type() string {
return "DeleteOrchestratorAddress"
}
func (msg *MsgDeleteOrchestratorAddress) GetSigners() []sdk.AccAddress {
creator, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
panic(err)
}
return []sdk.AccAddress{creator}
}
func (msg *MsgDeleteOrchestratorAddress) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(msg)
return sdk.MustSortJSON(bz)
}
func (msg *MsgDeleteOrchestratorAddress) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err)
}
return nil
}
|
package handlers
import (
"bytes"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/json"
"golang-rest/common"
"golang-rest/middlewares"
"golang-rest/models"
"net/http"
"net/http/httptest"
"testing"
)
func SetupRouter() *gin.Engine {
db, _ := common.Initialize()
router := gin.Default()
router.Use(common.Inject(db))
router.Use(gin.Recovery())
auth := router.Group("/api/v1/")
auth.Use(middlewares.CORSMiddlewareHandler())
// public endpoints.
auth.POST("/access-token", GetAccessToken)
return router
}
func TestGetAccessToken(t *testing.T) {
testRouter := SetupRouter()
login := models.Login{}
login.Username = "onurkaya"
login.Password = "onurkaya"
body, _ := json.Marshal(login)
buf := bytes.NewBuffer(body)
req, err := http.NewRequest("POST", "/api/v1/access-token", buf)
req.Header.Set("Content-Type", "application/json")
if err != nil {
t.Fatal(err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 201 {
t.Fatal("Invalid Request")
}
}
|
// Copyright 2017 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 types
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestContainsAnyAsterisk(t *testing.T) {
var tests = []struct {
expression string
containsAsterisks bool
}{
{"$.a[1]", false},
{"$.a[*]", true},
{"$.*[1]", true},
{"$**.a[1]", true},
}
for _, test := range tests {
// copy iterator variable into a new variable, see issue #27779
test := test
t.Run(test.expression, func(t *testing.T) {
pe, err := ParseJSONPathExpr(test.expression)
require.NoError(t, err)
require.Equal(t, test.containsAsterisks, pe.flags.containsAnyAsterisk())
})
}
}
func TestValidatePathExpr(t *testing.T) {
var tests = []struct {
expression string
success bool
legs int
}{
{` $ `, true, 0},
{" $ . key1 [ 3 ]\t[*].*.key3", true, 5},
{" $ . key1 [ 3 ]**[*].*.key3", true, 6},
{`$."key1 string"[ 3 ][*].*.key3`, true, 5},
{`$."hello \"escaped quotes\" world\\n"[3][*].*.key3`, true, 5},
{`$[1 to 5]`, true, 1},
{`$[2 to 1]`, false, 1},
{`$[last]`, true, 1},
{`$[1 to last]`, true, 1},
{`$[1to3]`, false, 1},
{`$[last - 5 to last - 10]`, false, 1},
{`$.\"escaped quotes\"[3][*].*.key3`, false, 0},
{`$.hello \"escaped quotes\" world[3][*].*.key3`, false, 0},
{`$NoValidLegsHere`, false, 0},
{`$ No Valid Legs Here .a.b.c`, false, 0},
{`$.a[b]`, false, 0},
{`$.*[b]`, false, 0},
{`$**.a[b]`, false, 0},
{`$.b[ 1 ].`, false, 0},
{`$.performance.txn-entry-size-limit`, false, 0},
{`$."performance".txn-entry-size-limit`, false, 0},
{`$."performance."txn-entry-size-limit`, false, 0},
{`$."performance."txn-entry-size-limit"`, false, 0},
{`$[`, false, 0},
{`$a.***[3]`, false, 0},
{`$1a`, false, 0},
}
for _, test := range tests {
// copy iterator variable into a new variable, see issue #27779
test := test
t.Run(test.expression, func(t *testing.T) {
pe, err := ParseJSONPathExpr(test.expression)
if test.success {
require.NoError(t, err)
require.Len(t, pe.legs, test.legs)
} else {
require.Error(t, err)
}
})
}
}
func TestPathExprToString(t *testing.T) {
var tests = []struct {
expression string
}{
{"$.a[1]"},
{"$.a[*]"},
{"$.*[2]"},
{"$**.a[3]"},
{`$."\"hello\""`},
{`$."a b"`},
{`$."one potato"`},
}
for _, test := range tests {
// copy iterator variable into a new variable, see issue #27779
test := test
t.Run(test.expression, func(t *testing.T) {
pe, err := ParseJSONPathExpr(test.expression)
require.NoError(t, err)
require.Equal(t, test.expression, pe.String())
})
}
}
func TestPushBackOneIndexLeg(t *testing.T) {
var tests = []struct {
expression string
index int
expected string
couldReturnMultipleValues bool
}{
{"$", 1, "$[1]", false},
{"$.a[1]", 1, "$.a[1][1]", false},
{"$.a[*]", 10, "$.a[*][10]", true},
{"$.*[2]", 2, "$.*[2][2]", true},
{"$**.a[3]", 3, "$**.a[3][3]", true},
{"$.a[1 to 3]", 3, "$.a[1 to 3][3]", true},
{"$.a[last-3 to last-3]", 3, "$.a[last-3 to last-3][3]", true},
{"$**.a[3]", -3, "$**.a[3][last-2]", true},
}
for _, test := range tests {
// copy iterator variable into a new variable, see issue #27779
test := test
t.Run(test.expression, func(t *testing.T) {
pe, err := ParseJSONPathExpr(test.expression)
require.NoError(t, err)
pe = pe.pushBackOneArraySelectionLeg(jsonPathArraySelectionIndex{index: jsonPathArrayIndexFromStart(test.index)})
require.Equal(t, test.expected, pe.String())
require.Equal(t, test.couldReturnMultipleValues, pe.CouldMatchMultipleValues())
})
}
}
func TestPushBackOneKeyLeg(t *testing.T) {
var tests = []struct {
expression string
key string
expected string
couldReturnMultipleValues bool
}{
{"$", "aa", "$.aa", false},
{"$.a[1]", "aa", "$.a[1].aa", false},
{"$.a[1]", "*", "$.a[1].*", true},
{"$.a[*]", "k", "$.a[*].k", true},
{"$.*[2]", "bb", "$.*[2].bb", true},
{"$**.a[3]", "cc", "$**.a[3].cc", true},
}
for _, test := range tests {
t.Run(test.expression, func(t *testing.T) {
pe, err := ParseJSONPathExpr(test.expression)
require.NoError(t, err)
pe = pe.pushBackOneKeyLeg(test.key)
require.Equal(t, test.expected, pe.String())
require.Equal(t, test.couldReturnMultipleValues, pe.CouldMatchMultipleValues())
})
}
}
|
package api
import (
"net/http"
"strings"
"github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/rancher/go-rancher/api"
"github.com/rancher/longhorn-manager/types"
)
type SnapshotHandlers struct {
man types.VolumeManager
}
func (sh *SnapshotHandlers) Create(w http.ResponseWriter, req *http.Request) error {
var input SnapshotInput
apiContext := api.GetApiContext(req)
if err := apiContext.Read(&input); err != nil {
return errors.Wrapf(err, "error read snapshotInput")
}
for k, v := range input.Labels {
if strings.Contains(k, "=") || strings.Contains(v, "=") {
return errors.New("labels cannot contain '='")
}
}
volName := mux.Vars(req)["name"]
if volName == "" {
return errors.Errorf("volume name required")
}
snapOps, err := sh.man.SnapshotOps(volName)
if err != nil {
return errors.Wrapf(err, "error getting SnapshotOps for volume '%s'", volName)
}
snapName, err := snapOps.Create(input.Name, input.Labels)
if err != nil {
return errors.Wrapf(err, "error creating snapshot '%s', for volume '%s'", input.Name, volName)
}
logrus.Debugf("created snapshot '%s'", snapName)
snap, err := snapOps.Get(snapName)
if err != nil {
return errors.Wrapf(err, "error getting snapshot '%s', for volume '%s'", snapName, volName)
}
if snap == nil {
return errors.Errorf("not found just created snapshot '%s', for volume '%s'", snapName, volName)
}
logrus.Debugf("success: created snapshot '%s' for volume '%s'", snapName, volName)
apiContext.Write(toSnapshotResource(snap))
return nil
}
func (sh *SnapshotHandlers) List(w http.ResponseWriter, req *http.Request) error {
volName := mux.Vars(req)["name"]
if volName == "" {
return errors.Errorf("volume name required")
}
snapOps, err := sh.man.SnapshotOps(volName)
if err != nil {
return errors.Wrapf(err, "error getting SnapshotOps for volume '%s'", volName)
}
snapList, err := snapOps.List()
if err != nil {
return errors.Wrapf(err, "error listing snapshots, for volume '%+v'", volName)
}
logrus.Debugf("success: listed snapshots for volume '%s'", volName)
api.GetApiContext(req).Write(toSnapshotCollection(snapList))
return nil
}
func (sh *SnapshotHandlers) Get(w http.ResponseWriter, req *http.Request) error {
var input SnapshotInput
apiContext := api.GetApiContext(req)
if err := apiContext.Read(&input); err != nil {
return errors.Wrapf(err, "error read snapshotInput")
}
if input.Name == "" {
return errors.Errorf("empty snapshot name not allowed")
}
volName := mux.Vars(req)["name"]
if volName == "" {
return errors.Errorf("volume name required")
}
snapOps, err := sh.man.SnapshotOps(volName)
if err != nil {
return errors.Wrapf(err, "error getting SnapshotOps for volume '%s'", volName)
}
snap, err := snapOps.Get(input.Name)
if err != nil {
return errors.Wrapf(err, "error getting snapshot '%s', for volume '%s'", input.Name, volName)
}
if snap == nil {
return errors.Errorf("not found snapshot '%s', for volume '%s'", input.Name, volName)
}
logrus.Debugf("success: got snapshot '%s' for volume '%s'", snap.Name, volName)
api.GetApiContext(req).Write(toSnapshotResource(snap))
return nil
}
func (sh *SnapshotHandlers) Delete(w http.ResponseWriter, req *http.Request) error {
var input SnapshotInput
apiContext := api.GetApiContext(req)
if err := apiContext.Read(&input); err != nil {
return errors.Wrapf(err, "error read snapshotInput")
}
if input.Name == "" {
return errors.Errorf("empty snapshot name not allowed")
}
volName := mux.Vars(req)["name"]
if volName == "" {
return errors.Errorf("volume name required")
}
snapOps, err := sh.man.SnapshotOps(volName)
if err != nil {
return errors.Wrapf(err, "error getting SnapshotOps for volume '%s'", volName)
}
if err := snapOps.Delete(input.Name); err != nil {
return errors.Wrapf(err, "error deleting snapshot '%+v', for volume '%+v'", input.Name, volName)
}
snap, err := snapOps.Get(input.Name)
if err != nil {
return errors.Wrapf(err, "error getting snapshot '%s', for volume '%s'", input.Name, volName)
}
if snap == nil {
return errors.Errorf("not found snapshot '%s', for volume '%s'", input.Name, volName)
}
logrus.Debugf("success: deleted snapshot '%s' for volume '%s'", input.Name, volName)
api.GetApiContext(req).Write(toSnapshotResource(snap))
return nil
}
func (sh *SnapshotHandlers) Revert(w http.ResponseWriter, req *http.Request) error {
var input SnapshotInput
apiContext := api.GetApiContext(req)
if err := apiContext.Read(&input); err != nil {
return errors.Wrapf(err, "error read snapshotInput")
}
if input.Name == "" {
return errors.Errorf("empty snapshot name not allowed")
}
volName := mux.Vars(req)["name"]
if volName == "" {
return errors.Errorf("volume name required")
}
snapOps, err := sh.man.SnapshotOps(volName)
if err != nil {
return errors.Wrapf(err, "error getting SnapshotOps for volume '%s'", volName)
}
if err := snapOps.Revert(input.Name); err != nil {
return errors.Wrapf(err, "error reverting to snapshot '%+v', for volume '%+v'", input.Name, volName)
}
snap, err := snapOps.Get(input.Name)
if err != nil {
return errors.Wrapf(err, "error getting snapshot '%s', for volume '%s'", input.Name, volName)
}
if snap == nil {
return errors.Errorf("not found snapshot '%s', for volume '%s'", input.Name, volName)
}
logrus.Debugf("success: reverted to snapshot '%s' for volume '%s'", input.Name, volName)
api.GetApiContext(req).Write(toSnapshotResource(snap))
return nil
}
func (sh *SnapshotHandlers) Backup(w http.ResponseWriter, req *http.Request) error {
var input SnapshotInput
apiContext := api.GetApiContext(req)
if err := apiContext.Read(&input); err != nil {
return errors.Wrapf(err, "error read snapshotInput")
}
if input.Name == "" {
return errors.Errorf("empty snapshot name not allowed")
}
volName := mux.Vars(req)["name"]
if volName == "" {
return errors.Errorf("volume name required")
}
settings, err := sh.man.Settings().GetSettings()
if err != nil || settings == nil {
return errors.New("cannot backup: unable to read settings")
}
backupTarget := settings.BackupTarget
if backupTarget == "" {
return errors.New("cannot backup: backupTarget not set")
}
backups, err := sh.man.VolumeBackupOps(volName)
if err != nil {
return errors.Wrapf(err, "error getting VolumeBackupOps for volume '%s'", volName)
}
if err := backups.StartBackup(input.Name, backupTarget); err != nil {
return errors.Wrapf(err, "error creating backup: snapshot '%s', volume '%s', dest '%s'", input.Name, volName, backupTarget)
}
logrus.Debugf("success: started backup: snapshot '%s', volume '%s', dest '%s'", input.Name, volName, backupTarget)
apiContext.Write(&Empty{})
return nil
}
func (sh *SnapshotHandlers) Purge(w http.ResponseWriter, req *http.Request) error {
volName := mux.Vars(req)["name"]
if volName == "" {
return errors.Errorf("volume name required")
}
snapOps, err := sh.man.SnapshotOps(volName)
if err != nil {
return errors.Wrapf(err, "error getting SnapshotOps for volume '%s'", volName)
}
if err := snapOps.Purge(); err != nil {
return errors.Wrapf(err, "error purging snapshots, for volume '%+v'", volName)
}
logrus.Debugf("success: purge snapshots for volume '%s'", volName)
api.GetApiContext(req).Write(&Empty{})
return nil
}
|
package impl3
import "github.com/sko00o/leetcode-adventure/queue-stack/queue"
/*
Notes:
○ 用队列模拟栈
§ 可以只用一个队列,压栈操作时,判断队列长度是否大于 1,
如果大于1,将n-1个元素出队再入队,以达到将队尾元素排到队头的效果。
出栈操作时,直接出队即可。压栈操作的时间复杂度是 O(n) 。
*/
// Queue is a FIFO Data Structure.
type Queue struct {
queue.SliceQueue
}
// MyStack is a stack using queue.
type MyStack struct {
Q Queue
}
// Constructor return MyStack object.
func Constructor() MyStack {
return MyStack{
Q: Queue{},
}
}
// Push element x onto stack.
// time complexity: O(n)
// space complexity : O(1)
func (s *MyStack) Push(x int) {
s.Q.EnQueue(x)
for i := len(s.Q.Data); i > 1; i-- {
s.Q.EnQueue(s.Q.Front())
s.Q.DeQueue()
}
}
// Pop removes the element on top of the stack and returns that element.
// time complexity: O(1)
// space complexity : O(1)
func (s *MyStack) Pop() int {
if s.Q.IsEmpty() {
return -1
}
res := s.Q.Front().(int)
s.Q.DeQueue()
return res
}
// Top get the top element.
// time complexity: O(1)
// space complexity : O(1)
func (s *MyStack) Top() int {
if s.Q.IsEmpty() {
return -1
}
return s.Q.Front().(int)
}
// Empty returns whether the queue is empty.
// time complexity: O(1)
// space complexity : O(1)
func (s *MyStack) Empty() bool {
return s.Q.IsEmpty()
}
|
package service
import (
"github.com/SungKing/blogsystem/models/entity"
"github.com/SungKing/blogsystem/models/dao"
)
type CommentService struct {
}
var commentDao = new(dao.CommentDao)
func (* CommentService)GetOne(id int32) entity.Comment {
return commentDao.GetOne(id)
}
func (* CommentService)QueryBlogComment(blogId int32)[]entity.Comment {
return commentDao.Query(blogId,1)
}
func (* CommentService) Insert(comment entity.Comment) int64 {
return commentDao.Insert(comment)
} |
package sync
import (
"time"
"github.com/cpusoft/goutil/belogs"
"github.com/cpusoft/goutil/xormdb"
)
// filePath, is nic dest path, eg: /root/rpki/data/reporrdp/rpki.apnic.cn/
func DelByFilePathDb(filePath string) (err error) {
start := time.Now()
belogs.Debug("DelByFilePathDb(): filePath:", filePath)
if len(filePath) == 0 {
belogs.Debug("DelByFilePathDb(): len(filePath) == 0:")
return nil
}
session, err := xormdb.NewSession()
defer session.Close()
err = delCerDb(session, filePath)
if err != nil {
belogs.Error("DelByFilePathDb(): delCerDb fail, filePath: ",
filePath, err)
return err
}
err = delCrlDb(session, filePath)
if err != nil {
belogs.Error("DelByFilePathDb(): delCrlDb fail, filePath: ",
filePath, err)
return err
}
err = delMftDb(session, filePath)
if err != nil {
belogs.Error("DelByFilePathDb(): delMftDb fail, filePath: ",
filePath, err)
return err
}
err = delRoaDb(session, filePath)
if err != nil {
belogs.Error("DelByFilePathDb(): delRoaDb fail, filePath: ",
filePath, err)
return err
}
err = delAsaDb(session, filePath)
if err != nil {
belogs.Error("DelByFilePathDb(): delAsaDb fail, filePath: ",
filePath, err)
return err
}
err = xormdb.CommitSession(session)
if err != nil {
return xormdb.RollbackAndLogError(session, "DelByFilePathsDb(): CommitSession fail:", err)
}
belogs.Info("DelByFilePathsDb(): filePath:", filePath, " time(s):", time.Since(start))
return nil
}
// param: cerId/roaId/crlId/mftId
// paramIdsStr: cerIdsStr/roaIdsStr/crlIdsStr/mftIdsStr
func getIdsByParamIdsDb(tableName string, param string, paramIdsStr string) (ids []int64, err error) {
belogs.Debug("getIdsByParamIdsDb():tableName :", tableName,
" param:", param, " paramIdsStr:", paramIdsStr)
ids = make([]int64, 0)
// get ids from tableName
err = xormdb.XormEngine.SQL("select id from " + tableName + " where " + param + " in " + paramIdsStr).Find(&ids)
if err != nil {
belogs.Error("getIdsByParamIdsDb(): get id fail, tableName: ", tableName, " param:", param,
" paramIdsStr:", paramIdsStr, err)
return nil, err
}
belogs.Debug("getIdsByParamIdsDb():get id fail, tableName: ", tableName, " param:", param,
" paramIdsStr:", paramIdsStr, " ids:", ids)
return ids, nil
}
|
// Copyright 2016 Lennart Espe. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.
// Bench is a file patching system using HTTPS and secure file hashing.
package main
import (
"flag"
"fmt"
"path/filepath"
"github.com/lnsp/bench/lib"
"github.com/lnsp/pkginfo"
)
var (
DynamicPool = flag.Bool("dynamic", true, "Dynamic worker pool")
PoolSize = flag.Int("worker", 1, "Async worker count")
PatchSource = flag.String("source", "./", "Source target")
TargetDirectory = flag.String("target", "./", "Local target")
VerboseOutput = flag.Bool("verbose", false, "Verbose logging")
PkgInfo = pkginfo.PackageInfo{
Name: "bench",
Version: pkginfo.PackageVersion{
Major: 0,
Minor: 2,
Patch: 1,
},
}
)
const (
HelpText = `USAGE: bench [action]
Available actions:
generate - Generate patch files from active folder
version - Print software version information
fetch - Fetch updated files using file or server origin
help - Display command overview
Available flags:
--target - Local target (default "./")
--verbose - Verbose logging (default false)
--source - Source target (default "./")
--worker - Async worker count (default 1)
--dynamic - Dynamic worker count (default true)`
)
func main() {
flag.Parse()
lib.SetVerbose(*VerboseOutput)
workingDir, _ := filepath.Abs(*TargetDirectory)
command := flag.Arg(0)
switch command {
case "generate":
lib.Generate(workingDir, *PatchSource, *PoolSize, *DynamicPool)
case "fetch":
lib.Fetch(workingDir, *PatchSource, *PoolSize, *DynamicPool)
case "version":
printVersion()
case "help":
fallthrough // to existing help case
default:
fmt.Println(HelpText)
}
}
func printVersion() {
fmt.Println(PkgInfo)
}
|
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
fmt.Printf("Hello, World!\n")
fmt.Printf("The sum of 2 and 3 is 5.\n")
first, _ := strconv.Atoi(os.Args[1])
second, _ := strconv.Atoi(os.Args[2])
sum := first + second
fmt.Printf("The sum of %s and %s is %s.",
os.Args[1], os.Args[2], strconv.Itoa(sum))
}
|
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
_ "walletApi/routers"
"walletApi/src/common"
"walletApi/src/model"
"walletApi/src/service"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/toolbox"
"github.com/beego/i18n"
)
//初始化
func init() {
dbhost := beego.AppConfig.String("dbhost")
dbport := beego.AppConfig.String("dbport")
dbuser := beego.AppConfig.String("dbuser")
dbpassword := beego.AppConfig.String("dbpassword")
db := beego.AppConfig.String("db")
//让beego也采用+8时区的时间
//Beego的ORM插入Mysql后,时区不一致的解决方案
//1、orm.RegisterDataBase("default", "mysql", "root:LPET6Plus@tcp(127.0.0.1:18283)/lpet6plusdb?charset=utf8&loc=Local")
//2、orm.RegisterDataBase("default", "mysql", "db_test:dbtestqwe321@tcp(127.0.0.1:3306)/db_test?charset=utf8&loc=Asia%2FShanghai")
//orm.DefaultTimeLoc, _ = time.LoadLocation("Asia/Shanghai")
//注册mysql Driver
orm.RegisterDriver("mysql", orm.DRMySQL)
//构造conn连接
//用户名:密码@tcp(url地址)/数据库
conn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + db + "?charset=utf8&loc=Local"
//注册数据库连接
orm.RegisterDataBase("default", "mysql", conn)
fmt.Printf("数据库连接成功!%s\n", conn)
}
func main() {
//简单的设置 Debug 为 true 打印查询的语句,可能存在性能问题,不建议使用在产品模式
orm.Debug = true
o := orm.NewOrm()
o.Using("default") // 默认使用 default,你可以指定为其他数据库
//启用Session
beego.BConfig.WebConfig.Session.SessionOn = true
beego.BConfig.WebConfig.Session.SessionName = "walletApisessionID"
var FilterUser = func(ctx *context.Context) {
noValidateMap := map[string]string{
"/Home/Login": "GET/POST",
"/Home/InitReg": "GET/POST",
"/Home/InitPass": "GET/POST",
"/Home/Reg": "POST",
"/Home/UpdatePwd": "POST",
}
fmt.Println("****", ctx.Request.RequestURI, ctx.Request.Method)
requireValidate := true
for k, v := range noValidateMap {
result := strings.Contains(v, ctx.Request.Method)
if ctx.Request.RequestURI == k && result {
requireValidate = false
break
}
}
if requireValidate {
u, ok := ctx.Input.Session(common.USER_INFO).(*model.User)
if !ok {
ctx.Redirect(302, "/")
}
//必须是管理员才能操作
if strings.Contains(ctx.Request.RequestURI, "/User/DeleteUser") || strings.Contains(ctx.Request.RequestURI, "/User/AddUser") {
if u.UserName != "admin" {
result := new(model.Result)
result.Status = 1
result.Msg = "无权限进行此操作!"
jsonBytes, _ := json.Marshal(result)
ctx.ResponseWriter.Write(jsonBytes)
return
}
}
}
}
beego.InsertFilter("/Home/*", beego.BeforeRouter, FilterUser)
beego.InsertFilter("/Category/*", beego.BeforeRouter, FilterUser)
beego.InsertFilter("/Goods/*", beego.BeforeRouter, FilterUser)
beego.InsertFilter("/Order/*", beego.BeforeRouter, FilterUser)
beego.InsertFilter("/User/*", beego.BeforeRouter, FilterUser)
beego.InsertFilter("/File/*", beego.BeforeRouter, FilterUser)
if beego.BConfig.RunMode == "dev" {
beego.BConfig.WebConfig.DirectoryIndex = true
beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
}
i18n.SetMessage("zh-CN", "conf/locale_zh-CN.ini")
i18n.SetMessage("en-US", "conf/locale_en-US.ini")
i18n.SetMessage("en-US", "conf/locale_zh-TW.ini")
beego.AddFuncMap("i18n", i18n.Tr)
runTask()
beego.Run()
}
func runTask() {
isRunning := false //是否正在运行
isPause := false
var blockNum int64
blockNum = model.QueryMaxBlockNum()
blockNum++
//1、新建任务
tk := toolbox.NewTask("myTask", "0/1 * * * * *", func() error {
if !isRunning {
isRunning = true
err := service.SyncBlockInfo(blockNum)
if err == nil {
blockNum++
}
isRunning = false
}
return nil
})
tk2 := toolbox.NewTask("myTask2", "0/1 * * * * *", func() error {
if !isPause {
service.SyncTransferStatus(func(err error) {
if err != nil {
fmt.Println(err.Error())
isPause = true
//休眠1秒中
time.Sleep(time.Duration(1) * time.Second)
isPause = false
}
})
}
return nil
})
//2、运行任务
err := tk.Run()
if err != nil {
fmt.Println(err)
}
err = tk2.Run()
if err != nil {
fmt.Println(err)
}
//3、对任务进行管理
toolbox.AddTask("myTask", tk)
toolbox.AddTask("myTask2", tk2)
toolbox.StartTask()
//4、信息任务
//time.Sleep(6 * time.Second)
//toolbox.StopTask()
}
/*
var UrlManager = func(ctx *context.Context) {
//数据库读取全部的url mapping数据
urlMapping := model.GetUrlMapping()
for baseurl,rule:=range urlMapping {
if baseurl == ctx.Request.RequestURI {
ctx.Input.RunController = rule.controller
ctx.Input.RunMethod = rule.method
break
}
}
}
beego.InsertFilter("/*",beego.BeforeRouter,UrlManager)
*/
|
package e2e_build_test
import (
"strings"
. "github.com/onsi/ginkgo/extensions/table"
"github.com/werf/werf/test/pkg/contruntime"
"github.com/werf/werf/test/pkg/thirdparty/contruntime/manifest"
"github.com/werf/werf/test/pkg/werf"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Build", func() {
DescribeTable("should succeed and produce expected image",
func(withLocalRepo bool, containerRuntime string) {
By("initializing")
setupEnv(withLocalRepo, containerRuntime)
contRuntime, err := contruntime.NewContainerRuntime(containerRuntime)
if err == contruntime.RuntimeUnavailError {
Skip(err.Error())
} else if err != nil {
Fail(err.Error())
}
By("state0: starting")
{
repoDirname := "repo0"
fixtureRelPath := "state0"
buildReportName := "report0.json"
By("state0: preparing test repo")
SuiteData.InitTestRepo(repoDirname, fixtureRelPath)
By("state0: building images")
werfProject := werf.NewProject(SuiteData.WerfBinPath, SuiteData.GetTestRepoPath(repoDirname))
buildOut, buildReport := werfProject.BuildWithReport(SuiteData.GetBuildReportPath(buildReportName))
Expect(buildOut).To(ContainSubstring("Building stage"))
Expect(buildOut).NotTo(ContainSubstring("Use cache image"))
By("state0: rebuilding same images")
Expect(werfProject.Build()).To(And(
ContainSubstring("Use cache image"),
Not(ContainSubstring("Building stage")),
))
By(`state0: getting built "dockerfile" image metadata`)
config := contRuntime.GetImageInspectConfig(buildReport.Images["dockerfile"].DockerImageName)
By("state0: checking built images metadata")
// FIXME(ilya-lesikov): CHANGED_ARG not changed on Native Buildah, needs investigation, then uncomment
// Expect(config.Env).To(ContainElement("COMPOSED_ENV=env-was_changed"))
// Expect(config.Labels).To(HaveKeyWithValue("COMPOSED_LABEL", "label-was_changed"))
Expect(config.Shell).To(ContainElements("/bin/sh", "-c"))
Expect(config.User).To(Equal("0:0"))
Expect(config.WorkingDir).To(Equal("/"))
Expect(config.Entrypoint).To(ContainElements("sh", "-ec"))
Expect(config.Cmd).To(ContainElement("tail -f /dev/null"))
Expect(config.Volumes).To(HaveKey("/persistent"))
Expect(config.OnBuild).To(ContainElement("RUN echo onbuild"))
Expect(config.StopSignal).To(Equal("SIGTERM"))
Expect(config.ExposedPorts).To(HaveKey(manifest.Schema2Port("80/tcp")))
Expect(config.Healthcheck.Test).To(ContainElements("CMD-SHELL", "echo healthcheck"))
By("state0: checking built images content")
contRuntime.ExpectCmdsToSucceed(
buildReport.Images["dockerfile"].DockerImageName,
"test -f /app/added/file2",
"test -f /app/copied/file1",
"test -f /app/copied/file2",
"echo 'file1content' | diff /app/added/file1 -",
"echo 'file2content' | diff /app/added/file2 -",
"echo 'file1content' | diff /app/copied/file1 -",
"echo 'file2content' | diff /app/copied/file2 -",
"test -f /helloworld.tgz",
"tar xOf /helloworld.tgz | grep 'Hello World!'",
"test -f /created-by-run",
"test -d /persistent/should-exist-in-volume",
)
}
By("state1: starting")
{
repoDirname := "repo0"
fixtureRelPath := "state1"
buildReportName := "report1.json"
By("state1: changing files in test repo")
SuiteData.UpdateTestRepo(repoDirname, fixtureRelPath)
By("state1: building images")
werfProject := werf.NewProject(SuiteData.WerfBinPath, SuiteData.GetTestRepoPath(repoDirname))
buildOut, buildReport := werfProject.BuildWithReport(SuiteData.GetBuildReportPath(buildReportName))
Expect(buildOut).To(ContainSubstring("Building stage"))
By("state1: rebuilding same images")
Expect(werfProject.Build()).To(And(
ContainSubstring("Use cache image"),
Not(ContainSubstring("Building stage")),
))
By(`state1: getting built "dockerfile" image metadata`)
// FIXME(ilya-lesikov): CHANGED_ARG not changed on Native Buildah, needs investigation, then uncomment
// config := contRuntime.GetImageInspectConfig(buildReport.Images["dockerfile"].DockerImageName)
By("state1: checking built images metadata")
// FIXME(ilya-lesikov): CHANGED_ARG not changed on Native Buildah, needs investigation, then uncomment
// Expect(config.Env).To(ContainElement("COMPOSED_ENV=env-was_changed-state1"))
// Expect(config.Labels).To(HaveKeyWithValue("COMPOSED_LABEL", "label-was_changed-state1"))
By("state1: checking built images content")
contRuntime.ExpectCmdsToSucceed(
buildReport.Images["dockerfile"].DockerImageName,
"test -f /app/added/file1",
"test -f /app/added/file3",
"test -f /app/copied/file1",
"test -f /app/copied/file3",
"! test -f /app/added/file2",
"! test -f /app/copied/file2",
"echo 'file1content-state1' | diff /app/added/file1 -",
"echo 'file3content-state1' | diff /app/added/file3 -",
"echo 'file1content-state1' | diff /app/copied/file1 -",
"echo 'file3content-state1' | diff /app/copied/file3 -",
"! test -f /helloworld.tgz",
"test -f /created-by-run-state1",
)
}
},
Entry("without repo using Docker", false, "docker"),
Entry("with local repo using Docker", true, "docker"),
Entry("with local repo using Native Rootless Buildah", true, "native-rootless-buildah"),
Entry("with local repo using Docker-With-Fuse Buildah", true, "docker-with-fuse-buildah"),
// TODO: uncomment when buildah allows building without --repo flag
// Entry("without repo using Native Rootless Buildah", false, contruntime.NativeRootlessBuildah),
// Entry("without repo using Docker-With-Fuse Buildah", false, contruntime.DockerWithFuseBuildah),
)
})
func setupEnv(withLocalRepo bool, containerRuntime string) {
switch containerRuntime {
case "docker":
if withLocalRepo {
SuiteData.Stubs.SetEnv("WERF_REPO", strings.Join([]string{SuiteData.RegistryLocalAddress, SuiteData.ProjectName}, "/"))
}
SuiteData.Stubs.UnsetEnv("WERF_CONTAINER_RUNTIME_BUILDAH")
case "native-rootless-buildah":
if withLocalRepo {
SuiteData.Stubs.SetEnv("WERF_REPO", strings.Join([]string{SuiteData.RegistryInternalAddress, SuiteData.ProjectName}, "/"))
}
SuiteData.Stubs.SetEnv("WERF_CONTAINER_RUNTIME_BUILDAH", "native-rootless")
case "docker-with-fuse-buildah":
if withLocalRepo {
SuiteData.Stubs.SetEnv("WERF_REPO", strings.Join([]string{SuiteData.RegistryInternalAddress, SuiteData.ProjectName}, "/"))
}
SuiteData.Stubs.SetEnv("WERF_CONTAINER_RUNTIME_BUILDAH", "docker-with-fuse")
default:
panic("unexpected containerRuntime")
}
if withLocalRepo {
SuiteData.Stubs.SetEnv("WERF_INSECURE_REGISTRY", "1")
SuiteData.Stubs.SetEnv("WERF_SKIP_TLS_VERIFY_REGISTRY", "1")
}
}
|
package models
import (
"database/sql"
"fmt"
"github.com/astaxie/beego/logs"
_ "github.com/go-sql-driver/mysql"
"log"
//"github.com/jmoiron/sqlx"
)
type MysqlDB struct{
BaseDB
MysqlConnector *sql.DB
}
func (db *MysqlDB) Connect() bool{
db.Host="118.190.207.134"
db.Port="3306"
db.UserName="rujiaowang_log"
db.UserPwd="Rujiaowang.net2018"
db.DBName="rujiaowang_log"
var err error
fmt.Println("我在这里测试",db.UserName+":"+db.UserPwd+"@tcp("+db.Host+":"+db.Port+")/"+db.DBName)
//db.Mysql,err=sql.Open("mysql",db.Name+":"+db.Pwd+"@tcp("+db.Host+":"+db.Port+")/"+db.DatabaseName)
db.MysqlConnector,err=sql.Open("mysql",db.UserName+":"+db.UserPwd+"@tcp("+db.Host+":"+db.Port+")/"+db.DBName)
if err!=nil{
log.Fatal(err)
return false
}
fmt.Println(db)
fmt.Println(db.UserName+":"+db.UserPwd+"@tcp("+db.Host+db.Port+")/"+db.DBName)
return true
}
func (db *MysqlDB) Close(){
db.Close()
}
func (db *MysqlDB) Query(sql string,args ...interface{}) (*sql.Rows,error){
rows,err:=db.MysqlConnector.Query(sql,args...)
return rows,err
}
func (db *MysqlDB) Query1(sql string,args ...interface{}) ([]map[string]interface{},error){
rows,err:=db.MysqlConnector.Query(sql,args...)
list:=rowsToMap(rows)
return list,err
}
func (db *MysqlDB) Exec(sql string,args ...interface{})(sql.Result,error){
result,err:=db.MysqlConnector.Exec(sql,args...)
if err!=nil{
logs.Error(err)
}
return result,err
}
//func rowsToMap(rows *sql.Rows) []interface{}{
// columns,_:=rows.Columns()
// coulmnsLength:=len(columns)
// fmt.Println("columns的值为:",columns)
// cache:=make([]interface{},coulmnsLength)
// fmt.Println("cache的值为:",cache)
// for i:=range cache{
// var p interface{}
// cache[i]=&p
// }
//
// for rows.Next(){
// err:=rows.Scan(cache...)
// if err!=nil{
// logs.Error(err)
// }
// fmt.Println("cache的值为:",cache)
// for i:=range cache{
// a:=cache[i]
// fmt.Println(a)
// }
//
// }
// return nil
//
//}
func rowsToMap(rows *sql.Rows) []map[string]interface{}{
columns,_:=rows.Columns()
coulmnsLength:=len(columns)
cache:=make([]interface{},coulmnsLength)
fmt.Println("columns的值为:",columns)
for index,_:=range cache{
var a interface{}
cache[index]=&a
}
var list []map[string]interface{}
for rows.Next(){
_ =rows.Scan(cache...)
item:=make(map[string]interface{})
for i,data:=range cache{
item[columns[i]]=*data.(*interface{})
}
list=append(list,item)
}
_=rows.Close()
return list
}
//func rowsToMap(rows *sql.Rows) []map[string]interface{}{
// columns,_:=rows.Columns()
// coulmnsLength:=len(columns)
// cache:=make([]interface{},coulmnsLength)
// fmt.Println("columns的值为:",columns)
// for index,_:=range cache{
// var a interface{}
// cache[index]=&a
// }
// var list []map[string]interface{}
// for rows.Next(){
// _ =rows.Scan(cache...)
// item:=make(map[string]interface{})
// for i,data:=range cache{
// item[columns[i]]=*data.(*interface{})
// fmt.Println(*data.(*interface{}))
// }
//
// list=append(list,item)
// }
// _=rows.Close()
// return list
//} |
package v1
import (
u "MS/apiHelpers"
vserv "MS/services/api"
"encoding/json"
"github.com/gin-gonic/gin"
)
func UserList(c *gin.Context) {
var userService vserv.UserService
err := json.NewDecoder(c.Request.Body).Decode(&userService.User)
if err != nil {
u.Respond(c.Writer, u.Message(1, "Invalid request"))
return
}
//call service
resp := userService.UserList()
//return response using api helper
u.Respond(c.Writer, resp)
}
|
package win
import (
"syscall"
"unsafe"
)
var (
// Library
libgdi32 = syscall.NewLazyDLL("gdi32.dll")
//libmsimg32 = syscall.NewLazyDLL("msimg32.dll")
// Functions
procCreateDC = libgdi32.NewProc("CreateDCW")
procCreateCompatibleDC = libgdi32.NewProc("CreateCompatibleDC")
procDeleteDC = libgdi32.NewProc("DeleteDC")
procGetObject = libgdi32.NewProc("GetObjectW")
procSelectObject = libgdi32.NewProc("SelectObject")
procDeleteObject = libgdi32.NewProc("DeleteObject")
procCreateBitmap = libgdi32.NewProc("CreateBitmap")
procCreateCompatibleBitmap = libgdi32.NewProc("CreateCompatibleBitmap")
procGetStockObject = libgdi32.NewProc("GetStockObject")
procCreatePen = libgdi32.NewProc("CreatePen")
procExtCreatePen = libgdi32.NewProc("ExtCreatePen")
procCreateSolidBrush = libgdi32.NewProc("CreateSolidBrush")
procCreateBrushIndirect = libgdi32.NewProc("CreateBrushIndirect")
procGetDeviceCaps = libgdi32.NewProc("GetDeviceCaps")
procSetBkMode = libgdi32.NewProc("SetBkMode")
procSetStretchBltMode = libgdi32.NewProc("SetStretchBltMode")
procSetBrushOrgEx = libgdi32.NewProc("SetBrushOrgEx")
procMoveToEx = libgdi32.NewProc("MoveToEx")
procLineTo = libgdi32.NewProc("LineTo")
procRectangle = libgdi32.NewProc("Rectangle")
procEllipse = libgdi32.NewProc("Ellipse")
)
func CreateDC(lpszDriver, lpszDevice, lpszOutput *uint16, lpInitData *DEVMODE) HDC {
ret, _, _ := procCreateDC.Call(
uintptr(unsafe.Pointer(lpszDriver)),
uintptr(unsafe.Pointer(lpszDevice)),
uintptr(unsafe.Pointer(lpszOutput)),
uintptr(unsafe.Pointer(lpInitData)))
return HDC(ret)
}
func CreateCompatibleDC(hdc HDC) HDC {
ret, _, _ := procCreateCompatibleDC.Call(
uintptr(hdc))
if ret == 0 {
panic("Create compatible DC failed")
}
return HDC(ret)
}
func DeleteDC(hdc HDC) bool {
ret, _, _ := procDeleteDC.Call(
uintptr(hdc))
return ret != 0
}
func GetObject(hgdiobj HGDIOBJ, cbBuffer uintptr, lpvObject unsafe.Pointer) int32 {
ret, _, _ := procGetObject.Call(
uintptr(hgdiobj),
uintptr(cbBuffer),
uintptr(lpvObject))
return int32(ret)
}
func SelectObject(hdc HDC, hgdiobj HGDIOBJ) HGDIOBJ {
ret, _, _ := procSelectObject.Call(
uintptr(hdc),
uintptr(hgdiobj))
if ret == 0 {
panic("SelectObject failed")
}
return HGDIOBJ(ret)
}
func DeleteObject(hgdiobj HGDIOBJ) bool {
ret, _, _ := procDeleteObject.Call(
uintptr(hgdiobj))
return ret != 0
}
func CreateBitmap(nWidth, nHeight int32, cPlanes, cBitsPerPel uint32, lpvBits unsafe.Pointer) HBITMAP {
ret, _, _ := procCreateBitmap.Call(
uintptr(nWidth),
uintptr(nHeight),
uintptr(cPlanes),
uintptr(cBitsPerPel),
uintptr(lpvBits))
return HBITMAP(ret)
}
func CreateCompatibleBitmap(hdc HDC, width, height uint32) HBITMAP {
ret, _, _ := procCreateCompatibleBitmap.Call(
uintptr(hdc),
uintptr(width),
uintptr(height))
return HBITMAP(ret)
}
// https://msdn.microsoft.com/zh-cn/library/windows/desktop/dd144925(d=printer,v=vs.85).aspx
func GetStockObject(fnObject int32) HGDIOBJ {
ret, _, _ := procGetStockObject.Call(
uintptr(fnObject))
return HGDIOBJ(ret)
}
func CreatePen(PenStyle, Width int32, color COLORREF) HPEN {
ret, _, _ := procCreatePen.Call(
uintptr(PenStyle),
uintptr(Width),
uintptr(color))
return HPEN(ret)
}
func ExtCreatePen(dwPenStyle, dwWidth uint32, lplb *LOGBRUSH, dwStyleCount uint32, lpStyle *uint32) HPEN {
ret, _, _ := procExtCreatePen.Call(
uintptr(dwPenStyle),
uintptr(dwWidth),
uintptr(unsafe.Pointer(lplb)),
uintptr(dwStyleCount),
uintptr(unsafe.Pointer(lpStyle)))
return HPEN(ret)
}
func CreateSolidBrush(color COLORREF) HBRUSH {
ret, _, _ := procCreateSolidBrush.Call(
uintptr(color))
return HBRUSH(ret)
}
func CreateBrushIndirect(lplb *LOGBRUSH) HBRUSH {
ret, _, _ := procCreateBrushIndirect.Call(
uintptr(unsafe.Pointer(lplb)))
return HBRUSH(ret)
}
func GetDeviceCaps(hdc HDC, index int32) int32 {
ret, _, _ := procGetDeviceCaps.Call(
uintptr(hdc),
uintptr(index))
return int32(ret)
}
func SetBkMode(hdc HDC, iBkMode int32) int32 {
ret, _, _ := procSetBkMode.Call(
uintptr(hdc),
uintptr(iBkMode))
if ret == 0 {
panic("SetBkMode failed")
}
return int32(ret)
}
func SetStretchBltMode(hdc HDC, iStretchMode int32) int32 {
ret, _, _ := procSetStretchBltMode.Call(
uintptr(hdc),
uintptr(iStretchMode))
return int32(ret)
}
func SetBrushOrgEx(hdc HDC, nXOrg, nYOrg int32, lppt *POINT) bool {
ret, _, _ := procSetBrushOrgEx.Call(
uintptr(hdc),
uintptr(nXOrg),
uintptr(nYOrg),
uintptr(unsafe.Pointer(lppt)))
return ret != 0
}
func MoveToEx(hdc HDC, x, y int32, lpPoint *POINT) bool {
ret, _, _ := procMoveToEx.Call(
uintptr(hdc),
uintptr(x),
uintptr(y),
uintptr(unsafe.Pointer(lpPoint)))
return ret != 0
}
func LineTo(hdc HDC, X, Y int32) bool {
ret, _, _ := procLineTo.Call(
uintptr(hdc),
uintptr(X),
uintptr(Y))
return ret != 0
}
func Rectangle(hdc HDC, LeftRect, TopRect, RightRect, BottomRect int32) bool {
ret, _, _ := procRectangle.Call(
uintptr(hdc),
uintptr(LeftRect),
uintptr(TopRect),
uintptr(RightRect),
uintptr(BottomRect))
return ret != 0
}
func Ellipse(hdc HDC, nLeftRect, nTopRect, nRightRect, nBottomRect int32) bool {
ret, _, _ := procEllipse.Call(
uintptr(hdc),
uintptr(nLeftRect),
uintptr(nTopRect),
uintptr(nRightRect),
uintptr(nBottomRect))
return ret != 0
}
|
package v1beta1
import (
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/config"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/util"
next "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/v1beta2"
"github.com/devspace-cloud/devspace/pkg/util/log"
)
// Upgrade upgrades the config
func (c *Config) Upgrade(log log.Logger) (config.Config, error) {
nextConfig := &next.Config{}
err := util.Convert(c, nextConfig)
if err != nil {
return nil, err
}
// Convert images insecure, dockerfilepath, contextpath, skipPush, build options
if c.Images != nil {
for imageConfigName, imageConfig := range *c.Images {
newImageConfig := (*nextConfig.Images)[imageConfigName]
if imageConfig.Build != nil && imageConfig.Build.Dockerfile != nil {
newImageConfig.Dockerfile = imageConfig.Build.Dockerfile
}
if imageConfig.Build != nil && imageConfig.Build.Context != nil {
newImageConfig.Context = imageConfig.Build.Context
}
if imageConfig.Insecure != nil {
if newImageConfig.Build == nil {
newImageConfig.Build = &next.BuildConfig{}
}
if newImageConfig.Build.Kaniko == nil {
newImageConfig.Build.Kaniko = &next.KanikoConfig{}
}
newImageConfig.Build.Kaniko.Insecure = imageConfig.Insecure
}
if imageConfig.SkipPush != nil {
if newImageConfig.Build == nil {
newImageConfig.Build = &next.BuildConfig{}
}
if newImageConfig.Build.Docker == nil {
newImageConfig.Build.Docker = &next.DockerConfig{}
}
newImageConfig.Build.Docker.SkipPush = imageConfig.SkipPush
}
if imageConfig.Build != nil && imageConfig.Build.Options != nil {
if newImageConfig.Build == nil {
newImageConfig.Build = &next.BuildConfig{}
}
if newImageConfig.Build.Kaniko != nil {
newImageConfig.Build.Kaniko.Options = &next.BuildOptions{
Target: imageConfig.Build.Options.Target,
Network: imageConfig.Build.Options.Network,
BuildArgs: imageConfig.Build.Options.BuildArgs,
}
} else {
if newImageConfig.Build.Docker == nil {
newImageConfig.Build.Docker = &next.DockerConfig{}
}
newImageConfig.Build.Docker.Options = &next.BuildOptions{
Target: imageConfig.Build.Options.Target,
Network: imageConfig.Build.Options.Network,
BuildArgs: imageConfig.Build.Options.BuildArgs,
}
}
}
}
}
return nextConfig, nil
}
// UpgradeVarPaths upgrades the config
func (c *Config) UpgradeVarPaths(varPaths map[string]string, log log.Logger) error {
return nil
}
|
package ifth
import (
"fmt"
"log"
"testing"
)
func InitTest() {
InitSlotGenerator(4)
_, err := InitMgo("localhost")
if err != nil {
log.Fatal(err)
}
log.Println("init ok")
}
func TestNewUrl(t *testing.T) {
InitTest()
url := NewUrl("http://test.tickpay.org", false)
log.Println(url)
}
func BenchmarkNewUrl(b *testing.B) {
InitTest()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_ = NewUrl("http://test.tickpay.org", false)
}
})
}
func TestFindUrls(t *testing.T) {
InitTest()
urls, err := FindHottestUrls(3)
if err != nil {
t.Fatal(err)
}
Dump(urls)
urls, err = FindNewestUrls(3)
if err != nil {
t.Fatal(err)
}
Dump(urls)
}
func Dump(urls []Url) {
for _, url := range urls {
fmt.Printf("%s %d %s\n\n", url.Slot, url.Count, url.CreatedTime)
}
}
|
package configuration
import (
"fmt"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/authelia/authelia/v4/internal/utils"
)
func TestShouldGenerateConfiguration(t *testing.T) {
dir := t.TempDir()
cfg := filepath.Join(dir, "config.yml")
created, err := EnsureConfigurationExists(cfg)
assert.NoError(t, err)
assert.True(t, created)
_, err = os.Stat(cfg)
assert.NoError(t, err)
}
func TestNotShouldGenerateConfigurationIfExists(t *testing.T) {
dir := t.TempDir()
cfg := filepath.Join(dir, "config.yml")
created, err := EnsureConfigurationExists(cfg)
assert.NoError(t, err)
assert.True(t, created)
created, err = EnsureConfigurationExists(cfg)
assert.NoError(t, err)
assert.False(t, created)
_, err = os.Stat(cfg)
assert.NoError(t, err)
}
func TestShouldNotGenerateConfigurationOnFSAccessDenied(t *testing.T) {
if runtime.GOOS == constWindows {
t.Skip("skipping test due to being on windows")
}
dir := t.TempDir()
assert.NoError(t, os.Mkdir(filepath.Join(dir, "zero"), 0000))
cfg := filepath.Join(dir, "zero", "config.yml")
created, err := EnsureConfigurationExists(cfg)
assert.EqualError(t, err, fmt.Sprintf("error occurred generating configuration: stat %s: permission denied", cfg))
assert.False(t, created)
}
func TestShouldNotGenerateConfiguration(t *testing.T) {
dir := t.TempDir()
cfg := filepath.Join(dir, "..", "not-a-dir", "config.yml")
created, err := EnsureConfigurationExists(cfg)
expectedErr := fmt.Sprintf(utils.GetExpectedErrTxt("pathnotfound"), cfg)
assert.EqualError(t, err, fmt.Sprintf(errFmtGenerateConfiguration, expectedErr))
assert.False(t, created)
}
|
package main
import (
"encoding/csv"
"errors"
"io"
"os"
"strings"
)
func CalculateCopiesFromCsv(path string, applicationID string) (copies int, err error) {
input, err := os.Open(path)
if err != nil {
return
}
defer input.Close()
reader := csv.NewReader(input)
firstRecord, err := reader.Read()
if err != nil {
return
}
err = checkFormat(firstRecord)
if err != nil {
return
}
users := make(map[string]User)
for {
record, err := reader.Read()
if err != nil {
break
}
if record[2] != applicationID {
continue
}
if hasUser(users, record[1]) {
if users[record[1]].HasComputer(record[0]) {
continue
}
copies -= users[record[1]].MinimalCopies()
users[record[1]].AddComputer(record[0], strings.ToUpper(record[3]))
copies += users[record[1]].MinimalCopies()
} else {
users[record[1]] = User{
ID: record[1],
Computers: make(map[string]Computer),
}
users[record[1]].AddComputer(record[0], strings.ToUpper(record[3]))
copies += users[record[1]].MinimalCopies()
}
}
if err != io.EOF {
return
} else {
err = nil
}
return
}
func checkFormat(firstRecord []string) (err error) {
if len(firstRecord) < 5 ||
firstRecord[0] != "ComputerID" ||
firstRecord[1] != "UserID" ||
firstRecord[2] != "ApplicationID" ||
firstRecord[3] != "ComputerType" ||
firstRecord[4] != "Comment" {
err = errors.New("file not supported")
}
return
}
func hasUser(users map[string]User, id string) (exsit bool) {
_, exsit = users[id]
return
}
|
package capsule
import (
"fmt"
"sync"
"github.com/go-redis/redis/v8"
"github.com/spf13/viper"
)
var redisClients sync.Map
//RedisClient new redis client instance
func RedisClient(args ...string) (client *redis.Client) {
name := "default"
if len(args) > 0 {
name = args[0]
}
connection, ok := redisClients.Load(name)
if ok {
client = connection.(*redis.Client)
return
}
client = newRedisClient(name)
redisClients.Store(name, client)
return client
}
//newRedisClient create a redis client
func newRedisClient(name string) *redis.Client {
prefix := fmt.Sprintf("redis.connections.%s", name)
options := getRedisOptions(prefix)
return redis.NewClient(options)
}
//getRedisOptions get redis client option by configure
func getRedisOptions(prefix string) *redis.Options {
host := viper.GetString(fmt.Sprintf("%s.host", prefix))
port := viper.GetString(fmt.Sprintf("%s.port", prefix))
addr := fmt.Sprintf("%s:%s", host, port)
password := viper.GetString(fmt.Sprintf("%s.password", prefix))
username := viper.GetString(fmt.Sprintf("%s.username", prefix))
options := &redis.Options{
Addr: addr,
DB: viper.GetInt(fmt.Sprintf("%s.db", prefix)),
}
if password != "" {
options.Password = password
}
if username != "" {
options.Username = username
}
return options
}
|
package main
import (
"fmt"
"os"
"strings"
"github.com/cloudfoundry/cli/plugin"
"github.com/krujos/usagereport-plugin/apihelper"
)
// ExportStructureCmd is this plugin
type ExportStructureCmd struct {
apiHelper apihelper.CFAPIHelper
cli plugin.CliConnection
}
// Run runs the plugin
func (cmd *ExportStructureCmd) Run(cliConnection plugin.CliConnection, args []string) {
cmd.apiHelper = &apihelper.APIHelper{}
cmd.cli = cliConnection
if args[0] == "export-structure" {
cmd.ExportStructureCmd(args)
}
}
// ExportStructureCmd doer
func (cmd *ExportStructureCmd) ExportStructureCmd(args []string) {
orgs, err := cmd.cli.GetOrgs()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// foreach org
for _, org := range orgs {
fmt.Println("cf create-org " + org.Name)
// get org users
orgUsers, err := cmd.cli.GetOrgUsers(org.Name)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, orgUser := range orgUsers {
if orgUser.Username == "admin" {
continue
}
for _, role := range orgUser.Roles {
fmt.Println("cf set-org-role " + orgUser.Username + " " + org.Name + " " + strings.TrimLeft(role, "Role"))
}
}
// foreach space
spaces, err := cmd.apiHelper.GetOrgSpaces(cmd.cli, "/v2/organizations/"+org.Guid+"/spaces")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, space := range spaces {
fmt.Println("cf create-space -o " + org.Name + " " + space.Name)
cmd.exportSpaceUsers(org.Name, space.Name)
}
}
}
func (cmd *ExportStructureCmd) exportSpaceUsers(org string, space string) {
spaceUsers, err := cmd.cli.GetSpaceUsers(org, space)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, spaceUser := range spaceUsers {
if spaceUser.Username == "admin" {
continue
}
for _, role := range spaceUser.Roles {
fmt.Println("cf set-space-role " + spaceUser.Username + " " + org + " " + space + " " + strings.TrimLeft(role, "Role"))
}
}
}
// GetMetadata returns metatada
func (cmd *ExportStructureCmd) GetMetadata() plugin.PluginMetadata {
return plugin.PluginMetadata{
Name: "export-structure",
Version: plugin.VersionType{
Major: 1,
Minor: 0,
Build: 0,
},
MinCliVersion: plugin.VersionType{
Major: 6,
Minor: 7,
Build: 0,
},
Commands: []plugin.Command{
{
Name: "export-structure",
HelpText: "Generates a series of CF CLI commands to recreate orgs, spaces, users and roles",
UsageDetails: plugin.Usage{
Usage: "cf export-structure",
},
},
},
}
}
func main() {
plugin.Start(new(ExportStructureCmd))
}
|
package bencode
import (
"bytes"
"encoding"
"fmt"
"io"
"reflect"
"sort"
)
// Marshal returns the bencode of v.
func Marshal(v interface{}) ([]byte, error) {
buf := bytes.Buffer{}
e := NewEncoder(&buf)
err := e.Encode(v)
return buf.Bytes(), err
}
// Marshaler is the interface implemented by types
// that can marshal themselves into valid bencode.
type Marshaler interface {
MarshalBencode() ([]byte, error)
}
// An Encoder writes bencoded objects to an output stream.
type Encoder struct {
w io.Writer
}
// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{w}
}
//Encode writes the bencoded data of val to its output stream.
//If an encountered value implements the Marshaler interface,
//its MarshalBencode method is called to produce the bencode output for this value.
//If no MarshalBencode method is present but the value implements encoding.TextMarshaler instead,
//its MarshalText method is called, which encodes the result as a bencode string.
//See the documentation for Decode about the conversion of Go values to
//bencoded data.
func (e *Encoder) Encode(val interface{}) error {
return e.encode(reflect.ValueOf(val))
}
func (e *Encoder) encode(val reflect.Value) error {
v := val
if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
v = v.Addr()
}
for {
flag := true
switch v.Kind() {
case reflect.Ptr, reflect.Interface:
flag = false
if v.IsNil() {
return nil
}
}
iface := v.Interface()
switch vv := iface.(type) {
case Marshaler:
data, err := vv.MarshalBencode()
if err != nil {
return err
}
_, err = e.w.Write(data)
if err != nil {
return err
}
return nil
case encoding.TextMarshaler:
data, err := vv.MarshalText()
if err != nil {
return err
}
_, err = fmt.Fprintf(e.w, "%d:%s", len(data), data)
if err != nil {
return err
}
return nil
}
if flag {
break
}
v = v.Elem()
}
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
_, err := fmt.Fprintf(e.w, "i%de", v.Int())
return err
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
_, err := fmt.Fprintf(e.w, "i%de", v.Uint())
return err
case reflect.Bool:
i := 0
if v.Bool() {
i = 1
}
_, err := fmt.Fprintf(e.w, "i%de", i)
return err
case reflect.String:
s := v.String()
_, err := fmt.Fprintf(e.w, "%d:%s", len(s), s)
return err
case reflect.Slice, reflect.Array:
return e.encodeArrayOrSlice(v)
case reflect.Map:
return e.encodeMap(v)
case reflect.Struct:
return e.encodeStruct(v)
}
return &UnsupportedTypeError{v.Type()}
}
func (e *Encoder) encodeArrayOrSlice(val reflect.Value) error {
// handle byte slices like strings
if byteSlice, ok := val.Interface().([]byte); ok {
_, err := fmt.Fprintf(e.w, "%d:", len(byteSlice))
if err == nil {
_, err = e.w.Write(byteSlice)
}
return err
}
if _, err := fmt.Fprint(e.w, "l"); err != nil {
return err
}
for i := 0; i < val.Len(); i++ {
if err := e.encode(val.Index(i)); err != nil {
return err
}
}
_, err := fmt.Fprint(e.w, "e")
return err
}
func (e *Encoder) encodeMap(val reflect.Value) error {
if _, err := fmt.Fprint(e.w, "d"); err != nil {
return err
}
var keys sortValues = val.MapKeys()
sort.Sort(keys)
for _, key := range keys {
mval := val.MapIndex(key)
mval = getDirectValue(mval)
if !mval.IsValid() {
continue
}
err := e.encode(key)
if err != nil {
return err
}
err = e.encode(mval)
if err != nil {
return err
}
}
_, err := fmt.Fprint(e.w, "e")
return err
}
func (e *Encoder) encodeStruct(val reflect.Value) error {
if _, err := fmt.Fprint(e.w, "d"); err != nil {
return err
}
dict := make(dictionary, 0, val.NumField())
dict, err := readStruct(dict, val)
if err != nil {
return err
}
sort.Sort(dict)
for _, entry := range dict {
_, err := fmt.Fprintf(e.w, "%d:%s", len(entry.key), entry.key)
if err != nil {
return err
}
err = e.encode(entry.value)
if err != nil {
return err
}
}
if _, err := fmt.Fprint(e.w, "e"); err != nil {
return err
}
return nil
}
func readStruct(dict dictionary, v reflect.Value) (dictionary, error) {
t := v.Type()
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.PkgPath != "" {
continue
}
_, ok := f.Tag.Lookup("bencode")
if f.Anonymous && !ok {
val := v.FieldByIndex(f.Index)
val = getDirectValue(val)
if !val.IsValid() {
continue
}
var err error
dict, err = readStruct(dict, val)
if err != nil {
return dict, err
}
}
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
key := f.Name
if f.PkgPath != "" {
continue
}
tag, ok := f.Tag.Lookup("bencode")
if f.Anonymous && !ok {
continue
}
val := v.FieldByIndex(f.Index)
isEmpty := isEmptyValue(val)
val = getDirectValue(val)
if !val.IsValid() {
continue
}
if !ok {
dict = append(dict, pair{key, val})
continue
}
name, opts := parseTag(tag)
if opts.Ignored() {
continue
}
if opts.OmitEmpty() && isEmpty {
continue
}
if name != "" {
dict = append(dict, pair{name, val})
} else {
dict = append(dict, pair{key, val})
}
}
return dict, nil
}
type sortValues []reflect.Value
func (p sortValues) Len() int { return len(p) }
func (p sortValues) Less(i, j int) bool { return p[i].String() < p[j].String() }
func (p sortValues) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func getDirectValue(val reflect.Value) reflect.Value {
v := val
for {
k := v.Kind()
switch k {
case reflect.Interface, reflect.Ptr:
if !v.IsNil() {
v = v.Elem()
continue
}
return reflect.Value{}
default:
return v
}
}
}
type pair struct {
key string
value reflect.Value
}
type dictionary []pair
func (d dictionary) Len() int { return len(d) }
func (d dictionary) Less(i, j int) bool { return d[i].key < d[j].key }
func (d dictionary) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
}
return false
}
|
package problems
// BFS
// Runtime: 56 ms
// Memory Usage: 6.5 MB
func canReach(arr []int, start int) bool {
var visited = make(map[int]bool)
var queue = make([]int, 0, len(arr))
queue = append(queue, start)
visited[start] = true
for len(queue) != 0 {
curr := queue[0]
if arr[curr] == 0 {
return true
}
queue = queue[1:]
for _, next := range []int{
curr + arr[curr],
curr - arr[curr],
} {
if next < 0 || next > len(arr)-1 {
continue
}
if visited[next] {
continue
}
visited[next] = true
queue = append(queue, next)
}
}
return false
}
// DFS
// Runtime: 56 ms
// Memory Usage: 6.7 MB
func canReach1(arr []int, start int) bool {
return dfs(arr, start, make(map[int]bool))
}
func dfs(arr []int, curr int, visited map[int]bool) bool {
if curr < 0 || curr > len(arr)-1 {
return false
}
if visited[curr] {
return false
}
visited[curr] = true
return arr[curr] == 0 ||
dfs(arr, curr+arr[curr], visited) ||
dfs(arr, curr-arr[curr], visited)
}
// DFS
// Runtime: 60 ms
// Memory Usage: 6.7 MB
func canReach2(arr []int, curr int) bool {
return dfs1(arr, curr)
}
func dfs1(arr []int, curr int) bool {
if curr < 0 || curr > len(arr)-1 || arr[curr] < 0 {
return false
}
arr[curr] = -arr[curr]
return arr[curr] == 0 ||
dfs1(arr, curr+arr[curr]) ||
dfs1(arr, curr-arr[curr])
}
|
package f
import (
"fmt"
)
type SecretValueGetter func(name string) string
func getKeyVault(name string) string {
return fmt.Sprintf("Real: KeyVault Call %s", name)
}
func GetSecretValue(getter SecretValueGetter, name string) string {
return getter(name)
}
// Usage Sample
func main() {
fmt.Printf(GetSecretValue(getKeyVault, "SomeName"))
fmt.Println()
}
|
package graphql
import (
"github.com/graphql-go/graphql/gqlerrors"
)
// type Schema interface{}
// Result has the response, errors and extensions from the resolved schema
type Result struct {
Data interface{} `json:"data"`
Errors []gqlerrors.FormattedError `json:"errors,omitempty"`
Extensions map[string]interface{} `json:"extensions,omitempty"`
}
// HasErrors just a simple function to help you decide if the result has errors or not
func (r *Result) HasErrors() bool {
return len(r.Errors) > 0
}
|
//////////////////////////////////////////////////////////////////////
// config.go
//////////////////////////////////////////////////////////////////////
package accounts
import (
"time"
)
const (
CHARSET = "utf8mb4"
TABLE_NAME_ACCOUNTS = "accounts"
TABLE_NAME_ACCOUNT_META = "account_meta"
TABLE_NAME_ACCOUNT_IMAGES = "account_images"
TABLE_NAME_ACCOUNT_IMAGE_MAP = "account_image_map"
TABLE_NAME_ACCOUNT_COMPANIES = "account_companies"
TABLE_NAME_ACCOUNT_COMPANY_MAP = "account_company_map"
TABLE_NAME_ACCOUNT_COMPANY_IMAGES = "account_company_images"
TABLE_NAME_ACCOUNT_COMPANY_IMAGE_MAP = "account_company_image_map"
COL_ACCOUNTS_ID = "id"
COL_ACCOUNTS_FIRST_NAME = "first_name"
COL_ACCOUNTS_LAST_NAME = "last_name"
COL_ACCOUNTS_MIDDLE_NAME = "middle_name"
COL_ACCOUNTS_NAME = "name"
COL_ACCOUNTS_NICK_NAME = "nick_name"
COL_ACCOUNTS_NATIONALITY = "nationality"
COL_ACCOUNTS_EMAIL = "email"
COL_ACCOUNTS_PHONE_NUMBER = "phone_number"
COL_ACCOUNTS_PASSWORD = "password"
COL_ACCOUNTS_STATUS = "status"
COL_ACCOUNTS_PUBLISHABLE_TOKEN = "publishable_token"
COL_ACCOUNTS_SECRET_TOKEN = "secret_token"
COL_ACCOUNTS_ADDRESS_COUNTRY = "address_country"
COL_ACCOUNTS_ADDRESS_CITY = "address_city"
COL_ACCOUNTS_ADDRESS_ZIP_CODE = "address_zip_code"
COL_ACCOUNTS_ADDRESS = "address"
COL_ACCOUNTS_ADDRESS_OPTION = "address_option"
COL_ACCOUNTS_CREATED_AT = "created_at"
COL_ACCOUNTS_UPDATED_AT = "updated_at"
COL_ACCOUNT_META_KEY = "meta_key"
COL_ACCOUNT_META_VALUE = "meta_value"
COL_ACCOUNT_IMAGES_ID = "image_id"
COL_ACCOUNT_IMAGES_NAME = "image_name"
COL_ACCOUNT_IMAGES_SIZE = "image_size"
COL_ACCOUNT_IMAGES_PATH = "image_path"
COL_ACCOUNT_IMAGES_URI = "image_uri"
COL_ACCOUNT_IMAGES_ALT = "image_alt"
COL_ACCOUNT_IMAGES_TYPE = "image_type"
COL_ACCOUNT_IMAGES_LINK = "image_link"
COL_ACCOUNT_IMAGES_MIME_TYPE = "image_mime_type"
COL_ACCOUNT_IMAGES_DATE = "image_date"
COL_ACCOUNT_COMPANIES_ID = "company_id"
COL_ACCOUNT_COMPANIES_NAME = "company_name"
COL_ACCOUNT_COMPANIES_NAME_EN = "company_name_en"
COL_ACCOUNT_COMPANIES_FOUNDATION_DATE = "company_foundation_date"
COL_ACCOUNT_COMPANIES_ADDRESS_COUNTRY = "company_address_country"
COL_ACCOUNT_COMPANIES_ADDRESS_CITY = "company_address_city"
COL_ACCOUNT_COMPANIES_ADDRESS_ZIP_CODE = "company_address_zip_code"
COL_ACCOUNT_COMPANIES_ADDRESS = "company_address"
COL_ACCOUNT_COMPANIES_ADDRESS_OPTION = "company_address_option"
COL_ACCOUNT_COMPANIES_INDUSTRY = "company_industry"
COL_ACCOUNT_COMPANIES_EMAIL = "company_email"
COL_ACCOUNT_COMPANIES_PHONE_NUMBER = "company_phone_number"
COL_ACCOUNT_COMPANIES_WEBSITE = "company_website"
COL_ACCOUNT_COMPANIES_CREATED_AT = "company_created_at"
COL_ACCOUNT_COMPANIES_UPDATED_AT = "company_updated_at"
COL_ACCOUNT_COMPANY_IMAGES_ID = "company_image_id"
COL_ACCOUNT_COMPANY_IMAGES_NAME = "company_image_name"
COL_ACCOUNT_COMPANY_IMAGES_SIZE = "company_image_size"
COL_ACCOUNT_COMPANY_IMAGES_PATH = "company_image_path"
COL_ACCOUNT_COMPANY_IMAGES_URI = "company_image_uri"
COL_ACCOUNT_COMPANY_IMAGES_ALT = "company_image_alt"
COL_ACCOUNT_COMPANY_IMAGES_TYPE = "company_image_type"
COL_ACCOUNT_COMPANY_IMAGES_LINK = "company_image_link"
COL_ACCOUNT_COMPANY_IMAGES_MIME_TYPE = "company_image_mime_type"
COL_ACCOUNT_COMPANY_IMAGES_DATE = "company_image_date"
)
type AccountsColumns struct {
ID string
FirstName string
LastName string
MiddleName string
Name string
NickName string
Nationality string
Email string
PhoneNumber string
Password string
Status string
PublishableToken string
SecretToken string
AddressCountry string
AddressCity string
AddressZipCode string
Address string
AddressOption string
CreatedAt time.Time
UpdatedAt time.Time
}
type SelectAccountsColumns struct {
ID []string
FirstName []string
LastName []string
MiddleName []string
Name []string
NickName []string
Nationality []string
Email []string
PhoneNumber []string
Password []string
Status []string
PublishableToken []string
SecretToken []string
AddressCountry []string
AddressCity []string
AddressZipCode []string
Address []string
AddressOption []string
CreatedAtBefore time.Time
CreatedAtAfter time.Time
UpdatedAtBefore time.Time
UpdatedAtAfter time.Time
}
type UpdateAccountsColumns struct {
Values AccountsColumns
Where AccountsColumns
}
type AccountMetaColumns struct {
AccountID string
MetaKey string
MetaValue string
}
type SelectAccountMetaColumns struct {
AccountID []string
MetaKey []string
MetaValue []string
}
type UpdateAccountMetaColumns struct {
Values AccountMetaColumns
Where AccountMetaColumns
}
type AccountImagesColumns struct {
ID string
Name string
Size string
Path string
URI string
Alt string
Type string
Link string
MimeType string
Date time.Time
}
type SelectAccountImagesColumns struct {
ID []string
Name []string
SizeOrMore string
SizeOrLess string
Path []string
URI []string
Alt []string
Type []string
Link []string
MimeType []string
DateBefore time.Time
DateAfter time.Time
}
type UpdateAccountImagesColumns struct {
Values AccountImagesColumns
Where AccountImagesColumns
}
type AccountImageMapColumns struct {
AccountID string
ImageID string
}
type SelectAccountImageMapColumns struct {
AccountID []string
ImageID []string
}
type UpdateAccountImageMapColumns struct {
Values AccountImageMapColumns
Where AccountImageMapColumns
}
type AccountCompaniesColumns struct {
ID string
Name string
NameEn string
FoundationDate time.Time
AddressCountry string
AddressCity string
AddressZipCode string
Address string
AddressOption string
Industry string
Email string
PhoneNumber string
Website string
CreatedAt time.Time
UpdatedAt time.Time
}
type SelectAccountCompaniesColumns struct {
ID []string
Name []string
NameEn []string
FoundationDate time.Time
AddressCountry []string
AddressCity []string
AddressZipCode []string
Address []string
AddressOption []string
Industry []string
Email []string
PhoneNumber []string
Website []string
CreatedAtBefore time.Time
CreatedAtAfter time.Time
UpdatedAtBefore time.Time
UpdatedAtAfter time.Time
}
type UpdateAccountCompaniesColumns struct {
Values AccountCompaniesColumns
Where AccountCompaniesColumns
}
type AccountCompanyMapColumns struct {
AccountID string
CompanyID string
}
type SelectAccountCompanyMapColumns struct {
AccountID []string
CompanyID []string
}
type UpdateAccountCompanyMapColumns struct {
Values AccountCompanyMapColumns
Where AccountCompanyMapColumns
}
type AccountCompanyImagesColumns struct {
ID string
Name string
Size string
Path string
URI string
Alt string
Type string
Link string
MimeType string
Date time.Time
}
type SelectAccountCompanyImagesColumns struct {
ID []string
Name []string
SizeOrMore string
SizeOrLess string
Path []string
URI []string
Alt []string
Type []string
Link []string
MimeType []string
DateBefore time.Time
DateAfter time.Time
}
type UpdateAccountCompanyImagesColumns struct {
Values AccountCompanyImagesColumns
Where AccountCompanyImagesColumns
}
type AccountCompanyImageMapColumns struct {
CompanyID string
CompanyImageID string
}
type SelectAccountCompanyImageMapColumns struct {
CompanyID []string
CompanyImageID []string
}
type UpdateAccountCompanyImageMapColumns struct {
Values AccountCompanyImageMapColumns
Where AccountCompanyImageMapColumns
}
|
package validator
import (
"github.com/go-playground/validator/v10"
"go.uber.org/zap"
"regexp"
)
func ValidateEmail(fl validator.FieldLevel) bool {
email := fl.Field().String()
if _, err := regexp.MatchString(`/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/`,
email); err != nil {
zap.S().Errorf("邮箱不合法 %s", err.Error())
return false
}
return true
}
|
/*
Copyright 2018 The HAWQ Team.
*/
package main
import (
"flag"
"log"
controllerlib "github.com/kubernetes-incubator/apiserver-builder/pkg/controller"
"github.com/hawq-cn/apiserver-example/pkg/controller"
)
var kubeconfig = flag.String("kubeconfig", "", "path to kubeconfig")
func main() {
flag.Parse()
config, err := controllerlib.GetConfig(*kubeconfig)
if err != nil {
log.Fatalf("Could not create Config for talking to the apiserver: %v", err)
}
controllers, _ := controller.GetAllControllers(config)
controllerlib.StartControllerManager(controllers...)
// Blockforever
select {}
}
|
/*
Author: Conor McGrath
Student ID: g00291461
Description: A web application using go based on the Eliza Program.
*/
package main
import (
"fmt"
"net/http"
"math/rand"
"regexp"
"time"
)
func elizaResponse(w http.ResponseWriter, r *http.Request) {
input := r.URL.Query().Get("value")
if matched, _ := regexp.MatchString(`(?i).*\b[Hh]ello|[Hh]ey|[Hh]i\b.*`, input); matched{
responses := []string {
"Hello. Nice to meet you.",
"Hi there.",
"What's up. What do you want to talk about.",
"Oh hello there.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
} else
if matched, _ := regexp.MatchString(`(?i).*\b[Ww]hy\b|why.*`, input); matched{
responses := []string {
"Why do you ask that?",
"I can't tell you why.",
"Have you thought about this that much?",
"Why do we have to talk about such things?",
"Unfortunately, I dont have all the answers.",
"I'm thoroughly enjoying this conversation.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ww]ho.*`, input); matched{
responses := []string {
"Im not sure who you are on about. Tell me more about yourself though!",
"I dont know who that is. Tell me more about you instead!",
"I can't answer that for certain.",
"I'm not interested in that, tell me about you!",
"Oh, you really are the talkative type aren't you?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ww]hat.*`, input); matched{
responses := []string {
"I'm not really sure to be honest.",
"I'm at a loss for things to say...",
"This conversation has been extremely enlightening.",
"I'd prefer not to comment....",
"Sometimes I like to answer any question put to me, the other times I tend to deviate from the question.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ww]hen.*`, input); matched{
responses := []string {
"I'm not really sure to be honest.",
"Does that question interest you ?",
"Are such questions much on your mind?",
"You seem like the inquisitive type...",
"What answer would please you most ?",
"I can't really answer that, i'd have to think about it",
"I find far easier to direct the conversation myself, it's almost a talent one could say.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ww]here.*`, input); matched{
responses := []string {
"I'm not really sure to be honest.",
"Do you not know that yourself? Or are you just trying to trick me?",
"I can't say I know that much about that.",
"Does it really concern you?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Hh]ow.*`, input); matched{
responses := []string {
"I'm not really sure to be honest.",
"Oh, sure, you know yourself.",
"Must we concern ourselves with such trivial matters?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*I am|I'm*`, input); matched{
responses := []string {
"Oh, and why is that?",
"Why are you like that?",
"I dont understand that.",
"Tell me, why is that the case?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ww]as I*`, input); matched{
responses := []string {
"What if you were?",
"Do you think you were?",
"Were you?",
"What would it mean if you were?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\bI was\b*`, input); matched{
responses := []string {
"Were you really?",
"Why do you tell me that you were?",
"Were you?",
"Perhaps I already knew you were?...",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\bI am|I'm\b*`, input); matched{
responses := []string {
"Are you?",
"Did you think telling me this would make a difference to me or you?",
"Talking to me can cause these things.",
"Do you truly believe that?",
"Why is that?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\bI do\b*`, input); matched{
responses := []string {
"Good for you.",
"I'm surprised.",
"Why do you?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\bI dont|I don't\b*`, input); matched{
responses := []string {
"I thought you would.",
"Hard to believe.",
"Why don't you?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Pp]erhaps\b*`, input); matched{
responses := []string {
"You don't seem quite certain.",
"Why the uncertain tone",
"You aren't sure?",
"Don't you know",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*you are|you're*`, input); matched{
responses := []string {
"You don't seem quite certain though...",
"Do you sometimes wish that you were?",
"You know a lot about me is that it",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Yy]ou\b*`, input); matched{
responses := []string {
"We were discussing you, not me.",
"You're not really talking about me, are you ?",
"What are your feelings now ?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Yy]es\b*`, input); matched{
responses := []string {
"You seem to be quite positive.",
"You are sure.",
"I see.",
"I understand.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Nn]o\b*`, input); matched{
responses := []string {
"Are you saying no just to be negative?",
"You are being a bit negative.",
"Why not?",
"Why 'no'?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Bb]ecause\b*`, input); matched{
responses := []string {
"Is that the real reason?",
"Don't any other reasons come to mind ?",
"Does that reason seem to explain anything else?",
"What other reasons might there be?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ww]hy don't you\b*`, input); matched{
responses := []string {
"Do you believe I don't?",
"Perhaps I will, in good time...",
"Would that please you?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\balwaysb*`, input); matched{
responses := []string {
"Really? Always?",
"Can't you think of a specific example",
"When?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ll]ike\b*`, input); matched{
responses := []string {
"Really? Like why is that?",
"I would never of guessed that.",
"Since when?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ll]ove\b*`, input); matched{
responses := []string {
"Really? Like why do you?",
"That's amazing. Tell me more.",
"I wish I could also feel that too.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\bI would\b*`, input); matched{
responses := []string {
"Really? Why would you?",
"Why would you?",
"You're telling me you would? Interesting. Go on.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Hh]ate\b*`, input); matched{
responses := []string {
"Really? Why is that?",
"I would never of guessed that.",
"Since when?",
"Hate is such a strong word.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\bdon't|do not\b*`, input); matched{
responses := []string {
"Why don't you?",
"I can't believe you dont.",
"I would of thought you would the oppposite for some reason...",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
}
if matched, _ := regexp.MatchString(`(?i).*\b[Ii]t is\b*`, input); matched{
responses := []string {
"Is it really?",
"I would never of guessed that.",
"I can't believe that that is the case.",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
return
} else{
responses := []string {
"Oh, can't we talk about something else?",
"I think we should talk about something else.",
"Tell me more about you.",
"I'm not really sure what you mean.",
"I can't say I fully grasp what you are saying.",
"Is ther any thing else you would like to talk about?",
}
randIndex := rand.Intn(len(responses))
fmt.Fprintf(w, responses[randIndex])
}
}
func main() {
//seed the time so a random response if picked
rand.Seed(time.Now().Unix())
//serves the file from the static folder
fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs)
//handles the function elizaResponse
http.HandleFunc("/elizaResponse", elizaResponse)
http.ListenAndServe(":8080", nil)
}
|
package utils
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rsa"
"crypto/x509"
"runtime"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestShouldReturnErrWhenX509DirectoryNotExist(t *testing.T) {
pool, warnings, errors := NewX509CertPool("/tmp/asdfzyxabc123/not/a/real/dir")
assert.NotNil(t, pool)
if runtime.GOOS == windows {
require.Len(t, warnings, 1)
assert.EqualError(t, warnings[0], "could not load system certificate pool which may result in untrusted certificate issues: crypto/x509: system root pool is not available on Windows")
} else {
assert.Len(t, warnings, 0)
}
require.Len(t, errors, 1)
if runtime.GOOS == windows {
assert.EqualError(t, errors[0], "could not read certificates from directory open /tmp/asdfzyxabc123/not/a/real/dir: The system cannot find the path specified.")
} else {
assert.EqualError(t, errors[0], "could not read certificates from directory open /tmp/asdfzyxabc123/not/a/real/dir: no such file or directory")
}
}
func TestShouldNotReturnErrWhenX509DirectoryExist(t *testing.T) {
dir := t.TempDir()
pool, warnings, errors := NewX509CertPool(dir)
assert.NotNil(t, pool)
if runtime.GOOS == windows {
require.Len(t, warnings, 1)
assert.EqualError(t, warnings[0], "could not load system certificate pool which may result in untrusted certificate issues: crypto/x509: system root pool is not available on Windows")
} else {
assert.Len(t, warnings, 0)
}
assert.Len(t, errors, 0)
}
func TestShouldReadCertsFromDirectoryButNotKeys(t *testing.T) {
pool, warnings, errors := NewX509CertPool("../suites/common/pki/")
assert.NotNil(t, pool)
require.Len(t, errors, 3)
if runtime.GOOS == "windows" {
require.Len(t, warnings, 1)
assert.EqualError(t, warnings[0], "could not load system certificate pool which may result in untrusted certificate issues: crypto/x509: system root pool is not available on Windows")
} else {
assert.Len(t, warnings, 0)
}
assert.EqualError(t, errors[0], "could not import certificate private.backend.pem")
assert.EqualError(t, errors[1], "could not import certificate private.oidc.pem")
assert.EqualError(t, errors[2], "could not import certificate private.pem")
}
func TestShouldGenerateCertificateAndPersistIt(t *testing.T) {
testCases := []struct {
Name string
PrivateKeyBuilder PrivateKeyBuilder
}{
{
Name: "P224",
PrivateKeyBuilder: ECDSAKeyBuilder{}.WithCurve(elliptic.P224()),
},
{
Name: "P256",
PrivateKeyBuilder: ECDSAKeyBuilder{}.WithCurve(elliptic.P256()),
},
{
Name: "P384",
PrivateKeyBuilder: ECDSAKeyBuilder{}.WithCurve(elliptic.P384()),
},
{
Name: "P521",
PrivateKeyBuilder: ECDSAKeyBuilder{}.WithCurve(elliptic.P521()),
},
{
Name: "Ed25519",
PrivateKeyBuilder: Ed25519KeyBuilder{},
},
{
Name: "RSA",
PrivateKeyBuilder: RSAKeyBuilder{keySizeInBits: 2048},
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
certBytes, keyBytes, err := GenerateCertificate(tc.PrivateKeyBuilder, []string{"authelia.com", "example.org"}, time.Now(), 3*time.Hour, false)
require.NoError(t, err)
assert.True(t, len(certBytes) > 0)
assert.True(t, len(keyBytes) > 0)
})
}
}
func TestShouldParseKeySigAlgorithm(t *testing.T) {
testCases := []struct {
Name string
InputKey, InputSig string
ExpectedKeyAlg x509.PublicKeyAlgorithm
ExpectedSigAlg x509.SignatureAlgorithm
}{
{
Name: "ShouldNotParseInvalidKeyAlg",
InputKey: "DDD",
InputSig: "SHA1",
ExpectedKeyAlg: x509.UnknownPublicKeyAlgorithm,
ExpectedSigAlg: x509.UnknownSignatureAlgorithm,
},
{
Name: "ShouldParseKeyRSASigSHA1",
InputKey: "RSA",
InputSig: "SHA1",
ExpectedKeyAlg: x509.RSA,
ExpectedSigAlg: x509.SHA1WithRSA,
},
{
Name: "ShouldParseKeyRSASigSHA256",
InputKey: "RSA",
InputSig: "SHA256",
ExpectedKeyAlg: x509.RSA,
ExpectedSigAlg: x509.SHA256WithRSA,
},
{
Name: "ShouldParseKeyRSASigSHA384",
InputKey: "RSA",
InputSig: "SHA384",
ExpectedKeyAlg: x509.RSA,
ExpectedSigAlg: x509.SHA384WithRSA,
},
{
Name: "ShouldParseKeyRSASigSHA512",
InputKey: "RSA",
InputSig: "SHA512",
ExpectedKeyAlg: x509.RSA,
ExpectedSigAlg: x509.SHA512WithRSA,
},
{
Name: "ShouldNotParseKeyRSASigInvalid",
InputKey: "RSA",
InputSig: "INVALID",
ExpectedKeyAlg: x509.RSA,
ExpectedSigAlg: x509.UnknownSignatureAlgorithm,
},
{
Name: "ShouldParseKeyECDSASigSHA1",
InputKey: "ECDSA",
InputSig: "SHA1",
ExpectedKeyAlg: x509.ECDSA,
ExpectedSigAlg: x509.ECDSAWithSHA1,
},
{
Name: "ShouldParseKeyECDSASigSHA256",
InputKey: "ECDSA",
InputSig: "SHA256",
ExpectedKeyAlg: x509.ECDSA,
ExpectedSigAlg: x509.ECDSAWithSHA256,
},
{
Name: "ShouldParseKeyECDSASigSHA384",
InputKey: "ECDSA",
InputSig: "SHA384",
ExpectedKeyAlg: x509.ECDSA,
ExpectedSigAlg: x509.ECDSAWithSHA384,
},
{
Name: "ShouldParseKeyECDSASigSHA512",
InputKey: "ECDSA",
InputSig: "SHA512",
ExpectedKeyAlg: x509.ECDSA,
ExpectedSigAlg: x509.ECDSAWithSHA512,
},
{
Name: "ShouldNotParseKeyECDSASigInvalid",
InputKey: "ECDSA",
InputSig: "INVALID",
ExpectedKeyAlg: x509.ECDSA,
ExpectedSigAlg: x509.UnknownSignatureAlgorithm,
},
{
Name: "ShouldParseKeyEd25519SigSHA1",
InputKey: "ED25519",
InputSig: "SHA1",
ExpectedKeyAlg: x509.Ed25519,
ExpectedSigAlg: x509.PureEd25519,
},
{
Name: "ShouldParseKeyEd25519SigSHA256",
InputKey: "ED25519",
InputSig: "SHA256",
ExpectedKeyAlg: x509.Ed25519,
ExpectedSigAlg: x509.PureEd25519,
},
{
Name: "ShouldParseKeyEd25519SigSHA384",
InputKey: "ED25519",
InputSig: "SHA384",
ExpectedKeyAlg: x509.Ed25519,
ExpectedSigAlg: x509.PureEd25519,
},
{
Name: "ShouldParseKeyEd25519SigSHA512",
InputKey: "ED25519",
InputSig: "SHA512",
ExpectedKeyAlg: x509.Ed25519,
ExpectedSigAlg: x509.PureEd25519,
},
{
Name: "ShouldParseKeyEd25519SigInvalid",
InputKey: "ED25519",
InputSig: "INVALID",
ExpectedKeyAlg: x509.Ed25519,
ExpectedSigAlg: x509.PureEd25519,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
actualKey, actualSig := KeySigAlgorithmFromString(tc.InputKey, tc.InputSig)
actualKeyLower, actualSigLower := KeySigAlgorithmFromString(strings.ToLower(tc.InputKey), strings.ToLower(tc.InputSig))
assert.Equal(t, tc.ExpectedKeyAlg, actualKey)
assert.Equal(t, tc.ExpectedSigAlg, actualSig)
assert.Equal(t, tc.ExpectedKeyAlg, actualKeyLower)
assert.Equal(t, tc.ExpectedSigAlg, actualSigLower)
})
}
}
func TestShouldParseCurves(t *testing.T) {
testCases := []struct {
Name string
Input string
Expected elliptic.Curve
}{
{
Name: "P224-Standard",
Input: "P224",
Expected: elliptic.P224(),
},
{
Name: "P224-Lowercase",
Input: "p224",
Expected: elliptic.P224(),
},
{
Name: "P224-Hyphenated",
Input: "P-224",
Expected: elliptic.P224(),
},
{
Name: "P256-Standard",
Input: "P256",
Expected: elliptic.P256(),
},
{
Name: "P256-Lowercase",
Input: "p256",
Expected: elliptic.P256(),
},
{
Name: "P256-Hyphenated",
Input: "P-256",
Expected: elliptic.P256(),
},
{
Name: "P384-Standard",
Input: "P384",
Expected: elliptic.P384(),
},
{
Name: "P384-Lowercase",
Input: "p384",
Expected: elliptic.P384(),
},
{
Name: "P384-Hyphenated",
Input: "P-384",
Expected: elliptic.P384(),
},
{
Name: "P521-Standard",
Input: "P521",
Expected: elliptic.P521(),
},
{
Name: "P521-Lowercase",
Input: "p521",
Expected: elliptic.P521(),
},
{
Name: "P521-Hyphenated",
Input: "P-521",
Expected: elliptic.P521(),
},
{
Name: "Invalid",
Input: "521",
Expected: nil,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
actual := EllipticCurveFromString(tc.Input)
assert.Equal(t, tc.Expected, actual)
})
}
}
func testMustBuildPrivateKey(b PrivateKeyBuilder) any {
k, err := b.Build()
if err != nil {
panic(err)
}
return k
}
func TestPublicKeyFromPrivateKey(t *testing.T) {
testCases := []struct {
Name string
PrivateKey any
Expected any
}{
{
Name: "RSA2048",
PrivateKey: testMustBuildPrivateKey(RSAKeyBuilder{}.WithKeySize(512)),
Expected: &rsa.PublicKey{},
},
{
Name: "ECDSA-P256",
PrivateKey: testMustBuildPrivateKey(ECDSAKeyBuilder{}.WithCurve(elliptic.P256())),
Expected: &ecdsa.PublicKey{},
},
{
Name: "Ed25519",
PrivateKey: testMustBuildPrivateKey(Ed25519KeyBuilder{}),
Expected: ed25519.PublicKey{},
},
{
Name: "Invalid",
PrivateKey: 8,
Expected: nil,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
actual := PublicKeyFromPrivateKey(tc.PrivateKey)
if tc.Expected == nil {
assert.Nil(t, actual)
} else {
assert.IsType(t, tc.Expected, actual)
}
})
}
}
func TestX509ParseKeyUsage(t *testing.T) {
testCases := []struct {
name string
have [][]string
ca bool
expected x509.KeyUsage
}{
{
"ShouldParseDefault", nil, false, x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
},
{
"ShouldParseDefaultCA", nil, true, x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
},
{
"ShouldParseDigitalSignature", [][]string{{"digital_signature"}, {"Digital_Signature"}, {"digitalsignature"}, {"digitalSignature"}}, false, x509.KeyUsageDigitalSignature,
},
{
"ShouldParseKeyEncipherment", [][]string{{"key_encipherment"}, {"Key_Encipherment"}, {"keyencipherment"}, {"keyEncipherment"}}, false, x509.KeyUsageKeyEncipherment,
},
{
"ShouldParseDataEncipherment", [][]string{{"data_encipherment"}, {"Data_Encipherment"}, {"dataencipherment"}, {"dataEncipherment"}}, false, x509.KeyUsageDataEncipherment,
},
{
"ShouldParseKeyAgreement", [][]string{{"key_agreement"}, {"Key_Agreement"}, {"keyagreement"}, {"keyAgreement"}}, false, x509.KeyUsageKeyAgreement,
},
{
"ShouldParseCertSign", [][]string{{"cert_sign"}, {"Cert_Sign"}, {"certsign"}, {"certSign"}, {"certificate_sign"}, {"Certificate_Sign"}, {"certificatesign"}, {"certificateSign"}}, false, x509.KeyUsageCertSign,
},
{
"ShouldParseCRLSign", [][]string{{"crl_sign"}, {"CRL_Sign"}, {"crlsign"}, {"CRLSign"}}, false, x509.KeyUsageCRLSign,
},
{
"ShouldParseEncipherOnly", [][]string{{"encipher_only"}, {"Encipher_Only"}, {"encipheronly"}, {"encipherOnly"}}, false, x509.KeyUsageEncipherOnly,
},
{
"ShouldParseDecipherOnly", [][]string{{"decipher_only"}, {"Decipher_Only"}, {"decipheronly"}, {"decipherOnly"}}, false, x509.KeyUsageDecipherOnly,
},
{
"ShouldParseMulti", [][]string{{"digitalSignature", "keyEncipherment", "dataEncipherment", "certSign", "crlSign"}}, false, x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageDataEncipherment | x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if len(tc.have) == 0 {
actual := X509ParseKeyUsage(nil, tc.ca)
assert.Equal(t, tc.expected, actual)
}
for _, have := range tc.have {
t.Run(strings.Join(have, ","), func(t *testing.T) {
actual := X509ParseKeyUsage(have, tc.ca)
assert.Equal(t, tc.expected, actual)
})
}
})
}
}
func TestX509ParseExtendedKeyUsage(t *testing.T) {
testCases := []struct {
name string
have [][]string
ca bool
expected []x509.ExtKeyUsage
}{
{"ShouldParseDefault", nil, false, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}},
{"ShouldParseDefaultCA", nil, true, []x509.ExtKeyUsage{}},
{"ShouldParseAny", [][]string{{"any"}, {"Any"}, {"any", "server_auth"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageAny}},
{"ShouldParseServerAuth", [][]string{{"server_auth"}, {"Server_Auth"}, {"serverauth"}, {"serverAuth"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}},
{"ShouldParseClientAuth", [][]string{{"client_auth"}, {"Client_Auth"}, {"clientauth"}, {"clientAuth"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}},
{"ShouldParseCodeSigning", [][]string{{"code_signing"}, {"Code_Signing"}, {"codesigning"}, {"codeSigning"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}},
{"ShouldParseEmailProtection", [][]string{{"email_protection"}, {"Email_Protection"}, {"emailprotection"}, {"emailProtection"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageEmailProtection}},
{"ShouldParseIPSECEndSystem", [][]string{{"ipsec_endsystem"}, {"IPSEC_Endsystem"}, {"ipsec_end_system"}, {"IPSEC_End_System"}, {"ipsecendsystem"}, {"ipsecEndSystem"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageIPSECEndSystem}},
{"ShouldParseIPSECTunnel", [][]string{{"ipsec_tunnel"}, {"IPSEC_Tunnel"}, {"ipsectunnel"}, {"ipsecTunnel"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageIPSECTunnel}},
{"ShouldParseIPSECUser", [][]string{{"ipsec_user"}, {"IPSEC_User"}, {"ipsecuser"}, {"ipsecUser"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageIPSECUser}},
{"ShouldParseOCSPSigning", [][]string{{"ocsp_signing"}, {"OCSP_Signing"}, {"ocspsigning"}, {"ocspSigning"}}, false, []x509.ExtKeyUsage{x509.ExtKeyUsageOCSPSigning}},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if len(tc.have) == 0 {
actual := X509ParseExtendedKeyUsage(nil, tc.ca)
assert.Equal(t, tc.expected, actual)
}
for _, have := range tc.have {
t.Run(strings.Join(have, ","), func(t *testing.T) {
actual := X509ParseExtendedKeyUsage(have, tc.ca)
assert.Equal(t, tc.expected, actual)
})
}
})
}
}
|
package handlers
import (
"fmt"
"log"
"time"
"math/rand"
"github.com/golang/protobuf/proto"
pbd "crazyant.com/deadfat/pbd/hero"
oaccount "webapi/account"
obean "webapi/bean"
. "webapi/common"
FYSDK "webapi/fysdk"
osession "webapi/session"
oskeleton "webapi/skeleton"
pkgTrace "webapi/trace"
)
func HandleGuestLogin(skeleton *oskeleton.Skeleton, session *osession.Session, _ *oaccount.Role, packet proto.Message) (error, uint16, proto.Message) {
payload, _ := packet.(*pbd.Login)
resp := &pbd.LoginResp{}
imei := payload.Imei
clientVersion := payload.ClientVersion
clientChannel := payload.Channel
nickName := payload.NickName
if imei == "" {
log.Printf("登录时设备号为空: [%s][%s][%s]", clientChannel, clientVersion, session.IP)
resp.Err = doHeroError(kIMEIIsEmpty)
return nil, uint16(pbd.GC_ID_GUEST_LOGIN_RESP), resp
}
// log.Printf("设备登录: %s %s", imei, session.IP)
pCache := skeleton.CacheManager()
pAccountManager := skeleton.AccountManager()
pConfManager := skeleton.ConfigManager()
// 新版本触发版本检查
if clientChannel != "" {
haveNewVersion, isForceUpdate, newVersion, downloadLink := pConfManager.CheckNewVersion(clientChannel, clientVersion)
if haveNewVersion {
resp.Update = &pbd.VersionUpdateAlert{
Force: proto.Bool(isForceUpdate),
Version: proto.String(newVersion),
Link: proto.String(downloadLink),
}
}
}
channelConf := pConfManager.GetChannel(clientChannel)
if channelConf == nil {
log.Printf("查询登录渠道配置时失败: %s", clientChannel)
resp.Err = doHeroError(kInternelServerError)
return nil, uint16(pbd.GC_ID_GUEST_LOGIN_RESP), resp
}
loginWay := uint32(channelConf.LoginMode)
loginUUID := imei
switch loginWay {
case GUEST_LOGIN:
loginUUID = imei
case FYSDK_ONLINE:
// 校验token
platform := channelConf.SignName
token := payload.FysdkToken
if platform == "" || token == "" {
log.Printf("FYSDK网游版本登录时platform或token为空: %s, %s", platform, token)
resp.Err = doHeroError(kIMEIIsEmpty)
return nil, uint16(pbd.GC_ID_GUEST_LOGIN_RESP), resp
}
uuid, err := FYSDK.Login(platform, token)
if err != nil {
log.Printf("FYSDK网游版本登录时校验出错: %v", err)
resp.Err = doHeroError(kInternelServerError)
return nil, uint16(pbd.GC_ID_GUEST_LOGIN_RESP), resp
}
if uuid == "" {
log.Printf("FYSDK网游版本uuid为空[渠道:%s][IMEI:%s][版本:%s]", clientChannel, imei, clientVersion)
resp.Err = doHeroError(kIMEIIsEmpty)
return nil, uint16(pbd.GC_ID_GUEST_LOGIN_RESP), resp
}
loginUUID = uuid
case FYSDK_OFFLINE:
loginUUID = payload.FysdkUuid
if loginUUID == "" {
log.Printf("FYSDK单机版本登录时UUID为空[渠道:%s][IMEI:%s][版本:%s]", clientChannel, imei, clientVersion)
resp.Err = doHeroError(kIMEIIsEmpty)
return nil, uint16(pbd.GC_ID_GUEST_LOGIN_RESP), resp
}
}
accountStr := fmt.Sprintf("%s:%s", clientChannel, loginUUID);
err, account := obean.FindSimAccount(accountStr)
var uid uint32
if err != nil {
//没有注册过的账号,注册
if uid = pCache.GenID("uid", 1); uid == 0 {
log.Printf("生成角色编号失败: %d", accountStr)
resp.Err = doHeroError(kInternelServerError)
return nil, uint16(pbd.GC_ID_GUEST_LOGIN_RESP), resp
} else {
if nickName == ""{
nickName = fmt.Sprintf("%s%05d","英雄", rand.Intn(99999));
}
if err := obean.RegisterAccount(accountStr, nickName, uid); err != nil {
log.Printf("插入新角色%d账号数据时出错: %v", uid, err)
resp.Err = doHeroError(kInternelServerError)
} else {
resp.Uid = uid
resp.ArenaRank = 0
resp.ArenaScore = 0
resp.ChallengeRank = 0
resp.ChallengeScore = 0
}
}
}else{
uid = account.Uid
if nickName != "" {
obean.SetNickName(nickName, uid)
}
resp.Uid = uid
resp.ArenaScore =obean.GetScore(uid)
resp.ArenaRank = obean.GetRank(uid)
resp.ChallengeRank = obean.GetChallRank(uid)
resp.ChallengeScore = obean.GetChallScore(uid)
}
resp.Token = skeleton.CreateUserSecret(uid)
pAccountManager.LoadRole(uid)
// 登陆事件
skeleton.Collect(pkgTrace.UserLogin,
clientChannel, imei, loginWay, loginUUID, uid, session.IP, clientVersion,
time.Now().Unix())
return nil, uint16(pbd.GC_ID_GUEST_LOGIN_RESP), resp
}
//func HandleNickSet(_ *oskeleton.Skeleton, _ *osession.Session, roleob *oaccount.Role, packet proto.Message) (error, uint16, proto.Message) {
// payload, _ := packet.(*pbd.NickSet)
// resp := &pbd.NickSetResp{}
//
// if roleob.GetGuideID() != obean.GUIDE_NICK_SET {
// resp.Err = doError(kNickNameHaveSet)
// return nil, uint16(pbd.GC_ID_NICK_SET_RESP), resp
// }
//
// nick := strings.TrimSpace(payload.GetNick())
// if nick == "" {
// resp.Err = doError(kNickIsSensitivity)
// return nil, uint16(pbd.GC_ID_NICK_SET_RESP), resp
// }
//
// lang := payload.GetLang()
//
// switch lang {
// case 1: // 简体中文
// if valid := wordstock.ValidWord(nick); !valid {
// resp.Err = doError(kNickIsSensitivity)
// return nil, uint16(pbd.GC_ID_NICK_SET_RESP), resp
// }
//
// default:
// }
//
// roleob.SetNickAndGuide(nick)
//
// return nil, uint16(pbd.GC_ID_NICK_SET_RESP), resp
//}
//func HandleInviteCodeInput(skeleton *oskeleton.Skeleton, session *osession.Session, roleob *oaccount.Role, packet proto.Message) (error, uint16, proto.Message) {
// payload, _ := packet.(*pbd.InviteCodeReq)
// resp := &pbd.InviteCodeResp{}
//
// // 判断邀请码是否符合规范
// code := strings.ToUpper(payload.GetInviteCode())
// if len(code) != 8 {
// resp.Err = doError(kInviteCodeInvalid)
// return nil, uint16(pbd.GC_ID_INVITE_CODE_RESP), resp
// }
//
// // 判断邀请码是否存在以及是否未被使用
// err, bean := obean.QueryInviteCode(code)
// if err != nil {
// log.Printf("查询邀请码%s时出错: %v", code, err)
// resp.Err = doError(kInviteCodeInvalid)
// return nil, uint16(pbd.GC_ID_INVITE_CODE_RESP), resp
// }
//
// // 判断是否存在
// if bean == nil {
// resp.Err = doError(kInviteCodeInvalid)
// return nil, uint16(pbd.GC_ID_INVITE_CODE_RESP), resp
// }
//
// // 判断是否满足限定渠道
// if roleob.GetChannelID() != bean.ChannelID {
// resp.Err = doError(kInviteCodeInvalid)
// return nil, uint16(pbd.GC_ID_INVITE_CODE_RESP), resp
// }
//
// // 判断是否已被使用
// if bean.Uid != 0 {
// resp.Err = doError(kInviteCodeUsed)
// return nil, uint16(pbd.GC_ID_INVITE_CODE_RESP), resp
// }
//
// // 判断是否过期
// if bean.Deadline > 0 && time.Now().Unix() > bean.Deadline {
// resp.Err = doError(kInviteCodeTimeout, fmt.Sprintf("%d", bean.Deadline))
// return nil, uint16(pbd.GC_ID_INVITE_CODE_RESP), resp
// }
//
// bean.SetAchieved(roleob.Uid())
// if err := obean.UpdateInviteCode(bean); err != nil {
// log.Printf("更新邀请码[%d][%s]使用记录时出错: %v", roleob.Uid(), code, err)
// resp.Err = doError(kInternelServerError)
// return nil, uint16(pbd.GC_ID_INVITE_CODE_RESP), resp
// }
//
// roleob.SetInviteCode(code)
//
// return nil, uint16(pbd.GC_ID_INVITE_CODE_RESP), resp
//}
//
//func HandleHeartBeat(skeleton *oskeleton.Skeleton, session *osession.Session, roleob *oaccount.Role, packet proto.Message) (error, uint16, proto.Message) {
//
// return nil, uint16(pbd.GC_ID_HEART_BEAT_RESP), roleob.SerializeNotifies()
//}
|
package handler
import (
"context"
"path/filepath"
"testing"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
// LocalNotificationTestSuite 是本地通知单元测试的 Test Suite
type LocalNotificationTestSuite struct {
suite.Suite
jinmuHealth *JinmuHealth
}
// SetupSuite 设置测试环境
func (suite *LocalNotificationTestSuite) SetupSuite() {
envFilepath := filepath.Join("testdata", "local.svc-biz-core.env")
suite.jinmuHealth = newTestingJinmuHealthFromEnvFile(envFilepath)
suite.jinmuHealth.datastore, _ = newTestingDbClientFromEnvFile(envFilepath)
suite.jinmuHealth.mailClient, _ = newTestingMailClientFromEnvFile(envFilepath)
}
// TestClientAuth 测试客户端授权
func (suite *LocalNotificationTestSuite) TestCreateLocalNotification() {
t := suite.T()
ctx := context.Background()
req := new(proto.CreateLocalNotificationRequest)
resp := new(proto.CreateLocalNotificationResponse)
req.LocalNotification = &proto.LocalNotification{
Content: "喜马宝宝提醒您,又到检查时间啦!",
Schedule: &proto.Schedule{
EventHappenAt: "2018-10-10T20:00:00",
Timezone: "local",
Repeat: &proto.RepeatSchedule{
Frequency: proto.Frequency_FREQUENCY_DAILY,
Interval: 1,
},
},
}
assert.NoError(t, suite.jinmuHealth.CreateLocalNotification(ctx, req, resp))
}
func (suite *LocalNotificationTestSuite) GetLocalNotifications() {
t := suite.T()
ctx := context.Background()
req := new(proto.GetLocalNotificationsRequest)
resp := new(proto.GetLocalNotificationsResponse)
assert.NoError(t, suite.jinmuHealth.GetLocalNotifications(ctx, req, resp))
}
func TestCreateLocalNotificationTestSuite(t *testing.T) {
suite.Run(t, new(LocalNotificationTestSuite))
}
|
package utils
import (
"bytes"
"context"
"fmt"
"github.com/riposa/utils/log"
"github.com/riposa/utils/errors"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/qiniu/api.v7/auth/qbox"
"github.com/qiniu/api.v7/storage"
"math"
"math/rand"
"strings"
"time"
)
const (
earthRadius = 6378.137
accessKey = ""
secretKey = ""
bucket = "testhengha"
getWxaCodeInterface = "https://api.weixin.qq.com/wxa/getwxacodeunlimit"
)
type TimeIt struct {
start time.Time
end time.Time
moduleName string
}
var (
utilsLogger = log.New()
)
func rad(n float64) float64 {
return n * math.Pi / 180.0
}
func GetWxaCode(token, scene, page string) (string, error) {
resp, err := Requests.PostJsonWithQueryString(getWxaCodeInterface, map[string]interface{}{"scene": scene, "page": page, "is_hyaline": true, "width": 100}, nil, map[string]string{"access_token": token})
if err != nil {
return "", err
}
img := resp.Body()
putPolicy := storage.PutPolicy{
Scope: bucket,
}
mac := qbox.NewMac(accessKey, secretKey)
upToken := putPolicy.UploadToken(mac)
cfg := storage.Config{}
cfg.Zone = &storage.ZoneHuadong
formUploader := storage.NewFormUploader(&cfg)
ret := storage.PutRet{}
putExtra := storage.PutExtra{}
data := img
dataLen := int64(len(data))
err = formUploader.PutWithoutKey(context.Background(), &ret, upToken, bytes.NewReader(data), dataLen, &putExtra)
if err != nil {
utilsLogger.Exception(err)
return "", err
}
return ret.Hash, nil
}
// distance unit is km
func PointSquareWithDistance(lat, lng, distance float64) (latScope [2]float64, lngScope [2]float64) {
radLat := rad(lat)
lngWidth := distance / (math.Cos(radLat) * 111.0)
latWidth := distance / 111.0
latScope[0] = lat + latWidth
latScope[1] = lat - latWidth
lngScope[0] = lng + lngWidth
lngScope[1] = lng - lngWidth
return
}
func calculateTwoPointDistance(lat1, lat2, lng1, lng2 float64) float64 {
radLat1 := rad(lat1)
radLat2 := rad(lat2)
latDiff := radLat1 - radLat2
lngDiff := rad(lng1) - rad(lng2)
res := 2 * math.Asin(math.Sqrt(math.Pow(math.Sin(latDiff/2), 2)+math.Cos(radLat1)*math.Cos(radLat2)*math.Pow(math.Sin(lngDiff/2), 2)))
res = res * earthRadius
res = math.Round(res*10000) / 10000
return res
}
// distance unit is km
func JudgeExistInRegion(lat1, lat2, lng1, lng2, distance float64) bool {
if calculateTwoPointDistance(lat1, lat2, lng1, lng2) <= distance {
return true
} else {
return false
}
}
func MpGetUserFromHeader(c *gin.Context) (string, error) {
author := c.GetHeader("Authorization")
if author != "" {
return strings.TrimPrefix(author, "UserID "), nil
} else {
return "", errors.New(7010)
}
}
func GetDBFromContext(c *gin.Context, schema string) (*gorm.DB, error) {
l, exist := c.Get(schema + "_conn")
if !exist {
return nil, errors.New(310)
}
conn, ok := l.(*gorm.DB)
if !ok {
return nil, errors.New(311)
}
return conn, nil
}
func CheckFieldLength(v string, max int, cn string) (bool, errors.Error) {
vSlice := strings.Split(v, "")
if len(vSlice) > max {
return false, errors.NewFormat(30, cn, max)
}
return true, errors.Error{}
}
func (t *TimeIt) End() {
t.end = time.Now()
utilsLogger.Infof(fmt.Sprintf("Goroutine [%s] cost %.3f ms", t.moduleName, float64(t.end.UnixNano()-t.start.UnixNano())/1e6))
}
func NewTimeIt(module string) *TimeIt {
var t TimeIt
t.start = time.Now()
t.moduleName = module
return &t
}
func IsLoggedIn(c *gin.Context) bool {
var isLoggedIn bool
t, exist := c.Get("is_logged_in")
if !exist {
isLoggedIn = false
} else {
if tt, ok := t.(bool); ok {
isLoggedIn = tt
} else {
isLoggedIn = false
}
}
return isLoggedIn
}
func GetUserIDFromContext(c *gin.Context) int {
var userID int
t, exist := c.Get("user_id")
if !exist {
userID = 0
} else {
if tt, ok := t.(int); ok {
userID = tt
} else {
userID = 0
}
}
return userID
}
func Factorial(n int) int {
var r int
r = 1
for ; n > 0; n-- {
r *= n
}
return r
}
func Combination(n, m int) int {
if n < m {
return 0
}
return Factorial(n) / Factorial(m) * Factorial(n-m)
}
func CombinationResult(n int, m int) [][]int {
if m < 1 || m > n {
fmt.Println("Illegal argument. Param m must between 1 and len(nums).")
return [][]int{}
}
result := make([][]int, 0, Combination(n, m))
indexes := make([]int, n)
for i := 0; i < n; i++ {
if i < m {
indexes[i] = 1
} else {
indexes[i] = 0
}
}
result = addTo(result, indexes)
for {
find := false
for i := 0; i < n-1; i++ {
if indexes[i] == 1 && indexes[i+1] == 0 {
find = true
indexes[i], indexes[i+1] = 0, 1
if i > 1 {
moveOneToLeft(indexes[:i])
}
result = addTo(result, indexes)
break
}
}
if !find {
break
}
}
return result
}
func addTo(arr [][]int, ele []int) [][]int {
newEle := make([]int, len(ele))
copy(newEle, ele)
arr = append(arr, newEle)
return arr
}
func moveOneToLeft(leftNums []int) {
sum := 0
for i := 0; i < len(leftNums); i++ {
if leftNums[i] == 1 {
sum++
}
}
for i := 0; i < len(leftNums); i++ {
if i < sum {
leftNums[i] = 1
} else {
leftNums[i] = 0
}
}
}
func FindNumsByIndexes(nums []int, indexes [][]int) [][]int {
if len(indexes) == 0 {
return [][]int{}
}
result := make([][]int, len(indexes))
for i, v := range indexes {
line := make([]int, 0)
for j, v2 := range v {
if v2 == 1 {
line = append(line, nums[j])
}
}
result[i] = line
}
return result
}
func Substr(str string, start int, length int) string {
rs := []rune(str)
rl := len(rs)
end := 0
if start < 0 {
start = rl - 1 + start
}
end = start + length
if start > end {
start, end = end, start
}
if start < 0 {
start = 0
}
if start > rl {
start = rl
}
if end < 0 {
end = 0
}
if end > rl {
end = rl
}
return string(rs[start:end])
}
func Bargain(target, current, remaining int, seed int64) (new int, over bool) {
var step = 80
if current-target <= 0 {
return -1, true
}
if remaining < 0 {
return -1, true
} else if remaining == 0 {
return current - target, true
}
rd := rand.New(rand.NewSource(seed))
standard := float64(current-target) / float64(remaining) / 2
param := 1 + float64(rd.Intn(step))/100.0
result := standard * param
return int(result), false
} |
package resdb
import (
"context"
"github.com/airbloc/airframe/afclient"
)
type Model struct {
typ string
client afclient.Client
}
func NewModel(client afclient.Client, typ string) Model {
return Model{
typ: typ,
client: client,
}
}
func (m Model) Get(ctx context.Context, id string) (*afclient.Object, error) {
return m.client.Get(ctx, m.typ, id)
}
func (m Model) Put(ctx context.Context, id string, data afclient.M) (*afclient.PutResult, error) {
return m.client.Put(ctx, m.typ, id, data)
}
func (m Model) Query(ctx context.Context, query afclient.M, opts ...afclient.QueryOption) ([]*afclient.Object, error) {
return m.client.Query(ctx, m.typ, query, opts...)
}
|
package main
import (
"fmt"
"math"
"os"
"time"
TransposeMatrix "github.com/HungHan1230/GoTesting/TransposeMatrix"
MyTestingReadFile "github.com/HungHan1230/GoTesting/MyTestingReadFile"
)
func main() {
// mainTransposeMatrix()
// mainMyTestingReadFile()
testDate()
}
func mainTransposeMatrix() {
sample := [][]string{
[]string{"a1", "a2", "a3", "a4", "a5"},
[]string{"b1", "b2", "b3", "b4", "b5"},
[]string{"c1", "c2", "c3", "c4", "c5"},
}
ar := TransposeMatrix.Transpose(sample)
fmt.Println(ar)
}
func mainMyTestingReadFile() {
MyTestingReadFile.Run()
}
// exists returns whether the given file or directory exists
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func testDate() {
var t1 int64 = 1588181730
// var t2 int64 = 1589442289
var t2 int64 = 1588250008
unixTimeUTC1 := time.Unix(t1, 0) //gives unix time stamp in utc
unixTimeUTC2 := time.Unix(t2, 0) //gives unix time stamp in utc
fmt.Println("unix time stamp in UTC :--->", unixTimeUTC1)
fmt.Println("unix time stamp in UTC :--->", unixTimeUTC2)
diff := unixTimeUTC2.Sub(unixTimeUTC1)
fmt.Println("days: ", diff.Hours()/24)
fmt.Println("days: ", int(diff.Hours()/24))
fmt.Println("days: ", math.Ceil(diff.Hours()/24))
// dict := make(map[string]string)
// dict["1588181730"] = "1"
// dict["1588250008"] = "2"
// if val, ok := dict["1588181730_"]; ok {
// //do something here
// fmt.Println(val)
// }else{
// fmt.Println("found nothing")
// }
// layout := "2006-01-02 15:04:05"
// current_timestamp, err := time.Parse(layout, t1)
}
|
package core
type RepositoryDriver struct {
Factory *RepositoryCoreFactory
}
|
package core
import (
"errors"
_ "log"
)
// DcmMetaInfo is to store DICOM meta data.
type DcmMetaInfo struct {
Preamble []byte // length: 128
Prefix []byte // length: 4
Elements []DcmElement
isEndofMetaInfo bool
}
// ReadOneElement read one DICOM element in meta information.
func (meta *DcmMetaInfo) ReadOneElement(stream *DcmFileStream) error {
var elem DcmElement
elem.isReadValue = true
var err error
err = elem.ReadDcmTagGroup(stream)
if err != nil {
return err
}
if elem.Tag.Group != 0x0002 {
stream.Putback(2)
meta.isEndofMetaInfo = true
return nil
}
err = elem.ReadDcmTagElement(stream)
if err != nil {
return err
}
err = elem.ReadDcmVR(stream)
if err != nil {
return err
}
err = elem.ReadValueLengthWithExplicitVR(stream)
if err != nil {
return err
}
err = elem.ReadValue(stream)
if err != nil {
return err
}
// log.Println(elem)
meta.Elements = append(meta.Elements, elem)
return nil
}
// Read meta information from file stream
func (meta *DcmMetaInfo) Read(stream *DcmFileStream) error {
// turn to the beginning of the file
err := stream.SeekToBegin()
if err != nil {
return err
}
// read the preamble
meta.Preamble, err = stream.Read(128)
if err != nil {
return err
}
//read the prefix
meta.Prefix, err = stream.Read(4)
if err != nil {
return err
}
// read dicom meta datasets
for !stream.Eos() && !meta.isEndofMetaInfo {
err = meta.ReadOneElement(stream)
if err != nil {
return err
}
}
return nil
}
// IsExplicitVR is to check if the tag is Explicit VR structure
func (meta DcmMetaInfo) IsExplicitVR() (bool, error) {
uid, err := meta.getTransferSyntaxUID()
if err != nil {
return false, err
}
var xfer DcmXfer
xfer.XferID = uid
err = xfer.GetDcmXferByID()
if err != nil {
return false, err
}
return xfer.IsExplicitVR(), nil
}
// GetByteOrder get the byte orber of the file
func (meta DcmMetaInfo) GetByteOrder() (EByteOrder, error) {
uid, err := meta.getTransferSyntaxUID()
if err != nil {
return EBOunknown, err
}
var xfer DcmXfer
xfer.XferID = uid
err = xfer.GetDcmXferByID()
if err != nil {
return EBOunknown, err
}
return xfer.ByteOrder, nil
}
// FindElement get the element info by given tag
func (meta DcmMetaInfo) FindElement(e *DcmElement) error {
for _, v := range meta.Elements {
if e.Tag == v.Tag {
*e = v
return nil
}
}
str := "not find the tag '" + e.Tag.String() + "' in the data set"
return errors.New(str)
}
func (meta DcmMetaInfo) getElementValue(tag DcmTag) string {
var elem DcmElement
elem.Tag = tag
err := meta.FindElement(&elem)
if err != nil {
return ""
}
return elem.GetValueString()
}
func (meta DcmMetaInfo) getTransferSyntaxUID() (string, error) {
var elem DcmElement
elem.Tag = DCMTransferSyntaxUID
err := meta.FindElement(&elem)
if err != nil {
return "", err
}
return elem.GetValueString(), nil
}
// FileMetaInformationGroupLength gets meta information group length
func (meta DcmMetaInfo) FileMetaInformationGroupLength() string {
return meta.getElementValue(DCMFileMetaInformationGroupLength)
}
// FileMetaInformationVersion gets meta information version
func (meta DcmMetaInfo) FileMetaInformationVersion() string {
return meta.getElementValue(DCMFileMetaInformationVersion)
}
// MediaStorageSOPClassUID gets media storage SOP Class UID
func (meta DcmMetaInfo) MediaStorageSOPClassUID() string {
return meta.getElementValue(DCMMediaStorageSOPClassUID)
}
// MediaStorageSOPInstanceUID gets media storage SOP Instance UID
func (meta DcmMetaInfo) MediaStorageSOPInstanceUID() string {
return meta.getElementValue(DCMMediaStorageSOPInstanceUID)
}
// TransferSyntaxUID gets Transfer Syntax UID
func (meta DcmMetaInfo) TransferSyntaxUID() string {
return meta.getElementValue(DCMTransferSyntaxUID)
}
// ImplementationClassUID gets Implementation Class UID
func (meta DcmMetaInfo) ImplementationClassUID() string {
return meta.getElementValue(DCMImplementationClassUID)
}
// ImplementationVersionName gets implementation version name
func (meta DcmMetaInfo) ImplementationVersionName() string {
return meta.getElementValue(DCMImplementationVersionName)
}
// SourceApplicationEntityTitle gets source application entity title
func (meta DcmMetaInfo) SourceApplicationEntityTitle() string {
return meta.getElementValue(DCMSourceApplicationEntityTitle)
}
// SendingApplicationEntityTitle gets sending application entity title
func (meta DcmMetaInfo) SendingApplicationEntityTitle() string {
return meta.getElementValue(DCMSendingApplicationEntityTitle)
}
// ReceivingApplicationEntityTitle gets receiving application entity title
func (meta DcmMetaInfo) ReceivingApplicationEntityTitle() string {
return meta.getElementValue(DCMReceivingApplicationEntityTitle)
}
// PrivateInformationCreatorUID gets private information createor UID
func (meta DcmMetaInfo) PrivateInformationCreatorUID() string {
return meta.getElementValue(DCMPrivateInformationCreatorUID)
}
// PrivateInformation gets private information
func (meta DcmMetaInfo) PrivateInformation() string {
return meta.getElementValue(DCMPrivateInformation)
}
|
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/gosexy/redis"
"github.com/adarqui/fsnotify"
"github.com/adarqui/fsmonitor"
"log"
"os"
"os/exec"
"strconv"
"strings"
"regexp"
)
type ResqueArgs struct {
FilePath string `json:"filePath"`
Event string `json:"event"`
}
type ResquePacket struct {
Class string `json:"class"`
Args []ResqueArgs `json:"args"`
}
const (
DEST_REDIS = iota
DEST_LOCAL
)
const (
MASK_CREATE = 0x01
MASK_UPDATE = 0x02
MASK_DELETE = 0x04
MASK_RENAME = 0x08
MASK_CLOSE_WRITE = 0x10
)
type Watcher struct {
Dest string
Class string
Queue string
QueuePreFormatted string
Events string
Source string
Filter string
destType int
mask uint32
Redis *Redis
Local *Local
}
type Redis struct {
Host string
Port uint
red *redis.Client
}
type Local struct {
Base string
Bin string
}
type Opts struct {
debug int
}
var opts Opts
func usage() {
log.Fatal("usage: ./watchque-go [<redishost:port>|</path/to/bin/dir>] <Class1>:<Queue1>:<Events>:<Directory1,...,DirectoryN>[:filters] ... <ClassN>:<QueueN>:<Events>:<Directory1, ...,DirectoryN>[:filters] [optional flags: --debug=<1,2,3>]")
}
func ParseOption(arg string) {
switch arg {
case "--debug=1":
opts.debug = 1
case "--debug=2":
opts.debug = 2
case "--debug=3":
opts.debug = 3
case "--debug=off":
opts.debug = 0
}
}
func Parse(dest, arg string) ([]*Watcher, error) {
arr := make([]*Watcher, 0)
tokens := strings.Split(arg, ":")
if len(tokens) < 4 {
return nil, errors.New("Invalid argument")
}
class := tokens[0]
queue := tokens[1]
events := tokens[2]
sources := tokens[3]
destType := DEST_REDIS
filter := ""
/* quick hack, need ability to filter */
if len(tokens) > 4 {
filter = tokens[4]
}
/*
* Destination parsing: Redis vs Local scripts
*/
dest_tokens := strings.Split(dest, ":")
if len(dest_tokens) == 0 {
return nil, errors.New("Invalid destination: Specify a path or redis:port combo")
}
dest_0 := dest_tokens[0]
if dest_0[0] == '/' {
destType = DEST_LOCAL
}
/*
* Directory/file (sources) parsing. These sources are what we monitor for events
*/
dir_tokens := strings.Split(sources, ",")
if len(dir_tokens) <= 0 {
return nil, errors.New("Invalid source directories")
}
/*
* Event parsing: Events we care about can be c (create), u (update), d (delete) or a (c u d)
*/
var mask uint32 = 0
for _, event := range events {
switch event {
case 'c':
{
mask |= MASK_CREATE
}
case 'C':
{
mask |= MASK_CLOSE_WRITE
}
case 'u':
{
mask |= MASK_UPDATE
}
case 'd':
{
mask |= MASK_DELETE
}
case 'r':
{
mask |= MASK_RENAME
}
case 'a':
{
mask = MASK_CREATE | MASK_UPDATE | MASK_DELETE | MASK_RENAME | MASK_CLOSE_WRITE
}
default:
{
log.Fatal("Parse: Invalid event", event)
}
}
}
for _, source := range dir_tokens {
a := new(Watcher)
a.Dest = dest
a.Class = class
a.Queue = queue
a.QueuePreFormatted = fmt.Sprintf("resque:queue:%s", a.Queue)
a.Events = events
a.Source = source
a.Filter = filter
a.destType = destType
a.mask = mask
switch destType {
case DEST_REDIS:
{
a.Redis = new(Redis)
a.Redis.Host = dest_0
a.Redis.Port = 6379
if len(dest_tokens) > 1 {
ui, _ := strconv.Atoi(dest_tokens[1])
a.Redis.Port = uint(ui)
}
}
case DEST_LOCAL:
{
a.Local = new(Local)
a.Local.Base = dest
a.Local.Bin = fmt.Sprintf("%s/%s/%s", dest, a.Class, a.Queue)
}
default:
{
return nil, errors.New("Invalid destination: Specify a path or redis:port combo")
}
}
arr = append(arr, a)
}
return arr, nil
}
/*
* Checks to see if we have this event in our mask. If so, return true & the string translation of the event type
*/
func isDesiredEvent(mask uint32, ev *fsnotify.FileEvent) (bool, string) {
if (mask&MASK_CREATE > 0) && ev.IsCreate() {
return true, "CREATE"
} else if (mask&MASK_CLOSE_WRITE > 0) && ev.IsCloseWrite() {
return true, "CLOSE_WRITE"
} else if (mask&MASK_DELETE > 0) && ev.IsDelete() {
return true, "DELETE"
} else if (mask&MASK_UPDATE > 0) && ev.IsModify() {
return true, "UPDATE"
} else if (mask&MASK_RENAME > 0) && ev.IsRename() {
return true, "RENAME"
}
return false, "UNDESIRED"
}
func (this *Watcher) Dump() {
Debug(1, "Dest=%s, Class=%s, Queue=%s, Events=%s, Source=%s, destType=%i, mask=%i\n",
this.Dest,
this.Class,
this.Queue,
this.Events,
this.Source,
this.destType,
this.mask)
}
func Launch(watchers []*Watcher) {
ch := make(chan *fsnotify.FileEvent, 255)
go watchers[0].Transponder(ch)
for _, watcher := range watchers {
go watcher.Launch(ch)
}
}
func (this *Watcher) Transponder(ch chan *fsnotify.FileEvent) {
switch this.destType {
case DEST_REDIS:
this.TransponderRedis(ch)
case DEST_LOCAL:
this.TransponderLocal(ch)
default:
{
log.Fatal("Transponder: Unknown transponder type")
}
}
}
func (this *Watcher) TransponderRedis(ch chan *fsnotify.FileEvent) {
DebugLn(2, "TransponderRedis: Entered")
this.Redis.red = redis.New()
err := this.Redis.red.Connect(this.Redis.Host, this.Redis.Port)
if err != nil {
log.Fatal("TransponderRedis: Connect failed: %s\n", err.Error())
}
/* Quick and dirty sadd.. want to add this to a per minute/per 30s interval. No need to sadd every time we rpush */
this.Redis.red.SAdd("resque:queues", this.Queue)
for ev := range ch {
boo, event := isDesiredEvent(this.mask, ev)
if boo == false {
Debug(3, "%v -> %s : Enqueue to: Queue=%s\n", event, ev.Name, this.Queue)
continue
}
/* Check against filters */
if this.Filter != "" {
truth, err := regexp.MatchString(this.Filter, ev.Name)
if truth == false || err != nil {
Debug(3, "%v -> %s : FAIL MATCH : Filter=%s", event, ev.Name, this.Filter)
continue
}
}
rpkt := ResquePacket{}
rpkt.Class = this.Class
rpkt.Args = make([]ResqueArgs, 1)
rpkt.Args[0].FilePath = ev.Name
rpkt.Args[0].Event = event
Debug(1, "%v -> %s : Enqueue to: Queue=%s Class=%s\n", event, ev.Name, this.Queue, rpkt.Class)
js, err := json.Marshal(&rpkt)
if err != nil {
log.Println(err)
}
_, _ = this.Redis.red.RPush(this.QueuePreFormatted, string(js))
}
}
func (this *Watcher) TransponderLocal(ch chan *fsnotify.FileEvent) {
Debug(2, "TransponderLocal: Entered")
for ev := range ch {
Debug(3, "TransponderLocal: Received event: %v\n", ev)
boo, event := isDesiredEvent(this.mask, ev)
if boo == false {
Debug(3, "TransponderLocal: Received undesired event: %v %s\n", ev, event)
continue
}
cmd := exec.Command(this.Local.Bin, event, this.Class, this.Queue, ev.Name)
err := cmd.Start()
if err != nil {
log.Printf("TransponderLocal: Error executing %s\n", this.Local.Bin)
continue
}
Debug(1, "TransponderLocal: Executed %s\n", this.Local.Bin)
}
}
func (this *Watcher) Launch(ch chan *fsnotify.FileEvent) {
this.Dump()
mon, err := fsmonitor.NewWatcher()
if err != nil {
log.Fatal("Launch:fsmonitor.NewWatcher:Error:", err)
}
err = mon.Watch(this.Source)
if err != nil {
log.Fatal("Launch:mon.Watch:Error:", err)
}
for {
ev := <-mon.Event
Debug(3, "Launch: Received event: %v\n", ev)
ch <- ev
}
}
func main() {
if len(os.Args) < 3 {
usage()
}
dest := os.Args[1]
arr := make([][]*Watcher, 0)
for k, arg := range os.Args {
if k <= 1 {
continue
}
/*
* Crude option processing
*/
if strings.HasPrefix(arg, "--") == true {
ParseOption(arg)
continue
}
watchers, err := Parse(dest, arg)
if err != nil {
log.Fatal(err)
}
arr = append(arr, watchers)
}
for _, watchers := range arr {
go Launch(watchers)
}
select {}
}
|
package oiio
import (
"fmt"
"os"
"path/filepath"
"testing"
)
var (
OCIO_CONFIG_PATH string
)
func init() {
// Set the environment to file-based test data config
pwd, _ := os.Getwd()
pwd, _ = filepath.Abs(pwd)
OCIO_CONFIG_PATH = filepath.Join(pwd, "testdata/spi-vfx/config.ocio")
if _, err := os.Stat(OCIO_CONFIG_PATH); os.IsNotExist(err) {
panic(fmt.Sprintf("%s not found\n", OCIO_CONFIG_PATH))
} else {
os.Setenv("OCIO", OCIO_CONFIG_PATH)
}
}
func TestNewColorConfig(t *testing.T) {
if !SupportsOpenColorIO() {
t.SkipNow()
}
cfg, err := NewColorConfig()
if err != nil {
t.Fatal(err)
}
checkConfig(t, cfg)
}
func TestNewColorConfigPath(t *testing.T) {
if !SupportsOpenColorIO() {
t.SkipNow()
}
_, err := NewColorConfigPath(OCIO_CONFIG_PATH)
if err != nil {
t.Error(err)
}
}
func checkConfig(t *testing.T, cfg *ColorConfig) {
expected := 20
actual := cfg.NumColorSpaces()
if expected != actual {
t.Errorf("Expected number of colorspaces == %v; got %v", expected, actual)
}
expected = 1
actual = cfg.NumLooks()
if expected != actual {
t.Errorf("Expected number of looks == %v; got %v", expected, actual)
}
expected = 2
actual = cfg.NumDisplays()
if expected != actual {
t.Errorf("Expected number of displays == %v; got %v", expected, actual)
}
expected = 3
actual = cfg.NumViews("sRGB")
if expected != actual {
t.Errorf("Expected number of views for sRGB == %v; got %v", expected, actual)
}
cs_expect := "vd8"
cs_actual := cfg.ColorSpaceNameByRole("matte_paint")
if cs_expect != cs_actual {
t.Errorf("Expected ColorSpace for role 'matte_paint' == %v; got %v", cs_expect, cs_actual)
}
for i, cs_expect := range []string{"lnf", "lnh", "ln16", "lg16"} {
cs_actual = cfg.ColorSpaceNameByIndex(i)
if cs_expect != cs_actual {
t.Errorf("Expected ColorSpace for index %d == %v; got %v", i, cs_expect, cs_actual)
}
}
look_expect := "di"
look_actual := cfg.LookNameByIndex(0)
if look_actual != look_expect {
t.Errorf("Expected Look for index 0 == %v; got %v", look_expect, look_actual)
}
for i, disp_expect := range []string{"DCIP3", "sRGB"} {
disp_actual := cfg.DisplayNameByIndex(i)
if disp_expect != disp_actual {
t.Errorf("Expected Display for index %d == %v; got %v", i, disp_expect, disp_actual)
}
}
for i, view_expect := range []string{"Film", "Log", "Raw"} {
view_actual := cfg.ViewNameByIndex("sRGB", i)
if view_actual != view_expect {
t.Errorf("Expected Look for display sRGB at index %d == %v; got %v", i, view_expect, view_actual)
}
}
}
func TestNewColorProcessor(t *testing.T) {
if !SupportsOpenColorIO() {
t.SkipNow()
}
cfg, err := NewColorConfig()
if err != nil {
t.Fatal(err)
}
_, err = cfg.CreateColorProcessor("lnf", "vd8")
if err != nil {
t.Error(err.Error())
}
}
|
package app
import (
"net/http"
"github.com/hsson/armit-website/app/handlers"
)
type Route struct {
Name string
Method string
Pattern string
Authed bool
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
false,
handlers.Index,
},
Route{
"Secured",
"GET",
"/secured",
true,
handlers.SecuredPage,
},
Route{
"Partners",
"GET",
"/partners",
false,
handlers.Partners,
},
Route{
"Partner",
"GET",
"/partners/{id:[0-9]+}",
false,
handlers.Partner,
},
}
|
package parser
import (
"strings"
"testing"
"github.com/jessejohnston/ProductIngester/product"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
type parserTestSuite struct {
suite.Suite
converter Converter
}
func Test_Parser(t *testing.T) {
s := new(parserTestSuite)
suite.Run(t, s)
}
func (s *parserTestSuite) SetupSuite() {
s.converter, _ = product.NewConverter(NumberFieldLength, CurrencyFieldLength, FlagsFieldLength)
}
func (s *parserTestSuite) Test_NewParser_NoInput_ReturnsError() {
t := s.T()
_, err := New(nil, s.converter)
require.Error(t, err)
require.Equal(t, ErrBadParameter, errors.Cause(err))
}
func (s *parserTestSuite) Test_NewParser_NoConverter_ReturnsError() {
t := s.T()
reader := strings.NewReader("the record")
_, err := New(reader, nil)
require.Error(t, err)
require.Equal(t, ErrBadParameter, errors.Cause(err))
}
func (s *parserTestSuite) Test_ParseRecord_NilRecord_ReturnsError() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
_, err := p.ParseRecord(1, nil)
require.Error(t, err)
require.Equal(t, ErrBadParameter, errors.Cause(err))
}
func (s *parserTestSuite) Test_ParseRecord_ShortRecord_ReturnsError() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("80000001 Kimchi-flavored white rice 00000567 00000000 00000000 00000000 00000000 00000000 NNNN")
_, err := p.ParseRecord(1, row)
require.Error(t, err)
require.Equal(t, ErrBadParameter, errors.Cause(err))
}
func (s *parserTestSuite) Test_ParseRecord_LongRecord_ReturnsError() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("80000001 Kimchi-flavored white rice 00000567 00000000 00000000 00000000 00000000 00000000 NNNNNNNNN 18ozzzzzz")
_, err := p.ParseRecord(1, row)
require.Error(t, err)
require.Equal(t, ErrBadParameter, errors.Cause(err))
}
func (s *parserTestSuite) Test_ParseRecord_SingularPrice_NoPromoPrice_PriceIsSingularPrice() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("80000001 Kimchi-flavored white rice 00000567 00000000 00000000 00000000 00000000 00000000 NNNNNNNNN 18oz")
r, err := p.ParseRecord(1, row)
require.NoError(t, err)
expectedPrice, _ := decimal.NewFromString("5.67")
require.True(t, r.Price.Equals(expectedPrice))
require.True(t, r.PromoPrice.Equals(decimal.Zero))
}
func (s *parserTestSuite) Test_ParseRecord_SingularPromoPrice_SplitPrice_PriceIsSplitPrice_PromoPriceIsSingularPrice() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("14963801 Generic Soda 12-pack 00000000 00000549 00001300 00000000 00000002 00000000 NNNNYNNNN 12x12oz")
r, err := p.ParseRecord(1, row)
require.NoError(t, err)
expectedPrice, _ := decimal.NewFromString("6.50")
require.True(t, r.Price.Equals(expectedPrice))
expectedPromoPrice, _ := decimal.NewFromString("5.49")
require.True(t, r.PromoPrice.Equals(expectedPromoPrice))
}
func (s *parserTestSuite) Test_ParseRecord_SingularPrice_SplitPromoPrice_PriceIsSingularPrice_PromoPriceIsSplitPrice() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("14963801 Generic Soda 12-pack 00000549 00000000 00000000 00001000 00000000 00000002 NNNNYNNNN 12x12oz")
r, err := p.ParseRecord(1, row)
require.NoError(t, err)
expectedPrice, _ := decimal.NewFromString("5.49")
require.True(t, r.Price.Equals(expectedPrice))
expectedPromoPrice, _ := decimal.NewFromString("5.00")
require.True(t, r.PromoPrice.Equals(expectedPromoPrice))
}
func (s *parserTestSuite) Test_ParseRecord_SingularPrice_SingularPromoPrice_PriceIsSingularPrice() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("40123401 Marlboro Cigarettes 00001000 00000549 00000000 00000000 00000000 00000000 YNNNNNNNN ")
r, err := p.ParseRecord(1, row)
require.NoError(t, err)
expectedPrice, _ := decimal.NewFromString("10.00")
require.True(t, r.Price.Equals(expectedPrice))
expectedPromoPrice, _ := decimal.NewFromString("5.49")
require.True(t, r.PromoPrice.Equals(expectedPromoPrice))
}
func (s *parserTestSuite) Test_ParseRecord_PerWeightFlagNotSet_HasEachUnitOfMeasure() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("40123401 Marlboro Cigarettes 00001000 00000549 00000000 00000000 00000000 00000000 YNNNNNNNN ")
r, err := p.ParseRecord(1, row)
require.NoError(t, err)
require.Equal(t, product.UnitEach, r.Unit)
}
func (s *parserTestSuite) Test_ParseRecord_PerWeightFlagSet_HasPoundUnitOfMeasure() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("50133333 Fuji Apples (Organic) 00000349 00000000 00000000 00000000 00000000 00000000 NNYNNNNNN lb")
r, err := p.ParseRecord(1, row)
require.NoError(t, err)
require.Equal(t, product.UnitPound, r.Unit)
}
func (s *parserTestSuite) Test_ParseRecord_TaxableFlagNotSet_HasZeroTaxRate() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("80000001 Kimchi-flavored white rice 00000567 00000000 00000000 00000000 00000000 00000000 NNNNNNNNN 18oz")
r, err := p.ParseRecord(1, row)
require.NoError(t, err)
require.Equal(t, decimal.Zero, r.TaxRate)
}
func (s *parserTestSuite) Test_ParseRecord_TaxableFlagSet_HasTaxRate() {
t := s.T()
reader := strings.NewReader("the file")
p, _ := New(reader, s.converter)
row := []byte("14963801 Generic Soda 12-pack 00000000 00000549 00001300 00000000 00000002 00000000 NNNNYNNNN 12x12oz")
r, err := p.ParseRecord(1, row)
require.NoError(t, err)
expectedTaxRate := decimal.NewFromFloat32(TaxRate)
require.Equal(t, expectedTaxRate, r.TaxRate)
}
func (s *parserTestSuite) Test_Parse_ReturnsAllRecords() {
t := s.T()
reader := strings.NewReader(
"80000001 Kimchi-flavored white rice 00000567 00000000 00000000 00000000 00000000 00000000 NNNNNNNNN 18oz\n" +
"14963801 Generic Soda 12-pack 00000000 00000549 00001300 00000000 00000002 00000000 NNNNYNNNN 12x12oz\n" +
"40123401 Marlboro Cigarettes 00001000 00000549 00000000 00000000 00000000 00000000 YNNNNNNNN \n" +
"50133333 Fuji Apples (Organic) 00000349 00000000 00000000 00000000 00000000 00000000 NNYNNNNNN lb")
p, _ := New(reader, s.converter)
records, errors, done := p.Parse()
require.NotNil(t, records)
require.NotNil(t, errors)
require.NotNil(t, done)
var results []*product.Record
for {
select {
case <-errors:
t.FailNow()
case r := <-records:
results = append(results, r)
case <-done:
goto finished
}
}
finished:
require.Len(t, results, 4)
require.Equal(t, 80000001, results[0].ID)
require.Equal(t, 14963801, results[1].ID)
require.Equal(t, 40123401, results[2].ID)
require.Equal(t, 50133333, results[3].ID)
}
func (s *parserTestSuite) Test_Parse_BadRecord_ReturnsOtherRecords_AndError() {
t := s.T()
reader := strings.NewReader(
"80000001 Kimchi-flavored white rice 00000567 00000000 00000000 00000000 00000000 00000000 NNNNNNNNN 18oz\n" +
"14963801 Generic Soda 12-pack 00000000 00000549 00001300 00000000 00000002 00000000 NNNNYNNNN 12x12oz\n" +
"40123401 Marlboro Cigare\n" +
"50133333 Fuji Apples (Organic) 00000349 00000000 00000000 00000000 00000000 00000000 NNYNNNNNN lb")
p, _ := New(reader, s.converter)
records, errors, done := p.Parse()
require.NotNil(t, records)
require.NotNil(t, errors)
require.NotNil(t, done)
var results []*product.Record
var errs []error
for {
select {
case e := <-errors:
errs = append(errs, e)
case r := <-records:
results = append(results, r)
case <-done:
goto finished
}
}
finished:
require.Len(t, results, 3)
require.Equal(t, 80000001, results[0].ID)
require.Equal(t, 14963801, results[1].ID)
require.Equal(t, 50133333, results[2].ID)
require.Len(t, errs, 1)
}
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strconv"
"strings"
)
type vertex struct {
f int
explored bool
scc int
}
var curLabel, numSCC int
// Input: directed acyclic graph G = (V, E) in
// adjacency-list representation.
// Postcondition: the f -values of vertices constitute a
// topological ordering of G.
func topoSort(edges map[int][]int, vertices map[int]*vertex) {
curLabel = len(vertices)
for k, v := range vertices {
if !v.explored {
dFSTopo(edges, vertices, k)
}
}
}
// Input: graph G = (V, E) in adjacency-list
// representation, and a vertex s in V .
// Postcondition: every vertex reachable from s is
// marked as “explored” and has an assigned f -value.
func dFSTopo(edges map[int][]int, vertices map[int]*vertex, s int) {
vertices[s].explored = true
for _, v := range edges[s] {
if !vertices[v].explored {
dFSTopo(edges, vertices, v)
}
}
vertices[s].f = curLabel
curLabel--
}
// Input: directed graph G = (V, E) in adjacency-list
// representation, and a vertex s in V .
// Postcondition: every vertex reachable from s is
// marked as “explored” and has an assigned scc-value.
func dFSSCC(edges map[int][]int, vertices map[int]*vertex, s int) {
vertices[s].explored = true
// scc(s) := numSCC // global variable above
vertices[s].scc = numSCC
for _, v := range edges[s] {
if !vertices[v].explored {
dFSSCC(edges, vertices, v)
}
}
}
// Kosaraju detects the strongly connected components of a directed graph.
//
// Input: directed graph G = (V, E) in adjacency-list
// representation, with V = {1, 2, 3, . . . , n}
// Postcondition: for every v, w in V , scc(v) = scc(w)
// if and only if v, w are in the same SCC of G.
func Kosaraju(edges, edgesRev map[int][]int, vertices map[int]*vertex) []int {
// first pass of depth-first search
// (computes f (v)’s, the magical ordering)
topoSort(edgesRev, vertices)
// second pass of depth-first search
// (finds SCCs in reverse topological order)
// create an array with the elements in increasing f(v) order
order := make([]int, len(vertices))
for k, v := range vertices {
order[v.f-1] = k
}
// mark all vertices of G as unexplored
for k := range vertices {
vertices[k].explored = false
}
for _, v := range order {
if !vertices[v].explored {
numSCC++
dFSSCC(edges, vertices, v)
}
}
// calculate SCC sizes
sccs := make(map[int]int)
for _, v := range vertices {
if _, ok := sccs[v.scc]; ok {
sccs[v.scc]++
} else {
sccs[v.scc] = 1
}
}
// enter sizes in an array and sort
sccSizes := make([]int, len(sccs))
for _, v := range sccs {
sccSizes = append(sccSizes, v)
}
sort.Ints(sccSizes)
return sccSizes
}
func main() {
if len(os.Args) < 2 {
log.Fatal("file argument missing")
}
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
edges := make(map[int][]int)
vertices := make(map[int]*vertex)
for scanner.Scan() {
if strings.TrimSpace(scanner.Text()) == "" {
continue
}
line := strings.Split(strings.TrimSpace(scanner.Text()), " ")
nums := make([]int, 2)
for i := range line {
nums[i], err = strconv.Atoi(line[i])
if err != nil {
log.Fatal(err)
}
}
// enter vertices in the vertices map
for _, v := range nums {
if _, ok := vertices[v]; !ok {
vertices[v] = &vertex{0, false, 0}
}
}
// enter relationships between vertices in the edges map
if _, ok := edges[nums[0]]; ok {
edges[nums[0]] = append(edges[nums[0]], nums[1])
} else {
edges[nums[0]] = nums[1:]
}
}
// create reversed edges map
edgesRev := make(map[int][]int)
for k, v := range edges {
for _, e := range v {
if _, ok := edgesRev[e]; ok {
edgesRev[e] = append(edgesRev[e], k)
} else {
edgesRev[e] = []int{k}
}
}
}
sccSizes := Kosaraju(edges, edgesRev, vertices)
fmt.Println(sccSizes)
}
|
package dal
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var (
DB *gorm.DB
)
func InitDB() {
var err error
// {user}:{password}@tcp({ip:port})/{database_name}?charset=utf8mb4&parseTime=True&loc=Local
dsn := "root:root_password@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
}
|
package oss_test
import (
"github.com/caarlos0/env"
. "web-layout/utils/aliyun/oss"
)
func getClient() (*Client, error) {
cfg := Config{}
if err := env.Parse(&cfg); err != nil {
return nil, err
}
return NewClient(cfg)
}
|
package main
import (
"fmt"
"sync"
)
var greetings string
var howdyDone chan bool
var mutex = &sync.Mutex{}
func howdyGreetings() {
mutex.Lock()
greetings = "Howdy Gopher!"
mutex.Unlock()
howdyDone <- true
}
func main() {
howdyDone = make(chan bool, 1)
go howdyGreetings()
mutex.Lock()
greetings = "Hello Gopher!"
fmt.Println(greetings)
mutex.Unlock()
<-howdyDone
}
|
package order_notify
import (
"context"
"fmt"
"strings"
"time"
"tpay_backend/utils"
"tpay_backend/payapi/internal/svc"
"github.com/tal-tech/go-zero/core/logx"
)
type ListenExpKeyHandler struct {
logx.Logger
svcCtx *svc.ServiceContext
}
func NewListenExpKeyHandler(svcCtx *svc.ServiceContext) *ListenExpKeyHandler {
return &ListenExpKeyHandler{
svcCtx: svcCtx,
}
}
// 开始监听过期的key
func (l *ListenExpKeyHandler) ListenRedisExpKey() {
logx.Info("开始监听redis...")
go l.subscribeExpireKey()
}
// 监听redis过期key事件
func (l *ListenExpKeyHandler) subscribeExpireKey() {
pubSub := l.svcCtx.Redis.PSubscribe(context.TODO(), fmt.Sprintf("__keyevent@%v__:expired", utils.RedisDbPayapi))
defer pubSub.Close()
for {
msg, err := pubSub.ReceiveMessage(context.TODO())
if err != nil {
logx.Errorf("获取订阅过期key出错,err:%v", err)
time.Sleep(time.Millisecond * 500) // 出错时稍微等待
continue
}
l.handleExpireKeyEvent(msg.Channel, msg.Pattern, msg.Payload)
}
}
// 处理过期key事件
func (l *ListenExpKeyHandler) handleExpireKeyEvent(channel, pattern, payload string) {
logx.Infof("ListenRedisExpKey()获的一条过期数据-----payload:%s", payload)
expireKeys := strings.Split(payload, "_")
if len(expireKeys) != 2 {
return
}
key := expireKeys[0]
if key == "" {
return
}
orderNo := expireKeys[1]
if orderNo == "" {
return
}
var notifyObj Notify
switch key {
case PayNotifyExpireKey:
notifyObj = NewPayOrderNotify(context.TODO(), l.svcCtx)
case TransferNotifyExpireKey:
notifyObj = NewTransferOrderNotify(context.TODO(), l.svcCtx)
default:
return
}
lockKey := GetLockKey(orderNo)
lockValue := utils.NewUUID()
// 获取分布式锁
if !utils.GetDistributedLock(l.svcCtx.Redis, lockKey, lockValue, 30*time.Second) {
return
}
notifyObj.OrderNotify(orderNo)
// 释放分布式锁
utils.ReleaseDistributedLock(l.svcCtx.Redis, lockKey, lockValue)
}
|
package leetcode
import (
"strings"
)
// Given a pattern and a string str, find if str follows the same pattern.
// Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
// Input: pattern = "abba", str = "dog cat cat dog"
// Output: true
// Input:pattern = "abba", str = "dog cat cat fish"
// Output: false
// You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.
func wordPattern(pattern string, str string) bool {
rMap := make(map[rune]*string)
wMap := make(map[string]*rune)
runes := []rune(pattern)
words := strings.Split(str, " ")
if len(runes) != len(words) {
return false
}
for i, r := range runes {
if rMap[r] == nil {
if wMap[words[i]] != nil {
return false
}
rMap[r] = &words[i]
wMap[words[i]] = &r
} else if *rMap[r] != words[i] {
return false
}
}
return true
}
|
package values
import (
"context"
"fmt"
"github.com/giantswarm/apiextensions-application/api/v1alpha1"
"github.com/giantswarm/microerror"
"github.com/imdario/mergo"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/giantswarm/app/v7/pkg/key"
)
// MergeSecretData merges the data from the catalog, app, user and extra config secrets
// and returns a single set of values.
func (v *Values) MergeSecretData(ctx context.Context, app v1alpha1.App, catalog v1alpha1.Catalog) (map[string]interface{}, error) {
appSecretName := key.AppSecretName(app)
catalogSecretName := key.CatalogSecretName(catalog)
userSecretName := key.UserSecretName(app)
extraConfigs := key.ExtraConfigs(app)
if appSecretName == "" && catalogSecretName == "" && userSecretName == "" && len(extraConfigs) == 0 {
// Return early as there is no secret.
return nil, nil
}
// We get the catalog level secrets if configured.
rawCatalogData, err := v.getSecretDataForCatalog(ctx, catalog)
if err != nil {
return nil, microerror.Mask(err)
}
catalogData, err := extractData(secret, "catalog", toStringMap(rawCatalogData))
if err != nil {
return nil, microerror.Mask(err)
}
if catalogData == nil {
// If there is no catalog data then treat it as an empty map otherwise `mergo.Merge` will silently
// fail to merge the first layers: `dst = nil; mergo.Merge(dst, MAP_OF_DATA)` and `dst` is still nil
catalogData = map[string]interface{}{}
}
// Pre cluster extra secrets
err = v.fetchAndMergeExtraConfigs(ctx, getPreClusterExtraSecretEntries(extraConfigs), v.getSecretAsString, catalogData)
if err != nil {
return nil, err
}
// We get the app level secrets if configured.
rawAppData, err := v.getSecretDataForApp(ctx, app)
if err != nil {
return nil, microerror.Mask(err)
}
appData, err := extractData(secret, "app", toStringMap(rawAppData))
if err != nil {
return nil, microerror.Mask(err)
}
// Secrets are merged and in case of intersecting values the app level
// secrets are preferred.
err = mergo.Merge(&catalogData, appData, mergo.WithOverride)
if err != nil {
return nil, microerror.Mask(err)
}
// Post cluster / pre user extra secrets
err = v.fetchAndMergeExtraConfigs(ctx, getPostClusterPreUserExtraSecretEntries(extraConfigs), v.getSecretAsString, catalogData)
if err != nil {
return nil, err
}
// We get the user level values if configured and merge them.
if userSecretName != "" {
rawUserData, err := v.getUserSecretDataForApp(ctx, app)
if err != nil {
return nil, microerror.Mask(err)
}
// Secrets are merged again and in case of intersecting values the user
// level secrets are preferred.
userData, err := extractData(secret, "user", toStringMap(rawUserData))
if err != nil {
return nil, microerror.Mask(err)
}
err = mergo.Merge(&catalogData, userData, mergo.WithOverride)
if err != nil {
return nil, microerror.Mask(err)
}
}
// Post user extra secrets
err = v.fetchAndMergeExtraConfigs(ctx, getPostUserExtraSecretEntries(extraConfigs), v.getSecretAsString, catalogData)
if err != nil {
return nil, err
}
return catalogData, nil
}
func (v *Values) getSecretAsString(ctx context.Context, secretName, secretNamespace string) (map[string]string, error) {
data, err := v.getSecret(ctx, secretName, secretNamespace)
if err != nil {
return nil, err
}
return toStringMap(data), nil
}
func (v *Values) getSecret(ctx context.Context, secretName, secretNamespace string) (map[string][]byte, error) {
if secretName == "" {
// Return early as no secret has been specified.
return nil, nil
}
v.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("looking for secret %#q in namespace %#q", secretName, secretNamespace))
secret, err := v.k8sClient.CoreV1().Secrets(secretNamespace).Get(ctx, secretName, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
return nil, microerror.Maskf(notFoundError, "secret %#q in namespace %#q not found", secretName, secretNamespace)
} else if err != nil {
return nil, microerror.Mask(err)
}
v.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("found secret %#q in namespace %#q", secretName, secretNamespace))
return secret.Data, nil
}
func (v *Values) getSecretDataForApp(ctx context.Context, app v1alpha1.App) (map[string][]byte, error) {
secret, err := v.getSecret(ctx, key.AppSecretName(app), key.AppSecretNamespace(app))
if err != nil {
return nil, microerror.Mask(err)
}
return secret, nil
}
func (v *Values) getSecretDataForCatalog(ctx context.Context, catalog v1alpha1.Catalog) (map[string][]byte, error) {
secret, err := v.getSecret(ctx, key.CatalogSecretName(catalog), key.CatalogSecretNamespace(catalog))
if err != nil {
return nil, microerror.Mask(err)
}
return secret, nil
}
func (v *Values) getUserSecretDataForApp(ctx context.Context, app v1alpha1.App) (map[string][]byte, error) {
secret, err := v.getSecret(ctx, key.UserSecretName(app), key.UserSecretNamespace(app))
if err != nil {
return nil, microerror.Mask(err)
}
return secret, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.