Commit 78f1c240 by wang

删除无用的

parent 48a132a4
package main
import (
"fmt"
"github.com/tidwall/gjson"
"math"
"os"
"reflect"
)
func main() {
path,_:=os.Getwd()
fmt.Print(path)
return
json := `{"supplier_id":"10000","brand_id":[1,2],"start_time":1600790400,"end_time":1606492800,"ratio":"75","allow_coupon":1,"is_part":1,"visible_roster":"","sign_name":"","activity_ad":"","activity_id":86,"blacklist_type":null,"activity_type":"1","class_id":"","canal":""}`
s := gjson.Get(json,"brand_id").Array()
d := make([]string,0)
for _,a := range s {
c := a.String()
d = append(d,c)
fmt.Print(c,reflect.TypeOf(c))
}
//flag := php2go.InArray(1,d)
//flag := php2go.InArray("1",[]string{"1","2"})
// fmt.Print(d,flag)
}
/*
四舍五入取多少位
@param float64 x 目标分析字符串
@param int wei 取小数多少位
*/
func MyRound(x float64,wei int) float64{
if wei == 0 {
return math.Floor(x + 0.5)
}
weis := map[int]float64{
1:10,
2:100,
3:1000,
4:10000,
5:100000,
6:1000000,
}
weishu := weis[wei]
a := math.Floor(x*weishu + 0.5)/weishu
return a
}
/*
go通道选择 Select
go 的select关键字可以让你同时等待多个通道操作
将协程
通道和select结合起来构成了go的一个强大特性
*/
package main
import (
"fmt"
"github.com/syyongx/php2go"
"time"
)
func main() {
c1 := make(chan string)
go func() {
fmt.Println(php2go.Time())
time.Sleep(time.Second * 1)
c1 <- "one"
}()
go func() {
fmt.Println(php2go.Time())
time.Sleep(time.Second * 2)
c1 <- "two"
}()
go func() {
fmt.Println(php2go.Time())
time.Sleep(time.Second * 10)
c1 <- "10"
}()
/*
如我们所期望的 程序输出了正确的值 对于select语句而言
它不断地检测通道是否有值过来 一旦有值过来立刻获取输出
*/
//我们使用select来等待通道的值 然后输出
for i := 0; i < 3; i++ {
select {
case x := <-c1:
fmt.Println(x)
case <- time.After(time.Second *2):
fmt.Println("read time out")
}
}
}
\ No newline at end of file
package main
import (
"errors"
"fmt"
"time"
)
func main() {
// 构建一个通道
ch := make(chan string)
// 开启一个并发匿名函数
go func() {
ch <- "gagagagagga111"
}()
go func() {
ch <- "gagagagagga223"
}()
go func() {
time.Sleep(1*time.Second)
ch <- "gagagagagga44444"
}()
//无限循环从通道中读取数据
for {
i,err := ReadWithSelect(ch)
//i, ok := <-ch
if err != nil {
fmt.Println(err)
break
}
fmt.Println(i)
}
}
//使用Select+超时改善无阻塞读写
func ReadWithSelect(ch chan string) (x string, err error) {
timeout := time.NewTimer(time.Microsecond * 50000).C //等待5s
select {
case x = <-ch:
return x, nil
case <-timeout.C:
return "", errors.New("read time out")
}
}
func WriteChWithSelect(ch chan int) error {
timeout := time.NewTimer(time.Microsecond * 500)
select {
case ch <- 1:
return nil
case <-timeout.C:
return errors.New("write time out")
}
}
package main
import "fmt"
func main() {
funtest3(funtest)
}
func funtest3( a func(s string)) {
a("123123")
}
func funtest(s string) {
fmt.Print(s)
}
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"runtime"
"strings"
"sync/atomic"
)
var Context *gin.Context
var REQUEST atomic.Value //等同于php 的$_REQUEST,只接收非数组值
type request123 map[string]string
//将gin的上下文放到全局变量
func ContextVars() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Print("nni")
//接收所有的变量+值
REQUEST123 := make(request123)
c.MultipartForm()
for requestName, requstValue := range c.Request.Form {
REQUEST123[requestName] = strings.TrimSpace(requstValue[0])
}
REQUEST.Store(&REQUEST123)
////将gin的上下文放到全局变量
Context = c
c.Next()
}
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
//初始化引擎
r := gin.Default()
r.Use(ContextVars())
r.POST("/user", func(c *gin.Context) {
//name := c.Request.FormValue("name")
d := c.Request.FormValue("power[fast]")
//agc := REQUEST.Load().(*request123)
//fmt.Print((*agc)["name"])
//fmt.Print(&REQUEST)
c.String(http.StatusOK, "Hello %s", d)
})
r.GET("/user", func(c *gin.Context) {
//name := c.Request.MultipartForm.Value["name"]
name := c.Request.FormValue("name")
//agc := REQUEST.Load().(*request123)
//fmt.Print((*agc)["name"])
//fmt.Print(&REQUEST)
c.String(http.StatusOK, "Hello %s", name)
})
r.Run(":9100") // listen and serve on 0.0.0.0:8080
}
\ No newline at end of file
package main
import (
json2 "encoding/json"
"fmt"
"sync"
)
func main() {
// 关键人物出场
var scene sync.Map
// 将键值对保存到sync.Map
scene.Store("greece", 97)
scene.Store("london", 100)
scene.Store("egypt", 200)
// 从sync.Map中根据键取值
fmt.Println(scene.Load("london"))
// 根据键删除对应的键值对
scene.Delete("london")
// 遍历所有sync.Map中的键值对
temp := make(map[string]interface{})
scene.Range(func(k, v interface{}) bool {
fmt.Println("iterate:", k, v)
s,_ := k.(string)
temp[s] = v
return true
})
fmt.Print(temp)
dd,error := json2.Marshal(temp)
fmt.Print(error,string(dd))
}
File mode changed
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"strings"
)
func Sha1(query string, pri_key string) string {
key := []byte(pri_key)
mac := hmac.New(sha1.New, key)
mac.Write([]byte(query))
query = base64.StdEncoding.EncodeToString(mac.Sum(nil))
return query
}
func main() {
ss := strings.Index("attr[456546]","attr")
print(ss)
return
//println(php2go.Sha1("123456"+"123456"))
//ss := Sha1("POST&https%3A%2F%2Fapi.tme.eu%2FProducts%2FSearch.json&Country%3DUS%26Currency%3DUSD%26Language%3DEN%26SearchPlain%3DRMCF0402FT12R0%26Token%3D3381c9d5d9663be68eb69ea3ce00af3a2b5789094c7cd488a4","a1d8647fa38710140628")
//println(ss)
}
package main
import (
"fmt"
"sort"
)
// 按map的key排序
func main() {
params := make(map[string]interface{})
params["name"] = "xxx"
params["age"] = 23
params["sex"] = 0
params["level"] = 1
// 1.取出所有的key
var keys []string
for k := range params{
keys = append(keys, k)
}
// 对字符串切片排序
sort.Strings(keys)
fmt.Println(keys)
// 打印key, val
for _, k := range keys{
fmt.Printf("key: %v val:%v \n", k, params[k])
}
}
package main
import (
cmap "github.com/orcaman/concurrent-map"
)
func main() {
m := cmap.New()
// Sets item within map, sets "bar" under key "foo"
m.Set("foo", "bar")
m.Set("a1", "dd")
m.Set("b2", "ba343r")
// Retrieve item from map.
if tmp, ok := m.Get("foo"); ok {
bar := tmp.(string)
println(bar)
}
s,_ := m.MarshalJSON()
println(string(s))
// Removes item under key "foo"
//m.Remove("foo")
}
\ No newline at end of file
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/semihalev/gin-stats"
)
func main() {
r := gin.Default()
r.Use(stats.RequestStats())
r.GET("/stats", func(c *gin.Context) {
fmt.Print(stats.RequestStats())
c.JSON(http.StatusOK, stats.Report())
})
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
\ No newline at end of file
package main
import "fmt"
func main() {
for a:=0;a<5;a++{
fmt.Println(a)
if a>3{
goto Loop
}
}
Loop: //放在for后边
fmt.Println("test")
}
\ No newline at end of file
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"runtime"
"strings"
)
var Context *gin.Context
var REQUEST map[string]string //等同于php 的$_REQUEST,只接收非数组值
//将gin的上下文放到全局变量
func ContextVars() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Print("nni")
//接收所有的变量+值
c.MultipartForm()
REQUEST1 := make(map[string]string)
for requestName, requstValue := range c.Request.Form {
REQUEST1[requestName] = strings.TrimSpace(requstValue[0])
}
REQUEST = REQUEST1
}
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
//初始化引擎
r := gin.Default()
r.Use(ContextVars())
r.POST("/user", func(c *gin.Context) {
//name := c.PostForm("name")
fmt.Print(REQUEST["name"],"nnini")
c.String(http.StatusOK, "Hello %s", REQUEST["name"])
})
r.Run(":9100") // listen and serve on 0.0.0.0:8080
}
\ No newline at end of file
package main
import (
"encoding/json"
"fmt"
"github.com/iancoleman/orderedmap"
)
func main() {
o := orderedmap.New()
o.Set("error_code", 1)
o.Set("error_msg", "fagaga")
s := orderedmap.New()
s.Set("total",10)
aggs := orderedmap.New()
aggs.Set("1001€品牌",[...]string{"3001€mouser€0","4003€arrowV€0"})
aggs.Set("1002€标称电压",[...]string{"2001€5.5V€0","4003€arrowV€0"})
s.Set("aggs",aggs)
o.Set("data", s)
m1,_ := o.Get("error_msg")
fmt.Print(m1)
bytes, err := json.Marshal(o)
fmt.Print(string(bytes),err)
return
//// use Get instead of i, ok := o["a"]
//val, ok := o.Get("a")
//
//// use Keys instead of for k, v := range o
//key := o.Keys()
//for _, k := range keys {
// v, _ := o.Get(k)
//}
// use o.Delete instead of delete(o, key)
//err := o.Delete("a")
// serialize to a json string using encoding/json
//bytes, err := json.Marshal(o)
//fmt.Print(string(bytes),err)
//prettyBytes, err := json.MarshalIndent(o)
//
//// deserialize a json string using encoding/json
//// all maps (including nested maps) will be parsed as orderedmaps
//s := `{"a": 1}`
//err := json.Unmarshal([]byte(s), &o)
//
//// sort the keys
//o.SortKeys(sort.Strings)
//
//// sort by Pair
//o.Sort(func(a *Pair, b *Pair) bool {
// return a.Value().(float64) < b.Value().(float64)
//})
}
\ No newline at end of file
package main
import (
"github.com/tidwall/sjson"
"gopkg.in/olivere/elastic.v5"
)
const json1 = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`
const param1 = `{
"query": {
"bool": {
"must": [
]
}
},
"aggs": {
"brand_id": {
"terms": {
"field": "brand_id",
"size": 1000
}
},
"attrs": {
"nested": {
"path": "attrs"
},
"aggs": {
"attr_name": {
"terms": {
"field": "attrs.attr_name",
"size": 5000
},
"aggs": {
"attr_value": {
"terms": {
"field": "attrs.attr_value",
"size": 5000
}
}
}
}
}
}
},
"sort": {
"sort": {
"order": "desc"
}
},
"from": 0,
"size": 0
}`
func main() {
query := elastic.NewBoolQuery()
query1 := elastic.NewBoolQuery()
query2 := elastic.NewBoolQuery()
query1.Must(elastic.NewTermQuery("class_id2",111))
query1.Should(elastic.NewTermQuery("brand_id","108"))
query1.Should(elastic.NewTermQuery("brand_id","107"))
query2.Should(elastic.NewNestedQuery("attrs",elastic.NewBoolQuery().Must(elastic.NewTermQuery("attrs.attr_name","nin"),elastic.NewTermQuery("attrs.attr_value","nni"))))
query2.Should(elastic.NewNestedQuery("attrs",elastic.NewBoolQuery().Must(elastic.NewTermQuery("attrs.attr_name","3333"),elastic.NewTermQuery("attrs.attr_value","333"))))
source := elastic.NewSearchSource()
source.Aggregation("brand_id",elastic.NewTermsAggregation().Field("brand_id").Size(1000))
source.Aggregation("attrs",elastic.NewNestedAggregation().Path("attrs").
SubAggregation("attr_name",elastic.NewTermsAggregation().Field("attrs.attr_name").Size(5000).
SubAggregation("attr_value",elastic.NewTermsAggregation().Field("attrs.attr_value").Size(5000))))
source.FetchSourceContext(elastic.NewFetchSourceContext(true).Include("goods_id", "stock")) //显示字段
source.Size(1)
query.Must(query1)
query.Must(query2)
source.Query(query)
searchRequest := elastic.NewSearchRequest().Source(source)
queryString, _ := searchRequest.Body()
print(queryString)
return
value, _ := sjson.Set(param1, "query.bool.must.-1", map[string]interface{}{"hello":"world"})
value, _ = sjson.Set(value, "query.bool.must.-1", map[string]interface{}{"hellosss":"world"})
println(value)
}
\ No newline at end of file
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/util/gconv"
"reflect"
)
type Struct1 struct {
A string `json:"a"`
B string `json:"b"`
C string `json:"c"`
D int `json:"d"`
E string `json:"e"`
F int `json:"f"`
G string `json:"g"`
}
type jsonStr string
/**
@author wangsong
redis hash sku 结构,主要是用作新增插入用
poolSkuSave 插入redis就是这些字段
*/
type SkuRedisInfo struct {
SpuId string `json:"spu_id"`
Encoded int `json:"encoded"`//供应商编码
Moq int `json:"moq" form:"moq" binding:"required"`//起订量
Mpq int `json:"mpq" form:"mpq" binding:"required"`//标准包装量
OldGoodsId int64 `json:"old_goods_id"`//老商品ID
GoodsType int `json:"goods_type"`//'0:自营 1:联营 2:专卖',
GoodsStatus int64 `json:"goods_status"`//sku状态 '商品状态 0:待审核 1:审核通过(上架)2:审核不通过 3:下架 4:删除'
BatchSn string `json:"batch_sn" form:"batch_sn" `//批次
Stock int `json:"stock" form:"stock" `//库存
HkDeliveryTime string `json:"hk_delivery_time" form:"hk_delivery_time" `//香港货期
CnDeliveryTime string `json:"cn_delivery_time" form:"cn_delivery_time" `//大陆货期
LadderPrice string `json:"ladder_price" form:"ladder_price" `//阶梯价钱
UpdateTime int `json:"update_time" xorm:"created"`
GoodsImages string `json:"goods_images" form:"goods_images" `//商品图片 所属spu
Canal string `json:"canal" form:"canal" `//渠道开发员ID
SupplierId int `json:"supplier_id" form:"supplier_id" binding:"required"`
CpTime int `json:"cp_time" form:"cp_time" `//茂则成本添加时间
}
func main() {
redisInfo:=SkuRedisInfo{}
redisInfo.SpuId="";
redisInfo.LadderPrice=`[{"purchases":5,"price_us":0.1677,"price_cn":0}]`
redisInfo.Moq=123
var jsonredisInfo map[string]interface{}
bytes, err:= json.Marshal(redisInfo)
if(err!=nil){
fmt.Println("错误")
//fmt.Println(err.Error())
}else{
json.Unmarshal([]byte(bytes),&jsonredisInfo)
//fmt.Printf("%+v", jsonredisInfo)
}
var jsonMap map[string]interface{}
var ladderPrice []map[string]interface{}
err = json.Unmarshal([]byte(`{"spu_id":2160610278284142904,"encoded":"","moq":5,"mpq":"1","old_goods_id":0,"goods_type":1,"goods_status":1,"batch_sn":"","stock":13583,"hk_delivery_time":"","cn_delivery_time":"","ladder_price":[{"purchases":5,"price_us":0.1677,"price_cn":0},{"purchases":25,"price_us":0.0852,"price_cn":0},{"purchases":107,"price_us":0.0505,"price_cn":0},{"purchases":501,"price_us":0.0481,"price_cn":0}],"update_time":1606890001,"goods_images":"","canal":"","supplier_id":4}`),&jsonMap)
for key,_:= range jsonMap{
if _, ok := jsonredisInfo[key]; ok {//有值
if(!reflect.ValueOf(jsonredisInfo[key]).IsZero()){//如果需要改的数据不为空,就要赋值到
s:=reflect.ValueOf(jsonredisInfo[key])
if(key=="ladder_price"){//ladder_price 需要单独处理下,如果直接赋值,会出现 斜划线 "\"
if(s.Kind()==reflect.String){
fmt.Println("是字符串")
}
ladderPriceStr:=gconv.String(jsonredisInfo[key])
err=json.Unmarshal([]byte(ladderPriceStr),&ladderPrice)
continue
}
if(s.Kind()==reflect.String){ //string
jsonMap[key]=gconv.String(jsonredisInfo[key])
}else{
jsonMap[key]=gconv.Int(jsonredisInfo[key]) //int
}
}else{//没有数据,其实不需要改,纠正一下类型。
s:=reflect.ValueOf(jsonredisInfo[key])
if(s.Kind()==reflect.String){ //string
jsonMap[key]=gconv.String(jsonMap[key])
}else{
jsonMap[key]=gconv.Int(jsonMap[key]) //int
}
}
reflect.ValueOf(jsonMap[key]).Kind()
}
}
if(err!=nil){
fmt.Println("错误")
fmt.Println(err.Error())
}else{
str,_:=json.Marshal(jsonMap)
fmt.Printf(string(str))
//fmt.Printf("%+v", jsonMap)
}
//reflect1(jsonMap,struct1)
}
/**
合并map,都有值以map1为主,字段类型以map1为主
*/
func mergeMap(map1 map[string]interface{},map2 map[string]interface{}) map[string]interface{} {
var newMap map[string]interface{}
newMap=map1//以map1为主,就先将map1给到newMap
//先算mp1
for key,_:= range map1{
if(!reflect.ValueOf(map1[key]).IsZero()){//如果不为空,就以取map1的值
s:=reflect.ValueOf(map1[key])
if(s.Kind()==reflect.String){ //string
newMap[key]=gconv.String(map1[key])
}else{
newMap[key]=gconv.Int(map1[key]) //int
}
delete(map2, key)//删一个重复的map2的key
}else{//没有数据,取mp2的值,类型要是map1字段的类型
if _, ok := map2[key]; ok { //map1的key在map2是否存在,不存在就不处理
if(!reflect.ValueOf(map2[key]).IsZero()){ //map2不能为0值才处理
m1 :=reflect.ValueOf(map1[key])
if(m1.Kind()==reflect.String){ //string
newMap[key]=gconv.String(map2[key])
}else{
newMap[key]=gconv.Int(map2[key]) //int
}
}
delete(map2, key)//删一个重复的map2的key
}
}
}
//处理map2,重复的被删了,剩下的直接添加
for key,value:= range map2{
s:=reflect.ValueOf(value)
if(s.Kind()==reflect.String){ //string
newMap[key]=gconv.String(value)
}else{
newMap[key]=gconv.Int(value) //int
}
}
return newMap
}
func test() {
/*if(key=="ladder_price"){//ladder_price 需要单独处理下,如果直接赋值,会出现 斜划线 "\"
if(s.Kind()==reflect.String){
fmt.Println("是字符串")
}
ladderPriceStr:=gconv.String(jsonredisInfo[key])
err=json.Unmarshal([]byte(ladderPriceStr),&ladderPrice)
continue
}*/
}
func reflect1(jsonMap map[string]interface{},interface2 interface{}) {
//var newMap map[string]interface{}
sval := reflect.ValueOf(interface2).Elem()
for i := 0; i < sval.NumField(); i++ {
name := sval.Type().Field(i).Name
jsonOneValue:=reflect.ValueOf(jsonMap[name])
if(jsonOneValue.IsZero()){//0值
if(jsonOneValue.Kind()==reflect.TypeOf(sval.Field(i)).Kind()){
}
//直接覆盖
}else{//非0值
}
fmt.Println(sval.Field(i))
}
}
func reflect_exp(struct1 interface{},struct2 interface{})error {
return nil
/*sval := reflect.ValueOf(struct1).Elem()
dval := reflect.ValueOf(struct2).Elem()
for i := 0; i < sval.NumField(); i++ {
value := sval.Field(i)
fmt.Println(value)
if (statusType == 1) { //如果struct1 字段值为零值就不覆盖struct2对应的字段值
if (value.IsZero()) {
continue
}
}
}*/
}
func exp() {
var jsonBlob = [ ] byte ( ` [
{ "Name" : "Platypus" , "Order" : "Monotremata" } ,
{ "Name" : "Quoll" , "Order" : "Dasyuromorphia" }
] ` )
type Animal struct {
Name string
Order string
}
var animals [ ] Animal
err := json. Unmarshal ( jsonBlob , & animals )
if err != nil {
fmt. Println ( "error:" , err )
}
fmt. Printf ( "%+v" , animals )
}
\ No newline at end of file
package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
"log"
)
func main() {
c1, err := redis.Dial("tcp", "192.168.1.235:6379")
if err != nil {
log.Fatalln(err)
}
if _, err := c1.Do("AUTH", "icDb29mLy2s"); err != nil {
c1.Close()
log.Fatalln(err)
}
defer c1.Close()
reply, err := redis.Values(c1.Do("hvals", "Self_StockLock165514"))
if err != nil {
fmt.Print(err,"错误")
// handle error
}
var albums []int64
if err := redis.ScanSlice(reply, &albums); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%v\n", albums)
//if _, err := redis.Scan(reply, &value1,&value2); err != nil {
// // handle error
// }
// fmt.Print(value1,value2)
return
//c1.Send("HGet", "sku","1150969960421953396")
c1.Send("hvals", "Self_StockLock165514")
//c1.Send("HGet", "sku","1159160904159516648333")
//c1.Send("HGet", "sku","1150961577851663286")
c1.Flush()
//echoReceive(c1.Receive())
s,err := c1.Receive()
fmt.Print(err,s.([]uint64))
//echoReceive(c1.Receive())
//echoReceive(c1.Receive())
//echoReceive(c1.Receive())
}
func echoReceive(res interface{}, err error){
if err != nil{
fmt.Println(err)
}else {
if res != nil{
fmt.Printf("--------- ")
fmt.Println(string(res.([]byte)))
}else {
fmt.Println(res)
}
}
}
package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
"log"
)
func main() {
c1, err := redis.Dial("tcp", "192.168.1.235:6379")
if err != nil {
log.Fatalln(err)
}
if _, err := c1.Do("AUTH", "icDb29mLy2s"); err != nil {
c1.Close()
log.Fatalln(err)
}
defer c1.Close()
// good_id := []interface{}{"spu","2160558271613306802","2160551632152235701"}
// res1,err := c1.Do("hmget","spu","2160558271613306802","2160551632152235701")
res1,err := c1.Do("hmget","spu","2160558271613306802")
reply, err := redis.Strings(res1,err)
//if err != nil {
// fmt.Print(err,"错误")
// // handle error
//}
fmt.Println(reply)
//if _, err := redis.Scan(reply, &value1,&value2); err != nil {
// // handle error
// }
// fmt.Print(value1,value2)
return
}
package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
_ "reflect"
)
type Student struct {
Id int
Name string
}
func (s Student) EchoName(name string){
fmt.Println("我的名字是:", name)
}
func main() {
c1, err := redis.Dial("tcp", "192.168.1.235:6379")
if err != nil {
}
if _, err := c1.Do("AUTH", "icDb29mLy2s"); err != nil {
c1.Close()
}
defer c1.Close()
s := []interface{}{"spu","2160558271613306802","2160551632152235701"}
//res1,err := c1.Do("hmget","spu","2160558271613306802","2160551632152235701")
res1,err := c1.Do("hmget",s...)
//res1,err := c1.Do("hmget","spu",good_id)
reply, err := redis.Strings(res1,err)
//if err != nil {
// fmt.Print(err,"错误")
// // handle error
//}
fmt.Println(reply)
//s := Student{Id: 1, Name: "咖啡色的羊驼"}
//v := reflect.ValueOf(s)
//// 获取方法控制权
//// 官方解释:返回v的名为name的方法的已绑定(到v的持有值的)状态的函数形式的Value封装
//mv := v.MethodByName("EchoName")
//// 拼凑参数
//args := []reflect.Value{reflect.ValueOf("咖啡色的羊驼")}
//
//// 调用函数
//mv.Call(args)
}
\ No newline at end of file
package main
import (
"fmt"
"github.com/syyongx/php2go"
"sort"
)
//阶梯价格排序算法
type SorterRatio []map[string]string
func (a SorterRatio) Len() int {
return len(a)
}
func (a SorterRatio) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a SorterRatio) Less(i, j int) bool {
return a[j]["sort"] < a[i]["sort"]
}
func main() {
s := make(map[string]string)
s["sort"] = "45"
s2 := make(map[string]string)
s2["sort"] = "89"
var slic SorterRatio
slic = append(slic, s)
slic = append(slic, s2)
sort.Sort(SorterRatio(slic))
fmt.Printf("%+v", slic)
fmt.Println(php2go.Stripos(",10005,10006,","100205",0))
return
if php2go.Stripos("10005",",10005,10006,",0) > -1 {
fmt.Println("1002 不参与分类的商品")
return
}
}
package main
import (
"fmt"
"sort"
)
//阶梯价格排 序算dfsdf法
type LadderPriceSorter []map[string]string
func (a LadderPriceSorter) Len() int {
return len(a)
}
func (a LadderPriceSorter) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a LadderPriceSorter) Less(i, j int) bool {
return a[j]["sort"] > a[i]["sort"]
}
func main() {
s:=make(map[string]string)
s["sort"]="60";
s2:=make(map[string]string)
s2["sort"]="56"
var slic LadderPriceSorter
slic=append(slic,s)
slic=append(slic,s2)
fmt.Printf("%+v", slic)
sort.Sort(LadderPriceSorter(slic))
fmt.Printf("%+v", slic)
}
package main
import (
"fmt"
"reflect"
)
type A struct {
A int
B int
C string
E string
}
type B struct {
A int
B int
C int
D int
}
func CopyStruct(a interface{}, b interface{}) {
sval := reflect.ValueOf(a).Elem()
dval := reflect.ValueOf(b).Elem()
for i := 0; i < sval.NumField(); i++ {
value := sval.Field(i)
name := sval.Type().Field(i).Name
dvalue := dval.FieldByName(name)
if(dvalue.Kind()!=sval.Field(i).Kind()){
continue
}
value.IsZero()
if dvalue.IsValid() == false {
continue
}
dvalue.Set(value) //这里默认共同成员的类型一样,否则这个地方可能导致 panic,需要简单修改一下。
}
}
func zero() {
}
func main() {
a := &A{2, 2, "", "b"}
b:=&A{}
var c A
if(reflect.ValueOf(c).IsZero()){
fmt.Printf("零值")
}else{
fmt.Printf("不是零值")
}
return
CopyStruct(a,b)
fmt.Printf("%+v", b)
}
\ No newline at end of file
package main
import (
"flag"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/syyongx/php2go"
"reflect"
"go_sku_server/boot"
"go_sku_server/service"
)
func StrRandom(lenNum int) string {
randStr := "sdwpkxmiqplmzacbmeruwulurjlauejrifkfghjklzxcvbnmqwwertyuiopkdsieurnvewjeilweiskvnx"
strLen := len(randStr) - 9
var result string
for i := 0; i < lenNum; i++ {
//start := common.Rand(0, strLen)
start := php2go.Rand(0, strLen)
fmt.Println(start)
str := php2go.Substr(randStr, uint(start), 9)
result = result + " " + str
}
return result
}
type LogFormatter struct{}
//格式详情
func (s *LogFormatter) Format(entry *log.Entry) ([]byte, error) {
msg := entry.Message + "\n"
return []byte(msg), nil
}
func main() {
var path string
flag.StringVar(&path, "configPath", "conf", "配置文件")
flag.Parse()
if err := boot.Boot(path); err != nil {
fmt.Println(err)
}
res, _ := service.GetGoodsInfo([]string{"74163","116492","74123","106095","116451","162774","74152","116078","74122","74132"})
fmt.Println(len(res))
}
func InterfaceSlice(slice interface{}) []interface{} {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("InterfaceSlice() given a non-slice type")
}
ret := make([]interface{}, s.Len())
for i := 0; i < s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret
}
package main
import (
"fmt"
"encoding/json"
)
func main() {
var goodsList []interface{}
var productList map[string]interface{}
var price_temp []interface{}
var tiered []interface{}
m := make(map[string]interface{})
m["goods_names"] = "LM358"
m["stock"] = [...]int64{1,23}
price_temp = append(price_temp,[...]int64{3,5})
m["price_temp"] = price_temp;
s := make(map[string]interface{})
s["purchases"]=1
s["price_us"]=0.66
s["price_us"]=0.67
s["price_cn"]=0.33
tiered = append(tiered,s);
m["tiered"] = tiered;
goodsList = append(goodsList, m)
productList = make(map[string]interface{})
productList["595-LM358BIDR"] = goodsList
productList["595-LM358LVIDDFR"] = goodsList
//map的遍历
for k, v := range productList{
fmt.Println(k,v)
}
jsonStr, err := json.Marshal(productList)
if err!=nil{
return
}
fmt.Printf("%s\n",jsonStr)
}
\ No newline at end of file
package main
import (
"fmt"
"encoding/json"
"go_sku_server/model"
)
func main() {
var LyClearGoodsList model.LyClearGoodsList
LyClearGoodsList.GoodsName = "LM358"
ladderPrice := make([]*model.TierItem, 0)
ladder := model.TierItem{
Purchases: 1,
PriceUs: 0.44,
PriceCn: 1.55,
}
ladderPrice = append(ladderPrice, &ladder)
LyClearGoodsList.Tiered = ladderPrice
var productList map[string]*model.LyClearGoodsList
productList = make(map[string]*model.LyClearGoodsList,0)
productList["595-LM358BIDR"] = &LyClearGoodsList
//map的遍历
for k, v := range productList{
fmt.Println(k,v)
}
jsonStr, err := json.Marshal(productList)
if err!=nil{
return
}
fmt.Printf("%s\n",jsonStr)
}
\ No newline at end of file
package main
import (
"bytes"
"fmt"
"strconv"
)
func intsToString(values []int) string {
var buf bytes.Buffer
buf.WriteByte('[')
for i, v := range values {
if i > 0 {
buf.WriteString(", ")
}
fmt.Fprintf(&buf, "%d", v)
}
buf.WriteByte(']')
return buf.String()
}
func main() {
var a,b,c float64
a=1.69*100
b=1.7*10
c=a*b/(100*10)
//��ȷ���2.873
fmt.Println(c)
//fmt.Println(fmt.Sprintf("%.2f",c))
//fmt.Println(FloatRound(c,2))
}
// ��ȡС��λ��
func FloatRound(f float64, n int) float64 {
format := "%." + strconv.Itoa(n) + "f"
//fmt.Println(format)
res, _ := strconv.ParseFloat(fmt.Sprintf(format, f), 64)
return res
}
package main
import (
"fmt"
"reflect"
)
// interface{}转为 []interface{}
func CreateAnyTypeSlice(slice interface{}) ([]interface{}, bool) {
val, ok := isSlice(slice)
if !ok {
return nil, false
}
sliceLen := val.Len()
out := make([]interface{}, sliceLen)
for i := 0; i < sliceLen; i++ {
out[i] = val.Index(i).Interface()
}
return out, true
}
// 判断是否为slcie数据
func isSlice(arg interface{}) (val reflect.Value, ok bool) {
val = reflect.ValueOf(arg)
if val.Kind() == reflect.Slice {
ok = true
}
return
}
// 看需求写的代码
func faa(arg interface{}) {
slice, ok := CreateAnyTypeSlice(arg)
if !ok {
return
}
for index,value := range slice {
fmt.Println(index,value)
}
}
func main() {
intSlice := []int{1,2,3,4,5,6,7,8}
strSlice := []string{"a","b","c","d"}
boolSlice := []bool{true,true,false,true}
faa(intSlice)
faa(strSlice)
faa(boolSlice)
}
\ No newline at end of file
package main
import (
"fmt"
"reflect"
"regexp"
"strings"
)
func remove2(s interface{}, deleteVal int) []interface{} {
val := reflect.ValueOf(s)
sliceLen := val.Len()
out := make([]interface{}, sliceLen)
if val.Kind() == reflect.Slice {
sliceLen := val.Len()
for i := 0; i < sliceLen; i++ {
if val.Index(i).Int() != int64(deleteVal){
out[i] = val.Index(i).Interface()
}
}
}
return out
}
func main(){
a := []int{1,2,3,4,5}
fmt.Println(remove2(a,3))
test := "a,b,c,d,e"
aaa := test
keywordSlice := strings.Split(test,",")
for _,v := range keywordSlice{
reg := regexp.MustCompile("(?i)"+v)
aaa = reg.ReplaceAllString(aaa,"<b class='f-red'>"+strings.ToUpper(v)+"</b>")
fmt.Println(aaa)
}
}
package main
import (
"bytes"
"fmt"
"io"
)
const debug = false
func main() {
//var buf *bytes.Buffer
var buf io.Writer
fmt.Printf("%T \n",buf)
if debug {
buf = new(bytes.Buffer) // enable collection of output
}
f(buf) // NOTE: subtly incorrect!
if debug {
// ...use buf...
}
}
// If out is non-nil, output will be written to it.
func f(out io.Writer) {
// ...do something...
fmt.Println(out)
fmt.Printf("%T \n",out)
if out != nil {
fmt.Println("!!!!!!!!!!")
out.Write([]byte("done!\n"))
}
var a interface{}
a = map[string]string{
"a":"b",
}
a = nil
b,_ := a.(map[string]string)
fmt.Println(b)
}
\ No newline at end of file
package main
import (
"fmt"
"github.com/imroc/req"
"github.com/syyongx/php2go"
"github.com/tidwall/gjson"
"go_sku_server/middleware"
"go_sku_server/model"
"go_sku_server/pkg/common"
"strconv"
"time"
)
//tme 类
type tme struct {
}
//tme外链网址
const tme_api_url_product string = "https://api.tme.eu/Products/Search.json" //'Products/Search' 查询商品 或者 'Products/GetPricesAndStocks' 查询价格
const tme_api_url_stock string = "https://api.tme.eu/Products/GetPricesAndStocks.json" //'Products/Search' 查询商品 或者 'Products/GetPricesAndStocks' 查询价格
const tme_token string = "3381c9d5d9663be68eb69ea3ce00af3a2b5789094c7cd488a4"//密钥
const tme_app_secret string = "a1d8647fa38710140628" //账号
//tme请求外链
func OutLinkTme(goodsName *string) map[string]*model.LyClearGoodsList {
if *goodsName == "" {
return nil
}
var (
result string //请求外链原始结果
SymbolList string //外链原始数据的goods_sn
);
if middleware.REQUEST["flags"] == "-1" { //原始数据调试
result = `{"Status":"OK","Data":{"ProductList":[{"Symbol":"0402WGF1000TCE","CustomerSymbol":"","OriginalSymbol":"0402WGF1000TCE","Producer":"ROYAL OHM","Description":"Resistor: thick film; SMD; 0402; 100\u03a9; 63mW; \u00b11%; -55\u00f7155\u00b0C","CategoryId":"100578","Category":"0402 SMD resistors","Photo":"\/\/ce8dc832c.cloudimg.io\/fit\/640x480\/n@4760e4647bc7d903de9205a51f321b69cdbed098\/_cdn_\/D9\/C2\/B0\/00\/0\/732317_1.jpg?mark_url=_tme-wrk_%2Ftme_new_render3d.png&mark_pos=center&mark_size=100pp","Thumbnail":"\/\/ce8dc832c.cloudimg.io\/fit\/100x75\/webp@3ec3fbcb8427a46b791b093cd6e191b483328d8a\/_cdn_\/D9\/C2\/B0\/00\/0\/732317_1.jpg","Weight":0.01,"WeightUnit":"g","SuppliedAmount":0,"MinAmount":10000,"Multiples":10000,"ProductStatusList":[],"Unit":"pcs","ProductInformationPage":"\/\/www.tme.eu\/en\/details\/0402wgf1000tce\/0402-smd-resistors\/royal-ohm\/","Guarantee":null,"OfferId":null},{"Symbol":"SMD0402-100R-1%","CustomerSymbol":"","OriginalSymbol":"0402WGF1000TCE","Producer":"ROYAL OHM","Description":"Resistor: thick film; SMD; 0402; 100\u03a9; 63mW; \u00b11%; -55\u00f7155\u00b0C","CategoryId":"100578","Category":"0402 SMD resistors","Photo":"\/\/ce8dc832c.cloudimg.io\/fit\/640x480\/n@4760e4647bc7d903de9205a51f321b69cdbed098\/_cdn_\/D9\/C2\/B0\/00\/0\/732317_1.jpg?mark_url=_tme-wrk_%2Ftme_new_render3d.png&mark_pos=center&mark_size=100pp","Thumbnail":"\/\/ce8dc832c.cloudimg.io\/fit\/100x75\/webp@3ec3fbcb8427a46b791b093cd6e191b483328d8a\/_cdn_\/D9\/C2\/B0\/00\/0\/732317_1.jpg","Weight":0.006,"WeightUnit":"g","SuppliedAmount":0,"MinAmount":100,"Multiples":100,"ProductStatusList":[],"Unit":"pcs","ProductInformationPage":"\/\/www.tme.eu\/en\/details\/smd0402-100r-1%\/0402-smd-resistors\/royal-ohm\/0402wgf1000tce\/","Guarantee":null,"OfferId":null}],"Amount":2,"PageNumber":1,"CategoryList":{"111000":2,"100299":2,"100300":2,"100578":2,"112309":2}}}`;
}else{
params1 := "Country=US&Currency=USD&Language=EN&SearchPlain="+*goodsName+"&Token="+tme_token
param := "POST"+"&"+php2go.Rawurlencode(tme_api_url_product)+"&"+php2go.Rawurlencode(params1)
common.PrintDebugHtml(param)
sign := common.Sha1(param,tme_app_secret) //生成签名
postParam := params1+"&ApiSignature="+php2go.URLEncode(sign);
common.PrintDebugHtml(postParam)
req.SetTimeout(30 * time.Second)
//resp, err := req.Post(params2,postParam)
req.Debug = true
ss := req.Param{
"SearchPlain":*goodsName,
"Country":"US",
"Currency":"USD",
"Language":"EN",
"Token":"3381c9d5d9663be68eb69ea3ce00af3a2b5789094c7cd488a4",
"ApiSignature":sign,
}
resp, err := req.Post(tme_api_url_product,ss)
if err != nil {
print(tme_api_url_product)
print(err)
}
result = resp.String(); //请求外链拿到结果
}
common.PrintDebugHtml("原始数据:"+result)
productList := make(map[string]*model.LyClearGoodsList,0)
if gjson.Get(result,"Status").String() != "OK" {
common.PrintDebugHtml("请求出错-没有数据")
return nil
}
apiGoodsList := gjson.Get(result, "Data.ProductList").Array()
i := 0;
for _, goods := range apiGoodsList {
goodsSn := goods.Get("Symbol").String()
if i == 0 {
SymbolList = SymbolList+"&SymbolList[0]="+goodsSn
}else{
SymbolList = SymbolList+"&SymbolList["+strconv.Itoa(i)+"]"+goodsSn
}
i ++;
var increment int64 = 1;
if goods.Get("Multiples").Int() > 0 {
increment = goods.Get("Multiples").Int()
}
var moq int64 = 1;
if goods.Get("MinAmount").Int() > 0 {
moq = goods.Get("MinAmount").Int()
}
//拼接联营数据
LyClearGoodsList := model.LyClearGoodsList{
GoodsName: goods.Get("OriginalSymbol").String(),
BrandName: goods.Get("Producer").String(),
Desc: goods.Get("Description").String(),
GoodsSn: goodsSn,
Docurl: goods.Get("DataSheetUrl").String(),
Url: goods.Get("ProductInformationPage").String(),
GoodsImg: goods.Get("Photo").String(),
Increment: increment,
Moq:moq, //最低起订量
}
productList[goodsSn] = &LyClearGoodsList
}
//查询价格库存
params1 := "Country=US&Currency=USD&Language=EN&SymbolList="+SymbolList+"&Token="+tme_token
param := "POST"+"&"+php2go.Rawurlencode(tme_api_url_stock)+php2go.Rawurlencode(params1)
sign := common.Sha1(param,tme_app_secret) //生成签名
req.SetTimeout(10 * time.Second)
resp, err := req.Post(tme_api_url_stock,req.BodyJSON(params1+"&ApiSignature"+sign))
if err != nil {
print(tme_api_url_stock)
print(err)
}
result = resp.String(); //请求外链拿到结果
fmt.Println(result,SymbolList)
if gjson.Get(result,"Status").String() != "OK" {
common.PrintDebugHtml("请求出错-价格库存")
return nil
}
priceData := gjson.Get(result, "Data.ProductList").Array()
for _, info := range priceData {
ladderPrice := make([]*model.TierItem, 0)
priceTemp := make([]interface{}, 0)
//拼接价格梯度
apiPriceTi := info.Get("PriceList").Array()
var apiLowerPrice float64 = 0; //计算最低价格
for _,priceItem := range apiPriceTi{
priceItemStr := priceItem.String();
skuPrice := gjson.Get(priceItemStr, "PriceValue").Float()
quantity := gjson.Get(priceItemStr, "Amount").Int()
if apiLowerPrice == 0 {
apiLowerPrice = skuPrice
}else if apiLowerPrice > skuPrice {
apiLowerPrice = skuPrice
}
ladder := model.TierItem{
Purchases: quantity,
PriceUs: skuPrice,
PriceCn: 0,
}
ladderPrice = append(ladderPrice, &ladder)
//梯度缓存数据
priceTemp = append(priceTemp,[]interface{}{
quantity,
skuPrice,
})
}
goodsSn := info.Get("Symbol").String()
productList[goodsSn].Stock = info.Get("Amount").Int() //库存
productList[goodsSn].Tiered = ladderPrice //梯度价格
productList[goodsSn].PriceTemp = priceTemp //梯度价格2
productList[goodsSn].SinglePrice = apiLowerPrice //最低价格
}
return productList
}
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
var wg sync.WaitGroup
userCount := 5
ch := make(chan bool, 2)
for i := 0; i < userCount; i++ {
wg.Add(1)
//fmt.Println(i)
ch <- true
//fmt.Println("ddd")
go send(ch, i,&wg)
}
wg.Wait()
//time.Sleep(time.Second)
}
func send(ch chan bool, i int,wg *sync.WaitGroup) {
defer wg.Done()
//time.Sleep(time.Second*i)
fmt.Println("dddd",i)
//fmt.Printf("go func: %d\n", i)
<- ch
}
package main
import (
"fmt"
"github.com/gogf/gf/util/gconv"
"reflect"
)
func main() {
s:="sdfsdf"
var a int
atype := reflect.ValueOf(a).Type()
vtype := reflect.ValueOf(s).Type()
fmt.Printf("type address:%v\n", atype)
fmt.Println("convertible:", vtype.ConvertibleTo(atype))
fmt.Println(gconv.Int(s))
return
}
\ No newline at end of file
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func IsZeroOfUnderlyingType(x interface{}) bool {
return reflect.DeepEqual(x, reflect.Zero(reflect.TypeOf(x)).Interface())
}
func main() {
var person Person //定义一个零值
fmt.Println(IsZeroOfUnderlyingType(person)) //零值结构体,输出true
person.Name = "chenqiognhe" //结构体属性Name赋值
fmt.Println(IsZeroOfUnderlyingType(person)) //输出false
fmt.Println(IsZeroOfUnderlyingType(person.Age)) //Age仍是零值,输出true
person.Age = 18 //Age赋值
fmt.Println(IsZeroOfUnderlyingType(person.Age)) //输出false
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment