golang 实现blockchain

package main import ( "crypto/sha256" "encoding/json" "flag" "fmt" "io" "log" "net/http" "sort" "strings" "time" "golang.org/x/net/websocket" ) const ( queryLatest = iota queryAll responseBlockchain ) var genesisBlock = &Block{ Index: 0, PreviousHash: "0", Timestamp: 1465154705, Data: "my genesis block!!", Hash: "816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7", } var ( sockets []*websocket.Conn blockchain = []*Block{genesisBlock} httpAddr = flag.String("api", ":3001", "api server address.") p2pAddr = flag.String("p2p", ":6001", "p2p server address.") initialPeers = flag.String("peers", "ws://localhost:6001", "initial peers") ) type Block struct { Index int64 `json:"index"` PreviousHash string `json:"previousHash"` Timestamp int64 `json:"timestamp"` Data string `json:"data"` Hash string `json:"hash"` } func (b *Block) String() string { return fmt. [Read More]

golang 读写excel

golang 读取excel package main import ( "fmt" "net/http" "errors" "strings" "gitee.com/johng/gf/g/os/gtime" "gitee.com/johng/gf/g/util/gregex" "github.com/GiterLab/aliyun-sms-go-sdk/dysms" "github.com/astaxie/beego/logs" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/json" "github.com/golang/glog" "github.com/pborman/uuid" "github.com/tealeg/xlsx" ) var ( accessKeyId = "" accessKeySecret = "" signName = "" templateParam = make(map[string]string) failList = []string{} ) func main() { r := gin.Default() r.Static("/", "./static") r.POST("/upload", Upload) r.Run(":6000") } func Upload(c *gin.Context) { templatecode := c.PostForm("templatecode") if templatecode == "" { return } file, err := c.FormFile("file") if err ! [Read More]

GORM 高级用法

``` %like%查询 result :=[]*dao.Product{} dao.DB().Table("product").Where("name like ?","%提高%").Find(&result) fmt.Println(result) ## 自定义JsonP 类型 type JsonP struct { T map[string]interface{} } func (p JsonP) Value() (driver.Value, error) { if p ==nil{ return "",nil } j, _ := json.Marshal(p.T) return j, nil } func (p *JsonP) Scan(src interface{}) error { if p ==nil{ return errors.New("p is nil") } source, ok := src.([]byte) if !ok { return errors.New("Type assertion .([]byte) failed.") } var i interface{} err := json. [Read More]

Coupon 商品优惠券 API

##coupon_temp 优惠券模板

CREATE TABLE `coupon_temp` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `utime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  `start_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `end_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `type` tinyint(1) NOT NULL,
  `metadata` varchar(11) DEFAULT NULL,
  `amount_available` bigint(16) DEFAULT NULL,
  `amount_off` bigint(16) DEFAULT NULL,
  `percent_off` bigint(16) DEFAULT NULL,
  `max_circulation` int(8) DEFAULT NULL,
  `max_user_circulation` int(8) DEFAULT NULL,
  `duration` bigint(16) DEFAULT NULL,
  `name` varchar(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=100003 DEFAULT CHARSET=utf8mb4;

Gin API 设计

package main import ( "fmt" "net/http" "reflect" "github.com/gin-gonic/gin" xutil "hdutil" "logic/pkg/dao" "logic/pkg/service" ) func main() { r := gin.Default() rt := r.Group(`/homeworks`) rt.POST( ``, xutil.GRequestBodyObject(reflect.TypeOf(dao.Homework{}), "json"), CreateHomework, ) rt.PUT( `/:homeworkId`, xutil.GPathRequireInt("homeworkId"), xutil.GRequestBodyMap, UpdateHomework, ) r.GET( `/homeworksByFilter`, xutil.GQueryRequireString("filter"), xutil.GQueryOptionalIntDefault("current", 1), xutil.GQueryOptionalIntDefault("pageSize", 10), GetHomeworkByFilter, ) rt.POST( `/notify`, xutil.GRequestBodyObject(reflect.TypeOf([]int64{}), "json"), BatchSendRemark, ) rt.GET( `/:homeworkId/thumb`, xutil.GPathRequireInt("homeworkId"), xutil.GQueryRequireString("sessionId"), ThumbUp, ) rt.GET( `/:homeworkId/sharetimeline`, xutil.GPathRequireInt("homeworkId"), ShareTimeline, ) rt.GET( `/:homeworkId/sharefriend`, xutil.GPathRequireInt("homeworkId"), ShareFriend, ) r.Run(":5000") } func CreateHomework(c *gin.Context) { u := c. [Read More]

商品订单系统API

订单 Order{ Amount: integer ($int64) 商品总金额 = 商品单价 * 购买的商品数量 (填购买几件,1,2,3等等) CancelUrl: string 取消订单后的回调url(不用填) Channel: string 订单渠道 alipay, wx_pub_qr 微信公众号扫码支付(必填,当前支持alipay或者wx_pub_qr) Ctime: string ($string) 订单创建时间 默认自动生成当前时间(不用填) Id: integer ($int64) 订单编号主键自增 (不用填) PingId: integer ($int64) ping++ 自动生成的订单编号 (不用填) PingInfo: string ping++ 自动生成的 支付凭证信息 (不用填) Price: integer ($int64) 商品单价 (必填) ProductId: integer ($int64) 商品id (必填) Status: string 订单状态 待支付:'CREATED',已支付:'PAID',支付失败:'FAIL',存在退款:'REFUNDED',订单已取消'CANCELED' (不用填,默认是待支付,服务端根据ping++的通知 更改状态) SuccessUrl: string 支付成功的回调url(不用填) UserId: integer ($int64) 用户id(必填) Utime: string ($string) 订单更改时间(默认自动生成当前时间,不用填) } 商品 Product{ Avatar: string 商品图片(必填,例如http://img. [Read More]

golang nsq

安装 brew install nsq nsqd : 负责接收消息,存储队列和将消息发送给客户端,nsqd 可以多机器部署,当你使用客户端向一个topic发送消息时,可以配置多个nsqd地址,消息会随机的 分配到各个nsqd上,nsqd优先把消息存储到内存channel中,当内存channel满了之后,则把消息写到磁盘文件中。他监听了两个tcp端口,一个用来服务客 户端,一个用来提供http的接口 ,nsqd 启动时置顶下nsqlookupd地址即可: 在一个 shell 中,运行 nsqlookupd: nsqlookupd: 主要负责服务发现 负责nsqd的心跳、状态监测,给客户端、nsqadmin提供nsqd地址与状态 ➜nsqlookupd [nsqlookupd] 2017/11/27 22:48:11.186029 nsqlookupd v1.0.0-compat (built w/go1.8) [nsqlookupd] 2017/11/27 22:48:11.186266 TCP: listening on [::]:4160 [nsqlookupd] 2017/11/27 22:48:11.186314 HTTP: listening on [::]:4161 再开启一个 shell,运行 nsqd: ➜ bin ./nsqd --lookupd-tcp-address=127.0.0.1:4160 [nsqd] 2017/11/27 22:49:11.433686 nsqd v1.0.0-compat (built w/go1.8) [nsqd] 2017/11/27 22:49:11.433755 ID: 280 [nsqd] 2017/11/27 22:49:11.433797 NSQ: persisting topic/channel metadata to nsqd.dat [nsqd] 2017/11/27 22:49:11. [Read More]

golang etcd watch

package etcd import ( "context" "encoding/json" "fmt" "LearnEtcd/tailf" "strings" "time" "github.com/astaxie/beego/logs" etcd_client "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/mvcc/mvccpb" "LearnEtcd/Ip" ) type EtcdClient struct { Client *etcd_client.Client Keys []string } var ( etcdClient *EtcdClient ) func InitEtcd(addr string, key string) (collectConf []tailf.CollectConf, err error) { cli, err := etcd_client.New(etcd_client.Config{ Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, DialTimeout: 5 * time.Second, }) if err != nil { logs.Error("connect etcd failed, err:", err) return } etcdClient = &EtcdClient{ Client: cli, } if strings. [Read More]

golang kafka

producer package kafka import ( "github.com/Shopify/sarama" "github.com/astaxie/beego/logs" ) var ( client sarama.SyncProducer ) func InitKafka(addr string) (err error) { config := sarama.NewConfig() config.Producer.RequiredAcks = sarama.WaitForAll config.Producer.Partitioner = sarama.NewRandomPartitioner config.Producer.Return.Successes = true client, err = sarama.NewSyncProducer([]string{addr}, config) if err != nil { logs.Error("init kafka producer failed, err:", err) return } logs.Debug("init kafka succ") return } func SendToKafka(data, topic string) (err error) { msg := &sarama.ProducerMessage{} msg.Topic = topic msg.Value = sarama. [Read More]