├── seckill ├── SecAdmin │ └── main.go ├── SecLayer │ ├── service │ │ ├── service.go │ │ ├── const.go │ │ ├── seclimit.go │ │ ├── user_history.go │ │ ├── logs.go │ │ ├── product_count.go │ │ ├── init.go │ │ └── product.go │ ├── main.go │ └── conf │ │ └── seclayer.conf └── SecProxy │ ├── service │ ├── error.go │ ├── seclimit.go │ ├── minLimit.go │ ├── redis_proc.go │ ├── antispam.go │ ├── config.go │ ├── service.go │ └── init.go │ ├── router │ └── router.go │ ├── main.go │ ├── tools │ ├── httpclient │ │ └── main.go │ └── setconf │ │ └── main.go │ ├── conf │ └── app.conf │ ├── controller │ └── skill.go │ └── load │ └── init.go ├── logcollection ├── web_admin │ ├── conf │ │ └── app.conf │ ├── views │ │ ├── app │ │ │ ├── error.html │ │ │ ├── apply.html │ │ │ └── index.html │ │ ├── log │ │ │ ├── error.html │ │ │ ├── index.html │ │ │ └── apply.html │ │ └── layout │ │ │ └── layout.html │ ├── static │ │ ├── font │ │ │ ├── iconfont.eot │ │ │ ├── iconfont.ttf │ │ │ └── iconfont.woff │ │ └── css │ │ │ └── modules │ │ │ ├── layer │ │ │ └── default │ │ │ │ ├── icon.png │ │ │ │ ├── icon-ext.png │ │ │ │ ├── loading-0.gif │ │ │ │ ├── loading-1.gif │ │ │ │ └── loading-2.gif │ │ │ ├── code.css │ │ │ └── laydate │ │ │ └── default │ │ │ └── laydate.css │ ├── routers │ │ └── router.go │ ├── tests │ │ └── default_test.go │ ├── main.go │ ├── controllers │ │ ├── AppController │ │ │ └── app.go │ │ └── LogController │ │ │ └── log.go │ └── models │ │ ├── app.go │ │ └── log.go ├── waitgroup │ └── main │ │ └── main.go ├── config │ └── main.go ├── logagent │ ├── main │ │ ├── ip.go │ │ ├── server.go │ │ ├── log.go │ │ ├── main.go │ │ ├── config.go │ │ └── etcd.go │ ├── tools │ │ └── SetConf │ │ │ └── main.go │ ├── kafka │ │ └── kafka.go │ └── tail │ │ └── tail.go ├── tail │ └── main.go ├── log_transfer │ ├── log.go │ ├── main.go │ ├── config.go │ ├── run.go │ ├── es.go │ └── kafka.go ├── elasticsearch │ └── main │ │ └── main.go ├── context │ └── main │ │ └── main.go ├── kafka │ ├── consumer │ │ └── main │ │ │ └── main.go │ └── producer │ │ └── main │ │ └── main.go └── etcd │ ├── main │ └── main.go │ └── watcher │ └── main.go ├── video_server ├── streamserver │ ├── defs.go │ ├── upload.html │ ├── response.go │ ├── limiter.go │ ├── main.go │ └── handlers.go ├── api │ ├── utils │ │ ├── misc_test.go │ │ └── misc.go │ ├── dbops │ │ ├── conn.go │ │ ├── iternal.go │ │ └── api.go │ ├── response.go │ ├── defs │ │ ├── err.go │ │ └── apidef.go │ ├── auth.go │ ├── main.go │ ├── session │ │ └── ops.go │ └── handlers.go ├── scheduler │ ├── response.go │ ├── taskrunner │ │ ├── defs.go │ │ ├── trmain.go │ │ ├── runner.go │ │ └── tasks.go │ ├── dbops │ │ ├── conn.go │ │ ├── api.go │ │ └── internal.go │ ├── main.go │ └── handlers.go ├── web │ ├── defs.go │ ├── main.go │ ├── client.go │ └── handlers.go ├── vendor │ └── jayce │ │ └── config.go ├── db.sql └── templates │ └── home.html ├── loadbalance ├── balance │ ├── balance.go │ ├── instance.go │ ├── random.go │ ├── roundrobin.go │ └── manager.go └── main │ ├── main.go │ └── hash.go ├── goroutine ├── chart │ ├── proto │ │ ├── const.go │ │ └── proto.go │ ├── chat_server │ │ ├── main │ │ │ ├── const.go │ │ │ ├── main.go │ │ │ ├── user_mgr.go │ │ │ ├── proto.go │ │ │ ├── redis.go │ │ │ ├── server.go │ │ │ └── client.go │ │ └── model │ │ │ ├── error.go │ │ │ ├── user.go │ │ │ └── mgr.go │ ├── model │ │ └── user.go │ └── chat_client │ │ └── main.go ├── maze │ ├── maze_test.go │ ├── maze.in │ ├── gen.go │ └── maze.go ├── fibonacii │ ├── fibonacii_test.go │ └── fibonacii.go ├── interfac │ └── student.go ├── channel │ ├── test │ │ └── main.go │ └── main │ │ └── main.go └── sort │ └── sort │ └── main.go ├── crawler-distributed ├── config │ └── config.go ├── worker │ ├── rpc_crawlservice.go │ ├── server │ │ └── worker_main.go │ ├── client │ │ └── worker.go │ └── types.go ├── persist │ ├── rpc.go │ ├── client │ │ └── itemsaver.go │ └── server │ │ └── saver.go ├── rpcsupport │ └── rpc.go └── distributed.go ├── crawler ├── engine │ ├── duplicate.go │ ├── worker.go │ ├── simple.go │ ├── concurrent.go │ └── types.go ├── model │ └── profile.go ├── scheduler │ ├── simple.go │ └── queued.go ├── zhenai │ └── parser │ │ ├── citylist.go │ │ ├── profile_test.go │ │ ├── city.go │ │ └── profile.go ├── main.go ├── persist │ └── itemsaver.go └── fetcher │ └── fetcher.go ├── rpc ├── rpc.go ├── server │ └── main.go └── client │ └── main.go └── README.md /seckill/SecAdmin/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | -------------------------------------------------------------------------------- /logcollection/web_admin/conf/app.conf: -------------------------------------------------------------------------------- 1 | appname = web_admin 2 | httpport = 8080 3 | runmode = dev 4 | -------------------------------------------------------------------------------- /logcollection/web_admin/views/app/error.html: -------------------------------------------------------------------------------- 1 |
2 |
{{.Error}}
3 |
-------------------------------------------------------------------------------- /logcollection/web_admin/views/log/error.html: -------------------------------------------------------------------------------- 1 |
2 |
{{.Error}}
3 |
-------------------------------------------------------------------------------- /seckill/SecLayer/service/service.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | 4 | func Run()(err error){ 5 | err = RunProcess() 6 | return 7 | } -------------------------------------------------------------------------------- /video_server/streamserver/defs.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | const ( 4 | VIDEO_DIR = "./videos/" 5 | MAX_UPLOAD_SIZE = 50 * 1024 * 1024 6 | ) 7 | -------------------------------------------------------------------------------- /loadbalance/balance/balance.go: -------------------------------------------------------------------------------- 1 | package balance 2 | 3 | type Balance interface { 4 | DoBalance([]*Instance, ...string) (*Instance, error) 5 | } 6 | -------------------------------------------------------------------------------- /logcollection/web_admin/static/font/iconfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JayceQ/golang-awesome/HEAD/logcollection/web_admin/static/font/iconfont.eot -------------------------------------------------------------------------------- /logcollection/web_admin/static/font/iconfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JayceQ/golang-awesome/HEAD/logcollection/web_admin/static/font/iconfont.ttf -------------------------------------------------------------------------------- /logcollection/web_admin/static/font/iconfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JayceQ/golang-awesome/HEAD/logcollection/web_admin/static/font/iconfont.woff -------------------------------------------------------------------------------- /goroutine/chart/proto/const.go: -------------------------------------------------------------------------------- 1 | package proto 2 | 3 | const ( 4 | UserLogin = "user_login" 5 | UserLoginRes = "user_login_res" 6 | UserRegister = "user_register" 7 | ) 8 | -------------------------------------------------------------------------------- /logcollection/web_admin/static/css/modules/layer/default/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JayceQ/golang-awesome/HEAD/logcollection/web_admin/static/css/modules/layer/default/icon.png -------------------------------------------------------------------------------- /goroutine/chart/chat_server/main/const.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | const ( 4 | UserLogin = "user_login" 5 | UserLoginRes = "user_login_res" 6 | UserRegister = "user_register" 7 | ) 8 | -------------------------------------------------------------------------------- /logcollection/web_admin/static/css/modules/layer/default/icon-ext.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JayceQ/golang-awesome/HEAD/logcollection/web_admin/static/css/modules/layer/default/icon-ext.png -------------------------------------------------------------------------------- /logcollection/web_admin/static/css/modules/layer/default/loading-0.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JayceQ/golang-awesome/HEAD/logcollection/web_admin/static/css/modules/layer/default/loading-0.gif -------------------------------------------------------------------------------- /logcollection/web_admin/static/css/modules/layer/default/loading-1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JayceQ/golang-awesome/HEAD/logcollection/web_admin/static/css/modules/layer/default/loading-1.gif -------------------------------------------------------------------------------- /logcollection/web_admin/static/css/modules/layer/default/loading-2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JayceQ/golang-awesome/HEAD/logcollection/web_admin/static/css/modules/layer/default/loading-2.gif -------------------------------------------------------------------------------- /video_server/api/utils/misc_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestNewUUID(t *testing.T) { 9 | s, _ := NewUUID() 10 | fmt.Printf("%s", s) 11 | } 12 | -------------------------------------------------------------------------------- /video_server/streamserver/upload.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | fdas fa 9 | 10 | -------------------------------------------------------------------------------- /crawler-distributed/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | const ( 4 | ItemSaverPort = ":1234" 5 | ElasticIndex = "profiles" 6 | 7 | 8 | WorkerPort0 = 9002 9 | CrawlServiceRpc = "CrawlService.Process" 10 | ) 11 | -------------------------------------------------------------------------------- /goroutine/maze/maze_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMaze(t *testing.T){ 6 | 7 | maze := readMaze( "maze.dat") 8 | walk(maze,point{0,0},point{len(maze) - 1,len(maze[0]) - 1}) 9 | 10 | } 11 | -------------------------------------------------------------------------------- /crawler/engine/duplicate.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | var visitedUrls = make(map[string]bool) 4 | func IsDuplicate(url string) bool{ 5 | if visitedUrls[url]{ 6 | return true 7 | } 8 | visitedUrls[url] = true 9 | return false 10 | } -------------------------------------------------------------------------------- /video_server/scheduler/response.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "net/http" 6 | ) 7 | 8 | func sendResponse(w http.ResponseWriter, sc int, resp string) { 9 | w.WriteHeader(sc) 10 | io.WriteString(w, resp) 11 | } 12 | -------------------------------------------------------------------------------- /video_server/streamserver/response.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "net/http" 6 | ) 7 | 8 | func sendErrorResponse(w http.ResponseWriter,sc int, errMsg string){ 9 | w.WriteHeader(sc) 10 | io.WriteString(w,errMsg) 11 | } -------------------------------------------------------------------------------- /goroutine/chart/chat_server/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | func main() { 8 | initRedis("localhost:6379", 16, 1024, time.Second*300) 9 | initUserMgr() 10 | runServer("0.0.0.0:10000") 11 | } 12 | -------------------------------------------------------------------------------- /goroutine/chart/chat_server/main/user_mgr.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "golang-awesome/goroutine/chart/chat_server/model" 4 | 5 | var ( 6 | mgr *model.UserMgr 7 | ) 8 | 9 | func initUserMgr() { 10 | mgr = model.NewUserMgr(pool) 11 | } 12 | -------------------------------------------------------------------------------- /goroutine/fibonacii/fibonacii_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | //func TestSubstr(t *testing.T) { 6 | // f := fibonacii() 7 | // printFileContents(f) 8 | //} 9 | 10 | func BenchmarkFib(b *testing.B){ 11 | f := fibonacii() 12 | printFileContents(f) 13 | } -------------------------------------------------------------------------------- /video_server/scheduler/taskrunner/defs.go: -------------------------------------------------------------------------------- 1 | package taskrunner 2 | 3 | const ( 4 | READY_TO_DISPATCH = "d" 5 | READY_TO_EXECUTE = "e" 6 | CLOSE = "c" 7 | 8 | VIDEO_PATH = "./videos/" 9 | ) 10 | 11 | type controlChan chan string 12 | type dataChan chan interface{} 13 | type fn func(dc dataChan) error 14 | -------------------------------------------------------------------------------- /goroutine/chart/chat_server/model/error.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrUserNotExist = errors.New("user not exist") 7 | ErrInvalidPasswd = errors.New("passwd or username not right") 8 | ErrInvalidParams = errors.New("invalid params") 9 | ErrUserExist = errors.New("user exist") 10 | ) 11 | -------------------------------------------------------------------------------- /seckill/SecLayer/service/const.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | const ( 4 | ErrServiceBusy = 1001 5 | ErrSecKillSucc = 1002 6 | ErrNotFoundProduct = 1003 7 | ErrSoldout = 1004 8 | ErrRetry = 1005 9 | ErrAlreadyBuy = 1006 10 | ) 11 | 12 | const ( 13 | ProductStatusSoldout = 2001 14 | ) 15 | 16 | -------------------------------------------------------------------------------- /goroutine/maze/maze.in: -------------------------------------------------------------------------------- 1 | 12 8 2 | 0 1 0 0 0 0 0 0 3 | 0 0 0 1 0 1 1 0 4 | 0 1 0 1 0 0 1 1 5 | 1 1 1 0 0 0 1 0 6 | 0 1 0 0 1 0 1 1 7 | 0 1 0 0 0 0 1 0 8 | 0 0 0 1 1 0 0 1 9 | 0 0 0 0 0 1 1 1 10 | 0 1 0 1 0 0 0 0 11 | 0 1 0 1 1 1 1 1 12 | 0 0 0 1 0 0 0 0 13 | 0 1 0 0 0 1 0 0 -------------------------------------------------------------------------------- /video_server/scheduler/dbops/conn.go: -------------------------------------------------------------------------------- 1 | package dbops 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | ) 7 | 8 | var ( 9 | dbConn *sql.DB 10 | err error 11 | ) 12 | 13 | func init(){ 14 | dbConn, err = sql.Open("mysql","root:123456@/video_server?charset=utf8") 15 | if err != nil{ 16 | panic(err) 17 | } 18 | fmt.Printf("dbConn : %v\n",dbConn) 19 | } -------------------------------------------------------------------------------- /crawler/engine/worker.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "github.com/astaxie/beego/logs" 5 | "golang-awesome/crawler/fetcher" 6 | ) 7 | 8 | func Worker(r Request) (ParserResult,error){ 9 | body, err := fetcher.Fetch(r.Url) 10 | if err != nil { 11 | logs.Error("请求[%s]失败,%s",r.Url,err) 12 | return ParserResult{},err 13 | } 14 | return r.Parse.Parse(body,r.Url),nil 15 | } 16 | -------------------------------------------------------------------------------- /seckill/SecProxy/service/error.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | const ( 4 | ErrInvalidRequest = 1001 5 | ErrNotFoundProductId = 1002 6 | ErrUserCheckAuthFailed = 1003 7 | ErrUserServiceBusy = 1004 8 | ErrActiveNotStart = 1005 9 | ErrActiveAlreadyEnd = 1006 10 | ErrActiveSaleOut = 1007 11 | ErrProcessTimeout = 1008 12 | ErrClientClosed = 1009 13 | ) -------------------------------------------------------------------------------- /rpc/rpc.go: -------------------------------------------------------------------------------- 1 | package rpcDemo 2 | 3 | import "github.com/pkg/errors" 4 | 5 | //Service.Method 6 | 7 | type DemoService struct { 8 | 9 | } 10 | 11 | type Args struct { 12 | A,B int 13 | } 14 | 15 | 16 | func (DemoService) Div(args Args,result *float64)error{ 17 | if args.B == 0 { 18 | return errors.New("division by zero") 19 | } 20 | 21 | *result = float64(args.A) / float64(args.B) 22 | return nil 23 | } 24 | -------------------------------------------------------------------------------- /seckill/SecProxy/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | "github.com/astaxie/beego/logs" 6 | "golang-awesome/SecKill/SecProxy/controller" 7 | ) 8 | 9 | func init() { 10 | logs.Debug("enter router main") 11 | beego.Router("/seckill", &controller.SkillController{}, "*:SecKill") 12 | beego.Router("/secinfo", &controller.SkillController{}, "*:SecInfo") 13 | } 14 | 15 | -------------------------------------------------------------------------------- /seckill/SecProxy/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang-awesome/seckill/SecProxy/load" 5 | _ "golang-awesome/seckill/SecProxy/router" 6 | "github.com/astaxie/beego" 7 | ) 8 | 9 | func main(){ 10 | 11 | err := load.InitConfig() 12 | if err != nil{ 13 | panic(err) 14 | return 15 | } 16 | 17 | err = load.InitSecKill() 18 | if err != nil{ 19 | panic(err) 20 | return 21 | } 22 | 23 | beego.Run() 24 | } -------------------------------------------------------------------------------- /crawler/model/profile.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type Profile struct { 4 | Id string 5 | Url string 6 | Name string 7 | Gender string 8 | Age string 9 | Height string 10 | Weight string 11 | Income string 12 | Marriage string 13 | Education string 14 | Occupation string 15 | Hukou string 16 | Xingzuo string 17 | House string 18 | Car string 19 | } 20 | -------------------------------------------------------------------------------- /logcollection/waitgroup/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | func main(){ 10 | wg := sync.WaitGroup{} 11 | 12 | for i := 0;i<10;i++{ 13 | wg.Add(1) 14 | go cacl(&wg,i) 15 | } 16 | 17 | wg.Wait() 18 | fmt.Println("all groutine finish") 19 | } 20 | 21 | func cacl(w *sync.WaitGroup,i int){ 22 | fmt.Println("cacl:",i) 23 | time.Sleep(time.Second) 24 | w.Done() 25 | } -------------------------------------------------------------------------------- /crawler-distributed/worker/rpc_crawlservice.go: -------------------------------------------------------------------------------- 1 | package worker 2 | 3 | import "golang-awesome/crawler/engine" 4 | 5 | type CrawlService struct { 6 | } 7 | 8 | func (CrawlService) Process(req Request,result *ParseResult) error{ 9 | request, err := DeserializeRequest(req) 10 | if err != nil { 11 | return err 12 | } 13 | 14 | parserResult, err := engine.Worker(request) 15 | *result = SerializeResult(parserResult) 16 | return nil 17 | } 18 | -------------------------------------------------------------------------------- /goroutine/chart/model/user.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | const ( 4 | UserStatusOnline = 1 5 | UserStatusOffline = iota 6 | ) 7 | 8 | type User struct { 9 | UserId int `json:"user_id"` 10 | Passwd string `json:"passwd` 11 | Nick string `json:"nick"` 12 | Sex string `json:"sex"` 13 | Header string `json:"header"` 14 | LastLogin string `json:"last_login"` 15 | Status int `json:"status"` 16 | } 17 | -------------------------------------------------------------------------------- /video_server/scheduler/dbops/api.go: -------------------------------------------------------------------------------- 1 | package dbops 2 | 3 | import "log" 4 | 5 | func AddVideoDeletionRecord(vid string) error{ 6 | stmtIns, err := dbConn.Prepare("insert into video_del_rec(video_id) values (?)") 7 | if err != nil{ 8 | return err 9 | } 10 | 11 | _, err = stmtIns.Exec(vid) 12 | if err != nil { 13 | log.Printf("AddVideoDeletionRecord error: %v",err) 14 | return err 15 | } 16 | 17 | defer stmtIns.Close() 18 | return nil 19 | } -------------------------------------------------------------------------------- /goroutine/chart/chat_server/model/user.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | const ( 4 | UserStatusOnline = 1 5 | UserStatusOffline = iota 6 | ) 7 | 8 | type User struct { 9 | UserId int `json:"user_id"` 10 | Passwd string `json:"passwd` 11 | Nick string `json:"nick"` 12 | Sex string `json:"sex"` 13 | Header string `json:"header"` 14 | LastLogin string `json:"last_login"` 15 | Status int `json:"status"` 16 | } 17 | -------------------------------------------------------------------------------- /video_server/api/dbops/conn.go: -------------------------------------------------------------------------------- 1 | package dbops 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | _ "github.com/go-sql-driver/mysql" 7 | ) 8 | 9 | var ( 10 | dbConn *sql.DB 11 | err error 12 | ) 13 | 14 | func init() { 15 | fmt.Println("Entering conn.go init function...") 16 | dbConn, err = sql.Open("mysql", "root:123456@/video_server?charset=utf8") 17 | if err != nil { 18 | panic(err.Error()) 19 | } 20 | fmt.Printf("dbConn +%v\n", dbConn) 21 | } 22 | -------------------------------------------------------------------------------- /video_server/scheduler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/julienschmidt/httprouter" 5 | "golang-awesome/video_server/scheduler/taskrunner" 6 | "net/http" 7 | ) 8 | 9 | func RegisterHandlers() *httprouter.Router { 10 | r := httprouter.New() 11 | r.GET("/video-delete-record/:vid-id", vidDelRecHandler) 12 | return r 13 | } 14 | 15 | func main() { 16 | go taskrunner.Start() 17 | r := RegisterHandlers() 18 | http.ListenAndServe(":9001",r) 19 | } 20 | -------------------------------------------------------------------------------- /logcollection/config/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego/config" 6 | ) 7 | 8 | func main() { 9 | conf, e := config.NewConfig("ini", "./logagent.conf") 10 | if e != nil { 11 | fmt.Println("new config failed ,err :", e) 12 | return 13 | } 14 | 15 | port, e := conf.Int("server::port") 16 | if e != nil { 17 | fmt.Println("read server:port failed,err:",e) 18 | return 19 | } 20 | 21 | fmt.Println("port:",port) 22 | 23 | } 24 | -------------------------------------------------------------------------------- /goroutine/chart/proto/proto.go: -------------------------------------------------------------------------------- 1 | package proto 2 | 3 | import "golang-awesome/goroutine/chart/model" 4 | 5 | type Message struct { 6 | Cmd string `json:"cmd"` 7 | Data string `json:"data"` 8 | } 9 | 10 | type LoginCmd struct { 11 | Id int `json:"user_id"` 12 | Passwd string `json:"passwd"` 13 | } 14 | 15 | type RegisterCmd struct { 16 | User model.User `json:"user"` 17 | } 18 | 19 | type LoginCmdRes struct { 20 | Code int `json:"code"` 21 | Error string `json:"error"` 22 | } 23 | -------------------------------------------------------------------------------- /rpc/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang-awesome/rpc" 5 | "log" 6 | "net" 7 | "net/rpc" 8 | "net/rpc/jsonrpc" 9 | ) 10 | 11 | func main(){ 12 | rpc.Register(rpcDemo.DemoService{}) 13 | listener, err := net.Listen("tcp",":1234") 14 | if err != nil { 15 | panic(err) 16 | } 17 | 18 | for { 19 | conn, err := listener.Accept() 20 | if err != nil { 21 | log.Printf("accept error: %v", err) 22 | continue 23 | } 24 | go jsonrpc.ServeConn(conn) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /video_server/api/response.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "golang-awesome/video_server/api/defs" 6 | "io" 7 | "net/http" 8 | ) 9 | 10 | func sendErrorResponse(w http.ResponseWriter, errResp defs.ErrResponse){ 11 | w.WriteHeader(errResp.HttpSC) 12 | resStr, _ := json.Marshal(&errResp.Error) 13 | io.WriteString(w, string(resStr)) 14 | } 15 | 16 | func sendNormalResponse(w http.ResponseWriter, resp string, sc int) { 17 | w.WriteHeader(sc) 18 | io.WriteString(w, resp) 19 | } -------------------------------------------------------------------------------- /goroutine/chart/chat_server/main/proto.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "golang-awesome/goroutine/chart/chat_server/model" 4 | 5 | type Message struct { 6 | Cmd string `json:"cmd"` 7 | Data string `json:"data"` 8 | } 9 | 10 | type LoginCmd struct { 11 | Id int `json:"user_id"` 12 | Passwd string `json:"passwd"` 13 | } 14 | 15 | type RegisterCmd struct { 16 | User model.User `json:"user"` 17 | } 18 | 19 | type LoginCmdRes struct { 20 | Code int `json:"code"` 21 | Error string `json:"error"` 22 | } 23 | -------------------------------------------------------------------------------- /loadbalance/balance/instance.go: -------------------------------------------------------------------------------- 1 | package balance 2 | 3 | import "strconv" 4 | 5 | type Instance struct { 6 | host string 7 | port int 8 | } 9 | 10 | func NewInstance(host string,port int) *Instance{ 11 | return &Instance{ 12 | host:host, 13 | port:port, 14 | } 15 | } 16 | 17 | func (p *Instance) GetHost() string{ 18 | return p.host 19 | } 20 | 21 | func (p *Instance) GetPort() int{ 22 | return p.port 23 | } 24 | 25 | func (p *Instance) String() string{ 26 | return p.host + ":" +strconv.Itoa(p.port) 27 | } -------------------------------------------------------------------------------- /seckill/SecLayer/service/seclimit.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | type SecLimit struct { 4 | count int 5 | curTime int64 6 | } 7 | 8 | func (p *SecLimit) Count(nowTime int64) (curCount int) { 9 | if p.curTime != nowTime { 10 | p.count = 1 11 | p.curTime = nowTime 12 | curCount = p.count 13 | return 14 | } 15 | 16 | p.count++ 17 | curCount = p.count 18 | return 19 | } 20 | 21 | func (p *SecLimit) Check(nowTime int64) int { 22 | if p.curTime != nowTime { 23 | return 0 24 | } 25 | return p.count 26 | } 27 | -------------------------------------------------------------------------------- /loadbalance/balance/random.go: -------------------------------------------------------------------------------- 1 | package balance 2 | 3 | import ( 4 | "errors" 5 | "math/rand" 6 | ) 7 | 8 | func init(){ 9 | RegisterBalance("random",&RandomBalance{}) 10 | } 11 | 12 | type RandomBalance struct { 13 | } 14 | 15 | func (p *RandomBalance) DoBalance(insts []*Instance,key ...string) (inst *Instance,err error){ 16 | 17 | if len(insts) == 0{ 18 | err = errors.New("no instance") 19 | return 20 | } 21 | 22 | lens := len(insts) 23 | index := rand.Intn(lens) 24 | inst = insts[index] 25 | return 26 | } 27 | -------------------------------------------------------------------------------- /crawler-distributed/worker/server/worker_main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "golang-awesome/crawler-distributed/config" 7 | "golang-awesome/crawler-distributed/rpcsupport" 8 | "golang-awesome/crawler-distributed/worker" 9 | "log" 10 | ) 11 | 12 | var port = flag.Int("port", config.WorkerPort0,"请输入默认工作端口号(默认10086)") 13 | 14 | func main(){ 15 | flag.Parse() 16 | port2 := fmt.Sprintf(":%d", *port) 17 | 18 | fmt.Println("Worker Server Start At:", port2) 19 | log.Fatal(rpcsupport.ServeRpc(port2,worker.CrawlService{})) 20 | } 21 | -------------------------------------------------------------------------------- /logcollection/logagent/main/ip.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | ) 7 | 8 | var ( 9 | localIPArray []string 10 | ) 11 | 12 | func init() { 13 | addrs, e := net.InterfaceAddrs() 14 | if e != nil { 15 | panic(fmt.Sprintf("get local ip failed, %v", e)) 16 | } 17 | 18 | for _, addr := range addrs { 19 | if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { 20 | if ipnet.IP.To4() != nil { 21 | localIPArray = append(localIPArray, ipnet.IP.String()) 22 | } 23 | } 24 | } 25 | 26 | fmt.Println(localIPArray) 27 | } 28 | -------------------------------------------------------------------------------- /video_server/web/defs.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type ApiBody struct { 4 | Url string `json:"url"` 5 | Method string `json:"method"` 6 | ReqBody string `json:"req_body"` 7 | } 8 | 9 | type Err struct { 10 | Error string `json:"error"` 11 | ErrorCode string `json:"error_code"` 12 | } 13 | 14 | var ( 15 | ErrorRequestNotRecognized = Err{Error: "api not recognized, bad request", ErrorCode: "001"} 16 | ErrorRequestBodyParseFailed = Err{Error: "request body is not correct", ErrorCode: "002"} 17 | ErrorInternalFaults = Err{Error: "internal server errror", ErrorCode: "003"} 18 | ) -------------------------------------------------------------------------------- /seckill/SecProxy/service/seclimit.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | type Limit struct { 4 | secLimit TimeLimit 5 | minLimit TimeLimit 6 | } 7 | 8 | type SecLimit struct { 9 | count int 10 | curTime int64 11 | } 12 | 13 | func (p *SecLimit) Count(nowTime int64) (curCount int) { 14 | if p.curTime != nowTime{ 15 | p.count = 1 16 | p.curTime = nowTime 17 | curCount = p.count 18 | return 19 | } 20 | 21 | p.count++ 22 | curCount = p.count 23 | return 24 | } 25 | 26 | func (p *SecLimit) Check(nowTime int64)int{ 27 | if p.curTime != nowTime{ 28 | return 0 29 | } 30 | 31 | return p.count 32 | } -------------------------------------------------------------------------------- /video_server/web/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/julienschmidt/httprouter" 5 | "net/http" 6 | ) 7 | 8 | func RegisterHandler() (r *httprouter.Router) { 9 | r = httprouter.New() 10 | r.GET("/", homeHandler) 11 | r.POST("/", homeHandler) 12 | r.GET("/userhome", userHomeHandler) 13 | r.POST("/userhome", userHomeHandler) 14 | r.POST("/api", apiHandler) 15 | r.POST("/upload/:vid-id", proxyHandler) 16 | r.ServeFiles("/statics/*filepath", http.Dir("./template")) 17 | return 18 | } 19 | 20 | func main() { 21 | r := RegisterHandler() 22 | http.ListenAndServe(":8080", r) 23 | } 24 | -------------------------------------------------------------------------------- /video_server/scheduler/handlers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/julienschmidt/httprouter" 5 | "golang-awesome/video_server/scheduler/dbops" 6 | "net/http" 7 | ) 8 | 9 | func vidDelRecHandler(w http.ResponseWriter,r *http.Request,p httprouter.Params){ 10 | vid := p.ByName("vid-id") 11 | if len(vid) == 0 { 12 | sendResponse(w,400, "video id should not be empty") 13 | } 14 | 15 | err := dbops.AddVideoDeletionRecord(vid) 16 | if err != nil { 17 | sendResponse(w, 500, "Internal server error") 18 | return 19 | } 20 | sendResponse(w,200, "delete video successfully") 21 | return 22 | } 23 | -------------------------------------------------------------------------------- /crawler-distributed/persist/rpc.go: -------------------------------------------------------------------------------- 1 | package persist 2 | 3 | import ( 4 | "golang-awesome/crawler/engine" 5 | "golang-awesome/crawler/persist" 6 | "gopkg.in/olivere/elastic.v5" 7 | "log" 8 | ) 9 | 10 | type ItemSaverService struct{ 11 | Client *elastic.Client 12 | Index string 13 | } 14 | 15 | func (s *ItemSaverService) Save(item engine.Item, result *string) error { 16 | 17 | err := persist.Save(s.Client, s.Index, item) 18 | log.Printf("save profile %s", item.Url) 19 | if err == nil { 20 | *result = "ok" 21 | }else { 22 | log.Printf("item:%s save error: %s", item, err) 23 | } 24 | 25 | return err 26 | } 27 | -------------------------------------------------------------------------------- /logcollection/logagent/main/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/astaxie/beego/logs" 5 | "golang-awesome/logcollection/logagent/kafka" 6 | "golang-awesome/logcollection/logagent/tail" 7 | "time" 8 | ) 9 | 10 | func serverRun() (err error) { 11 | for { 12 | msg := tail.GetOneLine() 13 | err = sendToKafka(msg) 14 | if err != nil { 15 | logs.Error("send to kafka failed,err:%v", err) 16 | time.Sleep(time.Second) 17 | continue 18 | } 19 | } 20 | return 21 | } 22 | 23 | func sendToKafka(msg *tail.TextMsg) (err error) { 24 | err = kafka.SendToKafka(msg.Msg, msg.Topic) 25 | return 26 | } 27 | -------------------------------------------------------------------------------- /seckill/SecLayer/service/user_history.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import "sync" 4 | 5 | type UserBuyHistory struct{ 6 | history map[int]int 7 | lock sync.RWMutex 8 | } 9 | 10 | func (p *UserBuyHistory) GetProductBuyCount(productId int) int{ 11 | p.lock.RLock() 12 | defer p.lock.RUnlock() 13 | 14 | count ,_ :=p.history[productId] 15 | return count 16 | } 17 | 18 | func (p *UserBuyHistory) Add(productId int,count int){ 19 | p.lock.RLock() 20 | defer p.lock.RUnlock() 21 | 22 | cur, ok :=p.history[productId] 23 | if !ok { 24 | cur = count 25 | }else { 26 | cur += count 27 | } 28 | 29 | p.history[productId] = cur 30 | } -------------------------------------------------------------------------------- /seckill/SecProxy/service/minLimit.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | 4 | type TimeLimit interface{ 5 | Count(nowTime int64)(curCount int) 6 | Check(nowTime int64) int 7 | } 8 | 9 | type MinLimit struct { 10 | count int 11 | curTime int64 12 | } 13 | 14 | func (p *MinLimit) Count(nowTime int64)(curCount int){ 15 | if nowTime -p.curTime > 60 { 16 | p.count =1 17 | p.curTime = nowTime 18 | curCount = p.count 19 | return 20 | } 21 | p.count ++ 22 | curCount = p.count 23 | return 24 | } 25 | 26 | func (p *MinLimit) Check(nowTime int64) int { 27 | if nowTime - p.curTime > 60 { 28 | return 0 29 | } 30 | 31 | return p.count 32 | } -------------------------------------------------------------------------------- /crawler/scheduler/simple.go: -------------------------------------------------------------------------------- 1 | package scheduler 2 | 3 | import "golang-awesome/crawler/engine" 4 | 5 | //简单的并发处理,所有工作协程,公用一个输入通道 6 | type SimpleScheduler struct { 7 | WorkerChan chan engine.Request 8 | } 9 | 10 | func (s *SimpleScheduler) Run() { 11 | s.WorkerChan = make(chan engine.Request) 12 | } 13 | 14 | func (s *SimpleScheduler) Submit(request engine.Request) { 15 | go func() { 16 | s.WorkerChan <- request 17 | }() 18 | } 19 | 20 | func (s *SimpleScheduler) GetWorkChan() chan engine.Request { 21 | return s.WorkerChan 22 | } 23 | 24 | func (s *SimpleScheduler) WorkReady(chan engine.Request) { 25 | panic("implement me") 26 | } 27 | -------------------------------------------------------------------------------- /goroutine/chart/chat_server/main/redis.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/garyburd/redigo/redis" 4 | import "time" 5 | 6 | var pool *redis.Pool 7 | 8 | func initRedis(addr string, idleConn, maxConn int, idleTimeout time.Duration) { 9 | 10 | pool = &redis.Pool{ 11 | MaxIdle: idleConn, 12 | MaxActive: maxConn, 13 | IdleTimeout: idleTimeout, 14 | Dial: func() (redis.Conn, error) { 15 | return redis.Dial("tcp", addr) 16 | }, 17 | } 18 | return 19 | } 20 | 21 | func GetConn() redis.Conn { 22 | return pool.Get() 23 | } 24 | 25 | func PutConn(conn redis.Conn) { 26 | conn.Close() 27 | } 28 | -------------------------------------------------------------------------------- /loadbalance/balance/roundrobin.go: -------------------------------------------------------------------------------- 1 | package balance 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | func init() { 8 | RegisterBalance("roundrobin", &RoundRobinBalance{}) 9 | } 10 | 11 | type RoundRobinBalance struct { 12 | curIndex int 13 | } 14 | 15 | func (p *RoundRobinBalance) DoBalance(insts []*Instance, key ...string) (inst *Instance, err error) { 16 | 17 | if len(insts) == 0 { 18 | err = errors.New("no instance") 19 | return 20 | } 21 | 22 | lens := len(insts) 23 | 24 | if p.curIndex >= lens { 25 | p.curIndex = 0 26 | } 27 | 28 | inst = insts[p.curIndex] 29 | p.curIndex = (p.curIndex + 1) % lens 30 | 31 | return 32 | } 33 | -------------------------------------------------------------------------------- /crawler/engine/simple.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import "github.com/astaxie/beego/logs" 4 | 5 | type SimpleEngine struct { 6 | 7 | } 8 | 9 | func (e *SimpleEngine) Run(queue ...Request){ 10 | var count = 0 11 | for len (queue) >0 { 12 | r := queue[0] 13 | queue = append(queue[1:]) 14 | 15 | results, err := Worker(r) 16 | if err != nil{ 17 | continue 18 | } 19 | for _, r := range results.Requests{ 20 | if IsDuplicate(r.Url){ 21 | continue 22 | } 23 | queue = append(queue,r) 24 | } 25 | 26 | for _, item :=range results.Items{ 27 | count ++ 28 | logs.Warn("Got Item: $%d %v",count,item) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /video_server/scheduler/taskrunner/trmain.go: -------------------------------------------------------------------------------- 1 | package taskrunner 2 | 3 | import "time" 4 | 5 | type Worker struct { 6 | ticker *time.Ticker 7 | runner *Runner 8 | } 9 | 10 | func NewWorker(interval time.Duration, r *Runner) *Worker { 11 | return &Worker{ 12 | ticker: time.NewTicker(interval * time.Second), 13 | runner: r, 14 | } 15 | } 16 | 17 | func (w *Worker) startWorker() { 18 | for { 19 | select { 20 | case <-w.ticker.C: 21 | go w.runner.StartAll() 22 | } 23 | } 24 | } 25 | 26 | func Start() { 27 | r := NewRunner(3, true, VideoClearDispathcer, VideoClearExecutor) 28 | w := NewWorker(3, r) 29 | go w.startWorker() 30 | } 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 项目说明 2 | Golang学习笔记,代码整理 3 | ## 目录说明 4 | * ### crawler-distributed 5 | 分布式爬虫,利用Go在并发性上的天然优势实现爬虫任务的分发和调度完成并发需求;使用rpc分离并独立单机版中的并发任务,实现分布式爬虫。 6 | 7 | * ### crawler 8 | 单任务爬虫,应用广度优先算法框架,嵌入数据爬取,信息提取等逻辑实现基本爬虫任务。 9 | 10 | * ### goroutine 11 | 使用goroutine实现的聊天服务器,迷宫算法等。 12 | 13 | * ### loadbalance 14 | 一致性Hash负载均衡的简单实现 15 | 16 | * ### logcollection 17 | 日志收集系统,使用tail读取收集日志,kafka进行分发,beego实现后台管理页面,etcd对服务器ip、目录配置切换 18 | 19 | * ### rpc 20 | 使用json实现rpc调用 21 | 22 | * ### seckill 23 | 商城秒杀系统,秒杀接入层到逻辑层通过redis队列(LPUSH)来通信,完成秒杀逻辑后返回(RPOP)结果 24 | 25 | * ### video_server 26 | 视频点播系统,go语言原生template实现web后端,集成阿里云SDK实现Cloud Native 27 | -------------------------------------------------------------------------------- /crawler/zhenai/parser/citylist.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "golang-awesome/crawler/engine" 5 | "regexp" 6 | ) 7 | 8 | const cityListReg = `]*>([^<]+)` 9 | 10 | func ParseCityList(contents []byte,_ string) engine.ParserResult{ 11 | results := engine.ParserResult{} 12 | 13 | reg := regexp.MustCompile(cityListReg) 14 | matches := reg.FindAllSubmatch(contents,-1) 15 | 16 | 17 | for _, m :=range matches{ 18 | results.Requests = append(results.Requests, engine.Request{ 19 | Url: string(m[1]), 20 | Parse:engine.NewFuncParser(ParseCity, "ParseCity"), 21 | }) 22 | } 23 | return results 24 | } -------------------------------------------------------------------------------- /rpc/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "golang-awesome/rpc" 6 | "net" 7 | "net/rpc/jsonrpc" 8 | ) 9 | 10 | func main(){ 11 | conn, err := net.Dial("tcp",":1234") 12 | if err != nil { 13 | panic(err) 14 | } 15 | 16 | client := jsonrpc.NewClient(conn) 17 | var result float64 18 | err = client.Call("DemoService.Div", 19 | rpcDemo.Args{10,3},&result) 20 | if err != nil { 21 | fmt.Println(err) 22 | }else { 23 | fmt.Println(result) 24 | } 25 | err = client.Call("DemoService.Div", 26 | rpcDemo.Args{10,0},&result) 27 | if err != nil { 28 | fmt.Println(err) 29 | }else { 30 | fmt.Println(result) 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /crawler-distributed/worker/client/worker.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "golang-awesome/crawler-distributed/config" 5 | "golang-awesome/crawler-distributed/worker" 6 | "golang-awesome/crawler/engine" 7 | "net/rpc" 8 | ) 9 | 10 | func CreateProcessor(clientChan chan*rpc.Client)engine.Processor{ 11 | return func(request engine.Request) (result engine.ParserResult, e error) { 12 | var sReq = worker.SerializeRequest(request) 13 | var sResult worker.ParseResult 14 | c := <-clientChan 15 | err := c.Call(config.CrawlServiceRpc,sReq, &sResult) 16 | if err != nil{ 17 | return engine.ParserResult{},err 18 | } 19 | return worker.DeserializeResult(sResult), nil 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /video_server/vendor/jayce/config.go: -------------------------------------------------------------------------------- 1 | package jayce 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | ) 7 | 8 | type Configuration struct { 9 | LBAddr string `json:"lb_addr"` 10 | OssAddr string `json:"oss_addr"` 11 | } 12 | 13 | var configuration *Configuration 14 | 15 | func init() { 16 | file, _ := os.Open("./conf.json") 17 | defer file.Close() 18 | 19 | decoder := json.NewDecoder(file) 20 | configuration = &Configuration{} 21 | 22 | err := decoder.Decode(configuration) 23 | if err != nil { 24 | panic(err) 25 | } 26 | } 27 | 28 | func GetLbAddr() string { 29 | return configuration.LBAddr 30 | } 31 | 32 | func GetOssAddr() string { 33 | return configuration.OssAddr 34 | } 35 | -------------------------------------------------------------------------------- /video_server/streamserver/limiter.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "log" 4 | 5 | type ConnLimiter struct { 6 | concurrentConn int 7 | bucket chan int 8 | } 9 | 10 | func NewConnLimiter(cc int) *ConnLimiter { 11 | return &ConnLimiter{ 12 | concurrentConn: cc, 13 | bucket: make(chan int, cc), 14 | } 15 | } 16 | 17 | func (cl *ConnLimiter) GetConn() bool { 18 | if len(cl.bucket) >= cl.concurrentConn { 19 | log.Printf("reached the rate limitation") 20 | return false 21 | } 22 | 23 | cl.bucket <- 1 24 | log.Printf("successfully got connection") 25 | return true 26 | } 27 | 28 | func (cl *ConnLimiter) ReleaseConn() { 29 | c := <-cl.bucket 30 | log.Printf("new connection coming : %d", c) 31 | } 32 | -------------------------------------------------------------------------------- /video_server/api/defs/err.go: -------------------------------------------------------------------------------- 1 | package defs 2 | 3 | type Err struct { 4 | Error string `json:"error"` 5 | ErrorCode string `json:"error_code"` 6 | } 7 | 8 | type ErrResponse struct { 9 | HttpSC int 10 | Error Err 11 | } 12 | 13 | var ( 14 | ErrorRequestBodyParseFailed = ErrResponse{HttpSC: 400, Error: Err{Error: "Request body is not correct", ErrorCode: "001"}} 15 | ErrorNotAuthUser = ErrResponse{HttpSC: 401, Error: Err{Error: "User authentication failed.", ErrorCode: "002"}} 16 | ErrorDBError = ErrResponse{HttpSC: 500, Error: Err{Error: "DB ops failed", ErrorCode: "003"}} 17 | ErrorInternalFaults = ErrResponse{HttpSC: 500, Error: Err{Error: "Internal service error", ErrorCode: "004"}} 18 | ) 19 | -------------------------------------------------------------------------------- /crawler-distributed/rpcsupport/rpc.go: -------------------------------------------------------------------------------- 1 | package rpcsupport 2 | 3 | import ( 4 | "log" 5 | "net" 6 | "net/rpc" 7 | "net/rpc/jsonrpc" 8 | ) 9 | 10 | func ServeRpc(host string, service interface{}) error{ 11 | rpc.Register(service) 12 | listener, err := net.Listen("tcp", host) 13 | if err != nil { 14 | return err 15 | } 16 | 17 | for { 18 | conn, err := listener.Accept() 19 | if err != nil { 20 | log.Panicf("accetp error: %v", err) 21 | continue 22 | } 23 | go jsonrpc.ServeConn(conn) 24 | } 25 | return nil 26 | } 27 | 28 | func NewClient(host string)(*rpc.Client,error){ 29 | conn, err := net.Dial("tcp", host) 30 | if err != nil { 31 | return nil, err 32 | } 33 | 34 | return jsonrpc.NewClient(conn), nil 35 | } 36 | -------------------------------------------------------------------------------- /logcollection/tail/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/hpcloud/tail" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | func main(){ 10 | filename := "my.log" 11 | tails, err := tail.TailFile(filename, tail.Config{ 12 | ReOpen: true, 13 | Follow: true, 14 | Location: &tail.SeekInfo{Offset:0,Whence:3}, 15 | MustExist: false, 16 | Poll: true, 17 | }) 18 | 19 | if err != nil { 20 | fmt.Println("tail file err:",err) 21 | return 22 | } 23 | 24 | var msg *tail.Line 25 | var ok bool 26 | for { 27 | msg ,ok = <-tails.Lines 28 | if !ok { 29 | fmt.Println("tail file close reopen,filename:%s\n",tails.Filename) 30 | time.Sleep(100 * time.Millisecond) 31 | continue 32 | } 33 | fmt.Println("msg:",msg) 34 | } 35 | } -------------------------------------------------------------------------------- /goroutine/fibonacii/fibonacii.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "strings" 8 | ) 9 | 10 | func fibonacii() intGen{ 11 | a, b := 0, 1 12 | return func() int { 13 | a, b = b, a+b 14 | return a 15 | } 16 | } 17 | 18 | type intGen func() int 19 | 20 | func (g intGen) Read(p []byte) (n int, err error) { 21 | next := g() 22 | if next > 10000{ 23 | return 0, io.EOF 24 | } 25 | s := fmt.Sprintf("%d\n",next) 26 | return strings.NewReader(s).Read(p) 27 | } 28 | 29 | func printFileContents(reader io.Reader){ 30 | scanner := bufio.NewScanner(reader) 31 | 32 | for scanner.Scan(){ 33 | fmt.Println(scanner.Text()) 34 | } 35 | } 36 | 37 | func main() { 38 | f := fibonacii() 39 | printFileContents(f) 40 | } -------------------------------------------------------------------------------- /loadbalance/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang-awesome/loadbalance/balance" 5 | "fmt" 6 | "math/rand" 7 | "time" 8 | "os" 9 | ) 10 | 11 | func main() { 12 | var insts []*balance.Instance 13 | 14 | for i := 0; i < 16; i++ { 15 | host := fmt.Sprintf("192.168.%d.%d", rand.Intn(255), rand.Intn(255)) 16 | one := balance.NewInstance(host, 8080) 17 | insts = append(insts, one) 18 | } 19 | 20 | var balanceName = "random" 21 | 22 | if len(os.Args) > 1 { 23 | balanceName = os.Args[1] 24 | } 25 | 26 | for { 27 | inst, err := balance.DoBalance(balanceName, insts) 28 | if err != nil { 29 | fmt.Println("do banlance err:", err) 30 | } 31 | 32 | fmt.Println(inst) 33 | time.Sleep(time.Second) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /goroutine/chart/chat_server/main/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | ) 7 | 8 | func runServer(addr string) (err error) { 9 | l, err := net.Listen("tcp", addr) 10 | if err != nil { 11 | fmt.Println("listen failed, ", err) 12 | return 13 | } 14 | 15 | for { 16 | conn, err := l.Accept() 17 | if err != nil { 18 | fmt.Println("accept failed, ", err) 19 | continue 20 | } 21 | 22 | go proccess(conn) 23 | } 24 | } 25 | 26 | func proccess(conn net.Conn) { 27 | 28 | defer conn.Close() 29 | client := &Client{ 30 | conn: conn, 31 | } 32 | 33 | err := client.Process() 34 | if err != nil { 35 | fmt.Println("client process failed, ", err) 36 | return 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /crawler-distributed/persist/client/itemsaver.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "golang-awesome/crawler-distributed/rpcsupport" 5 | "golang-awesome/crawler/engine" 6 | "log" 7 | ) 8 | 9 | //json rpc client 10 | //将数据通过rpc传送给rpc-server 11 | func ItemSaver(host string)(chan engine.Item,error){ 12 | ch := make (chan engine.Item,1024) 13 | 14 | rpc, err := rpcsupport.NewClient(host) 15 | go func() { 16 | itemCount := 0 17 | for item := range ch { 18 | itemCount ++ 19 | log.Printf("item saver: got item #%d: %v",itemCount, item) 20 | 21 | result := "" 22 | rpc.Call("ItemSaverService.Save",item,&result) 23 | 24 | if err != nil { 25 | log.Printf("Item Saver: Save error: %v",err) 26 | } 27 | } 28 | }() 29 | 30 | return ch,err 31 | } -------------------------------------------------------------------------------- /crawler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang-awesome/crawler/engine" 5 | "golang-awesome/crawler/persist" 6 | "golang-awesome/crawler/scheduler" 7 | "golang-awesome/crawler/zhenai/parser" 8 | ) 9 | 10 | func main(){ 11 | itemChan, err := persist.ItemSaver("profiles") 12 | if err != nil { 13 | panic(err) 14 | } 15 | 16 | var seed []engine.Request 17 | 18 | seed = []engine.Request{ 19 | { 20 | Url: "http://www.zhenai.com/zhenghun", 21 | Parse: engine.NewFuncParser(parser.ParseCityList, "ParseCityList"), 22 | }, 23 | } 24 | e := engine.ConcurrentEngine{ 25 | MaxWorkerCount: 100, 26 | Scheduler: &scheduler.QueuedScheduler{}, 27 | ItemChan: itemChan, 28 | RequestWorker: engine.Worker, 29 | } 30 | 31 | e.Run(seed...) 32 | } -------------------------------------------------------------------------------- /loadbalance/balance/manager.go: -------------------------------------------------------------------------------- 1 | package balance 2 | 3 | import "fmt" 4 | 5 | type BalanceMgr struct { 6 | allBalancer map[string]Balance 7 | } 8 | 9 | 10 | 11 | var mgr = BalanceMgr{ 12 | allBalancer:make(map[string]Balance), 13 | } 14 | 15 | func (p *BalanceMgr) registerBalance(name string,b Balance){ 16 | p.allBalancer[name] = b 17 | } 18 | 19 | func RegisterBalance(name string,b Balance){ 20 | mgr.registerBalance(name,b) 21 | } 22 | 23 | func DoBalance(name string,insts []*Instance) (inst *Instance,err error){ 24 | balance, ok := mgr.allBalancer[name] 25 | 26 | if !ok { 27 | err = fmt.Errorf("not found %s balance",name) 28 | return 29 | } 30 | 31 | fmt.Printf("use %s balance \n",name) 32 | inst,err = balance.DoBalance(insts) 33 | return 34 | } -------------------------------------------------------------------------------- /loadbalance/main/hash.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang-awesome/loadbalance/balance" 5 | "fmt" 6 | "math/rand" 7 | "hash/crc32" 8 | ) 9 | 10 | func init(){ 11 | balance.RegisterBalance("hash",&Hashbalance{}) 12 | } 13 | 14 | type Hashbalance struct { 15 | } 16 | 17 | func (p *Hashbalance) DoBalance(insts []*balance.Instance, key ...string) (inst *balance.Instance, err error) { 18 | 19 | var defKey = fmt.Sprintf("%d", rand.Int()) 20 | if len(key) > 0 { 21 | defKey = key[0] 22 | } 23 | 24 | lens := len(insts) 25 | if lens == 0 { 26 | err = fmt.Errorf("no backend balance") 27 | return 28 | } 29 | 30 | crcTable := crc32.MakeTable(crc32.IEEE) 31 | hashVal := crc32.Checksum([]byte(defKey), crcTable) 32 | index := int(hashVal) % lens 33 | inst = insts[index] 34 | 35 | return 36 | } 37 | -------------------------------------------------------------------------------- /crawler-distributed/persist/server/saver.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "golang-awesome/crawler-distributed/config" 6 | "golang-awesome/crawler-distributed/persist" 7 | "golang-awesome/crawler-distributed/rpcsupport" 8 | "gopkg.in/olivere/elastic.v5" 9 | "log" 10 | ) 11 | 12 | func main(){ 13 | fmt.Printf("item saver start at: %v", config.ItemSaverPort) 14 | log.Fatal(serveRpc(config.ItemSaverPort,config.ElasticIndex)) 15 | } 16 | 17 | 18 | func serveRpc(host, index string)error { 19 | client, err := elastic.NewClient( 20 | elastic.SetSniff(false), 21 | elastic.SetBasicAuth("elastic", "changeme")) 22 | 23 | if err != nil { 24 | return err 25 | } 26 | 27 | return rpcsupport.ServeRpc(host, 28 | &persist.ItemSaverService{ 29 | Client:client, 30 | Index:index, 31 | }, 32 | ) 33 | } -------------------------------------------------------------------------------- /seckill/SecProxy/tools/httpclient/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http" 7 | "sync" 8 | "time" 9 | ) 10 | 11 | func main() { 12 | start := time.Now().Unix() 13 | wg := sync.WaitGroup{} 14 | for i := 1; i < 100; i++ { 15 | wg.Add(1) 16 | go httpGet(i, &wg) 17 | } 18 | wg.Wait() 19 | fmt.Printf("the progress exit, use %d s" ,time.Now().Unix() -start) 20 | } 21 | func httpGet(userId int,wg *sync.WaitGroup) { 22 | url := fmt.Sprintf("http://localhost:9090/seckill?product_id=1002&user_id=%d",userId) 23 | resp, err := http.Get(url) 24 | if err != nil { 25 | fmt.Println(err) 26 | } 27 | 28 | defer resp.Body.Close() 29 | bytes, err := ioutil.ReadAll(resp.Body) 30 | if err != nil { 31 | fmt.Println(err) 32 | } 33 | 34 | fmt.Println(string(bytes)) 35 | wg.Done() 36 | } -------------------------------------------------------------------------------- /video_server/api/auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang-awesome/video_server/api/defs" 5 | "golang-awesome/video_server/api/session" 6 | "net/http" 7 | ) 8 | 9 | var HEADER_FIELD_SESSION = "X-Session-Id" 10 | var HEADER_FIELD_UNAME = "X-User-Name" 11 | 12 | func validateUserSession(r *http.Request) bool { 13 | sid := r.Header.Get(HEADER_FIELD_SESSION) 14 | if len(sid) == 0 { 15 | return false 16 | } 17 | 18 | uname, ok := session.IsSessionExpired(sid) 19 | if ok { 20 | return false 21 | } 22 | 23 | r.Header.Add(HEADER_FIELD_UNAME, uname) 24 | return true 25 | } 26 | 27 | 28 | func ValidateUser(w http.ResponseWriter, r *http.Request) bool { 29 | uname := r.Header.Get(HEADER_FIELD_UNAME) 30 | if len(uname) == 0 { 31 | sendErrorResponse(w, defs.ErrorNotAuthUser) 32 | return false 33 | } 34 | return true 35 | } -------------------------------------------------------------------------------- /logcollection/logagent/main/log.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/astaxie/beego/logs" 7 | ) 8 | 9 | func convertLogLevel(level string) int { 10 | switch level { 11 | case "debug": 12 | return logs.LevelDebug 13 | case "warn": 14 | return logs.LevelWarn 15 | case "info": 16 | return logs.LevelInfo 17 | case "trace": 18 | return logs.LevelTrace 19 | } 20 | 21 | return logs.LevelDebug 22 | } 23 | 24 | func initLogger() (err error) { 25 | 26 | config := make(map[string]interface{}) 27 | config["filename"] = appConfig.logPath 28 | config["level"] = convertLogLevel(appConfig.logLevel) 29 | 30 | bytes, err := json.Marshal(config) 31 | 32 | if err != nil { 33 | fmt.Println("initLogger failed, marshal err:", err) 34 | return 35 | } 36 | 37 | logs.SetLogger(logs.AdapterFile, string(bytes)) 38 | return 39 | } 40 | -------------------------------------------------------------------------------- /crawler/zhenai/parser/profile_test.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "log" 7 | "regexp" 8 | "testing" 9 | ) 10 | 11 | func TestReg(t *testing.T){ 12 | body, err := ioutil.ReadFile("profile_test_data.html") 13 | if err != nil { 14 | log.Printf("read file err, %v",err) 15 | return 16 | } 17 | 18 | //utf8Reader := transform.NewReader(bytes.NewReader(body),simplifiedchinese.GBK.NewDecoder()) 19 | //body1, _ := ioutil.ReadAll(utf8Reader) 20 | 21 | profileReg := regexp.MustCompile(`
([^<]+)
`) 22 | submatch := profileReg.FindAllSubmatch(body,-1) 23 | 24 | var IdRe = regexp.MustCompile(`
ID:([^<]+)
`) 25 | findSubmatch := IdRe.FindSubmatch(body) 26 | fmt.Printf("%v \n",string(findSubmatch[1])) 27 | for _, m := range submatch{ 28 | fmt.Printf("%v \n",string(m[1])) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /logcollection/web_admin/routers/router.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | "golang-awesome/logcollection/web_admin/controllers/AppController" 6 | "golang-awesome/logcollection/web_admin/controllers/LogController" 7 | ) 8 | 9 | func init() { 10 | beego.Router("/index", &AppController.AppController{}, "*:AppList") 11 | 12 | beego.Router("/app/list", &AppController.AppController{}, "*:AppList") 13 | beego.Router("/app/apply", &AppController.AppController{}, "*:AppApply") 14 | beego.Router("/app/create", &AppController.AppController{}, "*:AppCreate") 15 | 16 | beego.Router("/log/list", &LogController.LogController{}, "*:LogList") 17 | beego.Router("/log/apply", &LogController.LogController{}, "*:LogApply") 18 | beego.Router("/log/create", &LogController.LogController{}, "*:LogCreate") 19 | 20 | 21 | beego.Router("/hello", &AppController.AppController{}, "*:TestRestful") 22 | } 23 | -------------------------------------------------------------------------------- /goroutine/interfac/student.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "sort" 7 | ) 8 | 9 | type Student struct { 10 | name string 11 | age int 12 | score float32 13 | } 14 | 15 | type StudentList []Student 16 | 17 | func (p StudentList) Len() int { 18 | return len(p) 19 | } 20 | 21 | func (p StudentList) Less(i, j int) bool { 22 | return p[i].age < p[j].age 23 | } 24 | 25 | func (p StudentList) Swap(i, j int) { 26 | p[i], p[j] = p[j], p[i] 27 | } 28 | 29 | func main() { 30 | var stus StudentList 31 | 32 | for i := 0; i < 10; i++ { 33 | stu := Student{ 34 | name: fmt.Sprintf("stu%d", rand.Intn(100)), 35 | age: rand.Intn(100), 36 | score: rand.Float32() * 100, 37 | } 38 | stus = append(stus, stu) 39 | } 40 | 41 | for _,v := range stus{ 42 | fmt.Println(v) 43 | } 44 | fmt.Println("\n\n") 45 | sort.Sort(stus) 46 | 47 | for _,v := range stus{ 48 | fmt.Println(v) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /logcollection/log_transfer/log.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | 7 | "github.com/astaxie/beego/logs" 8 | ) 9 | 10 | func convertLogLevel(level string) int { 11 | 12 | switch level { 13 | case "debug": 14 | return logs.LevelDebug 15 | case "warn": 16 | return logs.LevelWarn 17 | case "info": 18 | return logs.LevelInfo 19 | case "trace": 20 | return logs.LevelTrace 21 | } 22 | 23 | return logs.LevelDebug 24 | } 25 | 26 | func initLogger(logPath string, logLevel string) (err error) { 27 | 28 | config := make(map[string]interface{}) 29 | config["filename"] = logPath 30 | config["level"] = convertLogLevel(logLevel) 31 | 32 | configStr, err := json.Marshal(config) 33 | if err != nil { 34 | fmt.Println("initLogger failed, marshal err:", err) 35 | return 36 | } 37 | 38 | logs.SetLogger(logs.AdapterFile, string(configStr)) 39 | return 40 | } 41 | -------------------------------------------------------------------------------- /logcollection/elasticsearch/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | 8 | elastic "gopkg.in/olivere/elastic.v5" 9 | ) 10 | 11 | type Tweet struct { 12 | User string 13 | Message string 14 | } 15 | 16 | func main() { 17 | client, err := elastic.NewClient(elastic.SetSniff(false), 18 | elastic.SetURL("http://localhost:9200/"), 19 | elastic.SetBasicAuth("elastic","changeme")) 20 | if err != nil { 21 | fmt.Println("connect es error:", err) 22 | return 23 | } 24 | 25 | fmt.Println("conn es succ") 26 | 27 | ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second) 28 | 29 | tweet := Tweet{User: "olivere", Message: "Take Five"} 30 | _, err = client.Index(). 31 | Index("twitter"). 32 | Type("tweet"). 33 | Id("1"). 34 | BodyJson(tweet). 35 | Do(ctx) 36 | if err != nil { 37 | // Handle error 38 | panic(err) 39 | return 40 | } 41 | cancelFunc() 42 | fmt.Println("insert succ") 43 | } 44 | -------------------------------------------------------------------------------- /video_server/db.sql: -------------------------------------------------------------------------------- 1 | # video_server 2 | 3 | create table comments ( 4 | id varchar(64) not null, 5 | video_id varchar(64) , 6 | content text, 7 | time datetime default current_timestamp , 8 | primary key (id) 9 | ); 10 | 11 | create table sessions ( 12 | session_id tinytext not null, 13 | TTL tinytext, 14 | login_name text 15 | ); 16 | 17 | alter table sessions add primary key (session_id(64)); 18 | 19 | create table users ( 20 | id int unsigned not null auto_increment, 21 | login_name varchar(64), 22 | pwd text not null, 23 | unique key(login_name), 24 | primary key (id) 25 | ); 26 | 27 | create table video_del_rec ( 28 | video_id varchar(64) not null, 29 | primary key (video_id) 30 | ); 31 | 32 | create table video_info ( 33 | id varchar(64) not null, 34 | author_id int(10), 35 | name text, 36 | display_ctime text, 37 | create_time datetime default current_timestamp , 38 | primary key (id) 39 | ); -------------------------------------------------------------------------------- /goroutine/channel/test/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main(){ 9 | msg := make(chan string, 1) 10 | 11 | for i := 0; i < 16; i++ { 12 | go send(msg,i) 13 | } 14 | 15 | for i := 0; i < 16; i++ { 16 | go recv(msg, i) 17 | } 18 | 19 | time.Sleep(time.Hour) 20 | } 21 | 22 | func send(msg chan string,i int) { 23 | str := fmt.Sprintf("this msg is from %dth goroutine, ",i) 24 | for { 25 | msg <- str 26 | time.Sleep(time.Second) 27 | } 28 | } 29 | 30 | func recv(msgChan chan string, i int) { 31 | 32 | //for msg := range msgChan { 33 | // fmt.Printf("%sand receivced by %dth goroutine\n", msg,i) 34 | //} 35 | 36 | //for{ 37 | // msg, ok := <- msgChan 38 | // if !ok { 39 | // break 40 | // } 41 | // fmt.Printf("%sand receivced by %dth goroutine\n", msg,i) 42 | //} 43 | 44 | for{ 45 | select { 46 | case msg := <-msgChan: 47 | fmt.Printf("%sand receivced by %dth goroutine\n", msg,i) 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /seckill/SecLayer/service/logs.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/astaxie/beego" 7 | "github.com/astaxie/beego/logs" 8 | ) 9 | 10 | func convertLogLevel(level string) int { 11 | switch level{ 12 | case "debug": 13 | return logs.LevelDebug 14 | case "warn": 15 | return logs.LevelWarn 16 | case "info": 17 | return logs.LevelInfo 18 | case "trace": 19 | return logs.LevelTrace 20 | default: 21 | return logs.LevelDebug 22 | } 23 | } 24 | 25 | func InitLogger()(err error){ 26 | 27 | config := make(map[string]interface{}) 28 | config["filename"] = AppConfig.LogPath 29 | config["level"] = convertLogLevel(AppConfig.LogLevel) 30 | 31 | bytes, err := json.Marshal(config) 32 | if err != nil{ 33 | fmt.Println("initLogger failed, marshal err: ",err) 34 | return 35 | } 36 | 37 | logs.SetLogger(logs.AdapterFile,string(bytes)) 38 | logs.SetLogger(logs.AdapterConsole,string(bytes)) 39 | beego.SetLogFuncCall(true) 40 | return 41 | } -------------------------------------------------------------------------------- /logcollection/logagent/tools/SetConf/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "go.etcd.io/etcd/clientv3" 7 | "time" 8 | ) 9 | 10 | const ( 11 | EtcdKey = "/net/badme/logagent/config/182.61.137.53" 12 | ) 13 | 14 | func SetLogConfToEtcd() { 15 | client, e := clientv3.New(clientv3.Config{ 16 | Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, 17 | DialTimeout: 5 * time.Second, 18 | }) 19 | if e != nil { 20 | fmt.Println("connect etcd failed, err:", e) 21 | } 22 | 23 | fmt.Println("connect success") 24 | defer client.Close() 25 | 26 | timeout, cancelFunc := context.WithTimeout(context.Background(), time.Second) 27 | response, e := client.Get(timeout, EtcdKey) 28 | cancelFunc() 29 | if e != nil { 30 | fmt.Println("get failed, err:", e) 31 | return 32 | } 33 | 34 | for _, ev := range response.Kvs { 35 | fmt.Printf("%s : %s\n", ev.Key, ev.Value) 36 | } 37 | } 38 | 39 | func main() { 40 | SetLogConfToEtcd() 41 | } 42 | -------------------------------------------------------------------------------- /seckill/SecLayer/service/product_count.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | type ProductCountMgr struct{ 9 | productCount map[int]int 10 | lock sync.RWMutex 11 | } 12 | 13 | func NewProductCountMgr()(productMgr *ProductCountMgr){ 14 | productMgr = &ProductCountMgr{ 15 | productCount:make(map[int]int,128), 16 | } 17 | 18 | return 19 | } 20 | 21 | func (p *ProductCountMgr) Count(productId int)(count int) { 22 | p.lock.RLock() 23 | defer p.lock.RUnlock() 24 | 25 | count = p.productCount[productId] 26 | return 27 | } 28 | 29 | func (p *ProductCountMgr) Add(productId,count int){ 30 | 31 | p.lock.Lock() 32 | defer p.lock.Unlock() 33 | 34 | cur,ok :=p.productCount[productId] 35 | if !ok { 36 | fmt.Printf("product_id[%v] cur[%v],map: %v",productId,cur,p.productCount) 37 | cur = count 38 | }else { 39 | fmt.Printf("product_id[%v] cur[%v],map: %v",productId,cur,p.productCount) 40 | cur += count 41 | } 42 | 43 | p.productCount[productId] = cur 44 | } -------------------------------------------------------------------------------- /video_server/scheduler/dbops/internal.go: -------------------------------------------------------------------------------- 1 | package dbops 2 | 3 | import ( 4 | "log" 5 | ) 6 | 7 | func ReadVideoDeletionRecord(count int)(ids []string,err error){ 8 | stmtOut, err := dbConn.Prepare("select video_id from video_del_rec limit ?") 9 | if err != nil { 10 | return 11 | } 12 | 13 | rows, err := stmtOut.Query(count) 14 | if err != nil { 15 | log.Printf("Query VideoDeletionRecord error: %s",err) 16 | return 17 | } 18 | 19 | for{ 20 | var id string 21 | if err := rows.Scan(&id); err !=nil{ 22 | return 23 | } 24 | ids = append(ids, id) 25 | } 26 | 27 | defer stmtOut.Close() 28 | return 29 | } 30 | 31 | func DelVideoDeletionRecord(vid string) (err error){ 32 | stmtDel, err := dbConn.Prepare("delete from video_del_rec where video_id = ?") 33 | 34 | if err != nil { 35 | return 36 | } 37 | 38 | _, err = stmtDel.Exec(vid) 39 | if err != nil { 40 | log.Printf("Deleting VideoDeletionRecord error: %s", err) 41 | return 42 | } 43 | 44 | defer stmtDel.Close() 45 | return 46 | } -------------------------------------------------------------------------------- /logcollection/log_transfer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/astaxie/beego/logs" 7 | ) 8 | 9 | func main() { 10 | 11 | err := initConfig("ini", "./log_transfer.conf") 12 | if err != nil { 13 | panic(err) 14 | return 15 | } 16 | fmt.Println(logConfig) 17 | 18 | err = initLogger(logConfig.LogPath, logConfig.LogLevel) 19 | if err != nil { 20 | panic(err) 21 | return 22 | } 23 | 24 | logs.Debug("init logger succ") 25 | 26 | err = initKafka(logConfig.KafkaAddr, logConfig.KafkaTopic) 27 | if err != nil { 28 | logs.Error("init kafka failed, err:%v", err) 29 | return 30 | } 31 | 32 | logs.Debug("init kafka succ") 33 | 34 | err = initES(logConfig.ESAddr) 35 | if err != nil { 36 | logs.Error("init es failed, err:%v", err) 37 | return 38 | } 39 | 40 | logs.Debug("init es client succ") 41 | 42 | err = run() 43 | if err != nil { 44 | logs.Error("run failed, err:%v", err) 45 | return 46 | } 47 | 48 | logs.Warn("warning, log_transfer is exited") 49 | 50 | } 51 | 52 | -------------------------------------------------------------------------------- /video_server/streamserver/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/julienschmidt/httprouter" 5 | "net/http" 6 | ) 7 | 8 | type middleWareHandler struct { 9 | r *httprouter.Router 10 | l *ConnLimiter 11 | } 12 | 13 | func NewMiddleWareHandler(r *httprouter.Router, cc int) http.Handler { 14 | return &middleWareHandler{ 15 | r: r, 16 | l: NewConnLimiter(cc), 17 | } 18 | } 19 | 20 | 21 | func RegisterHandlers() *httprouter.Router{ 22 | r := httprouter.New() 23 | r.GET("/videos/:vid-id",streamHandler) 24 | r.POST("/upload/:vid-id",uploadHandler) 25 | r.GET("/test",testPageHandler) 26 | return r 27 | } 28 | 29 | //重写ServeHTTP接口 30 | func (m middleWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request){ 31 | if !m.l.GetConn() { 32 | sendErrorResponse(w, http.StatusTooManyRequests, "too many requests") 33 | return 34 | } 35 | m.r.ServeHTTP(w,r) 36 | defer m.l.ReleaseConn() 37 | } 38 | 39 | func main() { 40 | r := RegisterHandlers() 41 | m := NewMiddleWareHandler(r, 20) 42 | http.ListenAndServe(":9000",m) 43 | } -------------------------------------------------------------------------------- /crawler/zhenai/parser/city.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "golang-awesome/crawler/engine" 5 | "regexp" 6 | ) 7 | 8 | const cityReg = `]*>([^<]+)]*>([^<]+)`) 12 | 13 | cityUrlRe = regexp.MustCompile(`href="(http://www.zhenai.com/zhenghun/[^"]+)`) 14 | ) 15 | 16 | 17 | func ParseCity(contents []byte,_ string) engine.ParserResult{ 18 | rs := engine.ParserResult{} 19 | 20 | match := profileRe.FindAllSubmatch(contents, -1) 21 | for _, m := range match { 22 | rs.Requests = append(rs.Requests, engine.Request{ 23 | Url: string(m[1]), 24 | Parse:NewProfileParser(string(m[2])), 25 | }) 26 | } 27 | 28 | //取本页面其他城市链接 29 | //match = cityUrlRe.FindAllSubmatch(contents, -1) 30 | //for _, m := range match { 31 | // rs.Requests = append(rs.Requests, engine.Request{ 32 | // Url: string(m[1]), 33 | // Parse: engine.NewFuncParser(ParseCity, "ParseCity"), 34 | // }) 35 | //} 36 | return rs 37 | } -------------------------------------------------------------------------------- /video_server/api/utils/misc.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "io" 7 | "jayce" 8 | "log" 9 | "net/http" 10 | "strconv" 11 | "time" 12 | ) 13 | 14 | func NewUUID() (string, error) { 15 | uuid := make([]byte, 16) 16 | n, err := io.ReadFull(rand.Reader, uuid) 17 | if n != len(uuid) || err != nil { 18 | return "", err 19 | } 20 | // variant bits; see section 4.1.1 21 | uuid[8] = uuid[8]&^0xc0 | 0x80 22 | // version 4 (pseudo-random); see section 4.1.3 23 | uuid[6] = uuid[6]&^0xf0 | 0x40 24 | return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil 25 | } 26 | 27 | func GetCurrentTimestampSec() (ts int) { 28 | ts, _ = strconv.Atoi(strconv.FormatInt(time.Now().UnixNano()/1000000000, 10)) 29 | return 30 | } 31 | 32 | func SendDeleteVideoRequest(id string) { 33 | addr := jayce.GetLbAddr() + ":9001" 34 | url := "http://" + addr + "video-delete-record/" + id 35 | _, err := http.Get(url) 36 | if err != nil { 37 | log.Printf("sending delete video request error: %s", err) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /logcollection/web_admin/static/css/modules/code.css: -------------------------------------------------------------------------------- 1 | /** layui-v2.4.5 MIT License By https://www.layui.com */ 2 | html #layuicss-skincodecss{display:none;position:absolute;width:1989px}.layui-code-h3,.layui-code-view{position:relative;font-size:12px}.layui-code-view{display:block;margin:10px 0;padding:0;border:1px solid #e2e2e2;border-left-width:6px;background-color:#F2F2F2;color:#333;font-family:Courier New}.layui-code-h3{padding:0 10px;height:32px;line-height:32px;border-bottom:1px solid #e2e2e2}.layui-code-h3 a{position:absolute;right:10px;top:0;color:#999}.layui-code-view .layui-code-ol{position:relative;overflow:auto}.layui-code-view .layui-code-ol li{position:relative;margin-left:45px;line-height:20px;padding:0 5px;border-left:1px solid #e2e2e2;list-style-type:decimal-leading-zero;*list-style-type:decimal;background-color:#fff}.layui-code-view pre{margin:0}.layui-code-notepad{border:1px solid #0C0C0C;border-left-color:#3F3F3F;background-color:#0C0C0C;color:#C2BE9E}.layui-code-notepad .layui-code-h3{border-bottom:none}.layui-code-notepad .layui-code-ol li{background-color:#3F3F3F;border-left:none} -------------------------------------------------------------------------------- /logcollection/context/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "io/ioutil" 7 | "net/http" 8 | "time" 9 | ) 10 | 11 | type Result struct { 12 | r *http.Response 13 | err error 14 | } 15 | 16 | func process() { 17 | timeout, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second) 18 | defer cancelFunc() 19 | tr := &http.Transport{} 20 | client := &http.Client{Transport: tr} 21 | c := make(chan Result, 1) 22 | request, e := http.NewRequest("GET", "http://google.com", nil) 23 | if e != nil { 24 | fmt.Println("http request failed, err:", e) 25 | return 26 | } 27 | go func() { 28 | response, i := client.Do(request) 29 | pack := Result{r: response, err: i} 30 | c <- pack 31 | }() 32 | 33 | select { 34 | case <-timeout.Done(): 35 | tr.CancelRequest(request) 36 | <-c 37 | fmt.Println("time out!") 38 | case res := <-c: 39 | defer res.r.Body.Close() 40 | bytes, _ := ioutil.ReadAll(res.r.Body) 41 | fmt.Printf("Server response : %s ", bytes) 42 | } 43 | return 44 | } 45 | 46 | func main() { 47 | process() 48 | } 49 | -------------------------------------------------------------------------------- /goroutine/maze/gen.go: -------------------------------------------------------------------------------- 1 | package main 2 | import ( 3 | "fmt" 4 | "math/rand" 5 | "os" 6 | "time" 7 | ) 8 | 9 | func init(){ 10 | //以时间作为初始化种子 11 | rand.Seed(time.Now().UnixNano()) 12 | } 13 | func ts() { 14 | fileName := "goroutine/maze/maze.dat" 15 | //file, _ := os.OpenFile(fileName,os.O_CREATE|os.O_APPEND|os.O_RDWR,0777) 16 | file, _ := os.Create(fileName) 17 | defer file.Close() 18 | row, col := 50, 50 19 | fmt.Fprintf(file, "%d %d\n", row, col) 20 | //ch := make(chan int,1) 21 | for i := 0; i < row; i++ { 22 | for j := 0; j < col; j++ { 23 | //select { 24 | //case ch <- 0: 25 | //case ch <- 1: 26 | //} 27 | i2 := rand.Float32() 28 | var num int 29 | if i2 > 0.8{ 30 | num = 1 31 | }else { 32 | num = 0 33 | } 34 | if i == row -1 && j == col -1{ 35 | fmt.Fprintf(file, "%d",0) 36 | }else if i == 0 && j == 0{ 37 | fmt.Fprintf(file, "%d ",0) 38 | }else if j == col -1{ 39 | fmt.Fprintf(file, "%d",num) 40 | }else{ 41 | fmt.Fprintf(file, "%d ",num) 42 | } 43 | 44 | } 45 | fmt.Fprintf(file, "\n") 46 | } 47 | 48 | 49 | } 50 | 51 | 52 | -------------------------------------------------------------------------------- /logcollection/logagent/kafka/kafka.go: -------------------------------------------------------------------------------- 1 | package kafka 2 | 3 | import ( 4 | "github.com/Shopify/sarama" 5 | "github.com/astaxie/beego/logs" 6 | ) 7 | 8 | var ( 9 | client sarama.SyncProducer 10 | ) 11 | 12 | func InitKafka(addr string)(e error){ 13 | 14 | config := sarama.NewConfig() 15 | config.Producer.RequiredAcks = sarama.WaitForAll 16 | config.Producer.Partitioner = sarama.NewRandomPartitioner 17 | config.Producer.Return.Successes = true 18 | 19 | client, e = sarama.NewSyncProducer([]string{addr}, config) 20 | if e != nil { 21 | logs.Error("init kafka producer failed, err :",e) 22 | return 23 | } 24 | 25 | logs.Debug("init kafka success") 26 | return 27 | } 28 | 29 | func SendToKafka(data,topic string)(err error){ 30 | msg := &sarama.ProducerMessage{} 31 | msg.Topic = topic 32 | msg.Value = sarama.StringEncoder(data) 33 | 34 | partition, offset, err := client.SendMessage(msg) 35 | if err != nil { 36 | logs.Error("send message failed, err :%v data:%v topic :%v",err,data,topic) 37 | return 38 | } 39 | logs.Debug("send success, partition:%v offset:%v topic:%v",partition,offset,topic) 40 | return 41 | } -------------------------------------------------------------------------------- /logcollection/kafka/consumer/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/Shopify/sarama" 6 | "strings" 7 | "time" 8 | ) 9 | 10 | func main(){ 11 | 12 | consumer, e := sarama.NewConsumer(strings.Split("127.0.0.1:9092", ","), nil) 13 | if e != nil{ 14 | fmt.Println("failed to start consumer: ",e) 15 | return 16 | } 17 | partitionList, e := consumer.Partitions("test") 18 | if e != nil { 19 | fmt.Println("failed to get the list of partitions: ",e) 20 | return 21 | } 22 | fmt.Println(partitionList) 23 | for partition := range partitionList{ 24 | pc, e := consumer.ConsumePartition("test", int32(partition), sarama.OffsetNewest) 25 | if e != nil { 26 | fmt.Printf("failed to start consumer for partition %d,%s\n",partition,e) 27 | return 28 | } 29 | defer pc.AsyncClose() 30 | 31 | go func(sarama.PartitionConsumer){ 32 | for msg := range pc.Messages(){ 33 | fmt.Printf("partition:%d, offset:%d, key:%s, value:%s",msg.Partition,msg.Offset,string(msg.Key),string(msg.Value)) 34 | fmt.Println() 35 | } 36 | }(pc) 37 | 38 | time.Sleep(time.Hour) 39 | consumer.Close() 40 | } 41 | } -------------------------------------------------------------------------------- /logcollection/kafka/producer/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/Shopify/sarama" 5 | "fmt" 6 | "log" 7 | "os" 8 | "time" 9 | ) 10 | 11 | func main(){ 12 | 13 | config := sarama.NewConfig() 14 | config.Producer.RequiredAcks = sarama.WaitForAll 15 | config.Producer.Partitioner = sarama.NewRandomPartitioner 16 | config.Producer.Return.Successes = true 17 | 18 | var logger = log.New(os.Stderr, "[kafka]", log.LstdFlags) 19 | sarama.Logger = logger 20 | client, err := sarama.NewSyncProducer([]string{"127.0.0.1:9092"}, config) 21 | if err != nil{ 22 | logger.Println("producer close,err:",err) 23 | return 24 | } 25 | 26 | defer client.Close() 27 | 28 | for { 29 | msg := &sarama.ProducerMessage{} 30 | msg.Topic = "test" 31 | msg.Value = sarama.StringEncoder("this is a test massage, my massage is good") 32 | 33 | partition, offset, e := client.SendMessage(msg) 34 | if e != nil { 35 | logger.Println("send massage failed," , err) 36 | return 37 | } 38 | 39 | fmt.Printf("partition :%v ,offset:%v\n" ,partition,offset) 40 | time.Sleep(time.Second *10) 41 | } 42 | 43 | 44 | 45 | 46 | } -------------------------------------------------------------------------------- /seckill/SecLayer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego/logs" 6 | "golang-awesome/seckill/SecLayer/service" 7 | ) 8 | 9 | func main() { 10 | //1. 加载配置文件 11 | err := service.InitConfig("ini", "./conf/seclayer.conf") 12 | if err != nil { 13 | logs.Error("init config failed, err:%v", err) 14 | panic(fmt.Sprintf("init config failed, err:%v", err)) 15 | } 16 | 17 | logs.Debug("load config succ, data:%v",service.AppConfig) 18 | //2. 初始化日志库 19 | err = service.InitLogger() 20 | if err != nil { 21 | logs.Error("init logger failed, err:%v", err) 22 | panic(fmt.Sprintf("init logger failed, err:%v", err)) 23 | } 24 | 25 | logs.Debug("init logger succ") 26 | //3. 初始化秒杀逻辑 27 | err = service.InitSecLayer(service.AppConfig) 28 | if err != nil { 29 | msg := fmt.Sprintf("init sec kill failed, err:%v", err) 30 | logs.Error(msg) 31 | panic(msg) 32 | } 33 | 34 | logs.Debug("init sec layer succ") 35 | //4. 运行业务逻辑 36 | err = service.Run() 37 | if err != nil { 38 | logs.Error("service run return, err:%v", err) 39 | return 40 | } 41 | 42 | logs.Info("service run exited") 43 | } 44 | -------------------------------------------------------------------------------- /crawler/persist/itemsaver.go: -------------------------------------------------------------------------------- 1 | package persist 2 | 3 | import ( 4 | "context" 5 | "github.com/pkg/errors" 6 | "golang-awesome/crawler/engine" 7 | "gopkg.in/olivere/elastic.v5" 8 | "log" 9 | ) 10 | 11 | func ItemSaver(index string) (chan engine.Item, error){ 12 | ch := make(chan engine.Item, 1024) 13 | client, err := elastic.NewClient(elastic.SetSniff(false), 14 | elastic.SetURL("http://localhost:9200/"), 15 | elastic.SetBasicAuth("elastic","changeme")) 16 | if err != nil { 17 | return nil, err 18 | } 19 | 20 | go func() { 21 | itemCount := 0 22 | for item := range ch{ 23 | itemCount ++ 24 | log.Printf("Item Saver: Got Item #%d: %v", itemCount, item) 25 | err := Save(client, index, item) 26 | if err != nil { 27 | log.Printf("Item Saver: save error: %s",err) 28 | } 29 | } 30 | }() 31 | return ch, nil 32 | } 33 | 34 | 35 | func Save(client *elastic.Client, index string, item engine.Item)(err error){ 36 | if item.Type == ""{ 37 | return errors.New("item.type 不能为空") 38 | } 39 | 40 | _, err = client.Index(). 41 | Index(index). 42 | Type(item.Type). 43 | Id(item.Id). 44 | BodyJson(item). 45 | Do(context.Background()) 46 | return err 47 | } -------------------------------------------------------------------------------- /logcollection/web_admin/tests/default_test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "net/http" 5 | "net/http/httptest" 6 | "testing" 7 | "runtime" 8 | "path/filepath" 9 | _ "golang-awesome/logcollection/web_admin/routers" 10 | 11 | "github.com/astaxie/beego" 12 | . "github.com/smartystreets/goconvey/convey" 13 | ) 14 | 15 | func init() { 16 | _, file, _, _ := runtime.Caller(1) 17 | apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".." + string(filepath.Separator)))) 18 | beego.TestBeegoInit(apppath) 19 | } 20 | 21 | 22 | // TestBeego is a sample to run an endpoint test 23 | func TestBeego(t *testing.T) { 24 | r, _ := http.NewRequest("GET", "/", nil) 25 | w := httptest.NewRecorder() 26 | beego.BeeApp.Handlers.ServeHTTP(w, r) 27 | 28 | beego.Trace("testing", "TestBeego", "Code[%d]\n%s", w.Code, w.Body.String()) 29 | 30 | Convey("Subject: Test Station Endpoint\n", t, func() { 31 | Convey("Status Code Should Be 200", func() { 32 | So(w.Code, ShouldEqual, 200) 33 | }) 34 | Convey("The Result Should Not Be Empty", func() { 35 | So(w.Body.Len(), ShouldBeGreaterThan, 0) 36 | }) 37 | }) 38 | } 39 | 40 | -------------------------------------------------------------------------------- /seckill/SecLayer/conf/seclayer.conf: -------------------------------------------------------------------------------- 1 | [logs] 2 | log_level=debug 3 | log_path=./logs/seclayer.log 4 | 5 | 6 | [etcd] 7 | server_addr = 127.0.0.1:2379 8 | etcd_sec_key_prefix = /net/badme/backend/seckill 9 | etcd_product_key = product 10 | etcd_black_list_key = blacklist 11 | etcd_timeout = 5 12 | 13 | [redis] 14 | #redis 接入层->业务逻辑层 15 | redis_proxy2layer_addr= 16 | redis_proxy2layer_pwd= 17 | redis_proxy2layer_idle = 64 18 | redis_proxy2layer_active = 0 19 | redis_proxy2layer_idle_timeout = 300 20 | redis_proxy2layer_queue_name = sec_queue 21 | 22 | #redis 业务逻辑层->接入层 23 | redis_layer2proxy_addr= 24 | redis_layer2proxy_pwd= 25 | redis_layer2proxy_idle = 64 26 | redis_layer2proxy_active = 0 27 | redis_layer2proxy_idle_timeout = 300 28 | redis_layer2proxy_queue_name = recv_queue 29 | 30 | [service] 31 | write_proxy2layer_goroutine_num = 1 32 | read_layer2proxy_goroutine_num = 1 33 | handle_user_goroutine_num =1 34 | read2handle_chan_size = 100000 35 | handle2write_chan_size = 100000 36 | max_request_wait_timeout = 30 37 | #单位是毫秒 38 | send_to_write_chan_timeout=100 39 | send_to_handle_chan_timeout = 100 40 | #token秘钥 41 | seckill_token_passwd=fIOxU7iik65vVvBGtNcnrjL4E9MdRpTfzzxE3dx6b7BAHN5etUdSzRW5yjzHzFGW -------------------------------------------------------------------------------- /video_server/api/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/julienschmidt/httprouter" 5 | "golang-awesome/video_server/api/session" 6 | "log" 7 | "net/http" 8 | ) 9 | 10 | type middleWareHandler struct { 11 | r *httprouter.Router 12 | } 13 | 14 | func newMiddleWareHandler(r *httprouter.Router) *middleWareHandler { 15 | return &middleWareHandler{r: r} 16 | } 17 | 18 | func (m middleWareHandler) ServeHTTP(w http.ResponseWriter, r * http.Request){ 19 | validateUserSession(r) 20 | m.r.ServeHTTP(w,r) 21 | } 22 | 23 | 24 | func RegisterHandlers() *httprouter.Router{ 25 | log.Printf("preparing to post requesr\n") 26 | r := httprouter.New() 27 | r.POST("/user",CreateUser) 28 | r.POST("/user/:username",Login) 29 | r.GET("/user/:username",GetUserInfo) 30 | r.POST("/user/:username/videos",AddNewVideo) 31 | r.GET("/user/:username/videos",ListAllVideos) 32 | r.DELETE("/user/:username/videos/:vid-id",DeleteVideo) 33 | r.POST("/videos/:vid-id/comments",PostComment) 34 | r.GET("/videos/:vid-id/comments",ShowComments) 35 | return r 36 | } 37 | 38 | func prepare(){ 39 | session.LoadSessionsFromDB() 40 | } 41 | 42 | func main(){ 43 | prepare() 44 | r := RegisterHandlers() 45 | m := newMiddleWareHandler(r) 46 | http.ListenAndServe(":8000",m) 47 | } -------------------------------------------------------------------------------- /logcollection/web_admin/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego/logs" 6 | "github.com/jmoiron/sqlx" 7 | "go.etcd.io/etcd/clientv3" 8 | "golang-awesome/logcollection/web_admin/models" 9 | _ "golang-awesome/logcollection/web_admin/routers" 10 | _ "github.com/go-sql-driver/mysql" 11 | "github.com/astaxie/beego" 12 | "time" 13 | ) 14 | 15 | func initDb() (err error) { 16 | database, err := sqlx.Open("mysql", "root:P@ssw0rd@tcp(182.61.137.53:3306)/logagent") 17 | if err != nil { 18 | logs.Warn("open mysql failed,", err) 19 | return 20 | } 21 | 22 | models.InitDb(database) 23 | return 24 | } 25 | 26 | func initEtcd()(err error){ 27 | client, e := clientv3.New(clientv3.Config{ 28 | Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, 29 | DialTimeout: 5 * time.Second, 30 | }) 31 | 32 | if e != nil { 33 | fmt.Println("connect to etcd failed,err:",e) 34 | return 35 | } 36 | models.InitEtcd(client) 37 | return 38 | } 39 | 40 | func main() { 41 | err := initDb() 42 | 43 | if err != nil { 44 | logs.Warn("initDb failed, err:%v", err) 45 | return 46 | } 47 | 48 | err = initEtcd() 49 | if err != nil { 50 | logs.Warn("initEtcd failed, err%v",err) 51 | return 52 | } 53 | beego.Run() 54 | } 55 | 56 | -------------------------------------------------------------------------------- /goroutine/sort/sort/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //前后元素依次比较 6 | func bubbleSort(a []int){ 7 | for i := 0; i a[j]{ 22 | min = j 23 | } 24 | } 25 | a[i],a[min] = a[min],a[i] 26 | } 27 | } 28 | 29 | //插入排序,将元素一个个插入到有序序列 30 | func insertSort(a []int){ 31 | for i:=1;i0 ;j--{ 33 | if a[j] > a[j-1]{ 34 | break 35 | } 36 | a[j],a[j-1] = a[j-1],a[j] 37 | } 38 | } 39 | } 40 | 41 | //每次确定一个元素的位置,小的放左边,大的放右边,递归 42 | func quickSort(a []int,left,right int){ 43 | if left >= right{ 44 | return 45 | } 46 | 47 | val := a[left] 48 | k := left 49 | for i := left +1; i 0 && len(workerQ) > 0 { 26 | activeRequest = requestQ[0] 27 | activeWorker = workerQ[0] 28 | } 29 | select { 30 | case r := <-s.requestChan: 31 | requestQ = append(requestQ, r) 32 | case w := <-s.workerChan: 33 | workerQ = append(workerQ, w) 34 | case activeWorker <- activeRequest: 35 | requestQ = requestQ[1:] 36 | workerQ = workerQ[1:] 37 | } 38 | } 39 | }() 40 | } 41 | 42 | func (s *QueuedScheduler) Submit(request engine.Request) { 43 | s.requestChan <- request 44 | } 45 | 46 | func (s *QueuedScheduler) GetWorkChan() chan engine.Request { 47 | return make(chan engine.Request) 48 | } 49 | 50 | func (s *QueuedScheduler) WorkReady(w chan engine.Request) { 51 | s.workerChan <- w 52 | } 53 | -------------------------------------------------------------------------------- /logcollection/log_transfer/config.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/astaxie/beego/config" 7 | ) 8 | 9 | type LogConfig struct { 10 | KafkaAddr string 11 | ESAddr string 12 | LogPath string 13 | LogLevel string 14 | KafkaTopic string 15 | } 16 | 17 | var ( 18 | logConfig *LogConfig 19 | ) 20 | 21 | func initConfig(confType string, filename string) (err error) { 22 | conf, err := config.NewConfig(confType, filename) 23 | if err != nil { 24 | fmt.Println("new config failed, err:", err) 25 | return 26 | } 27 | 28 | logConfig = &LogConfig{} 29 | logConfig.LogLevel = conf.String("logs::log_level") 30 | if len(logConfig.LogLevel) == 0 { 31 | logConfig.LogLevel = "debug" 32 | } 33 | 34 | logConfig.LogPath = conf.String("logs::log_path") 35 | if len(logConfig.LogPath) == 0 { 36 | logConfig.LogPath = "./logs" 37 | } 38 | 39 | logConfig.KafkaAddr = conf.String("kafka::server_addr") 40 | if len(logConfig.KafkaAddr) == 0 { 41 | err = fmt.Errorf("invalid kafka addr") 42 | return 43 | } 44 | 45 | logConfig.ESAddr = conf.String("es::addr") 46 | if len(logConfig.ESAddr) == 0 { 47 | err = fmt.Errorf("invalid es addr") 48 | return 49 | } 50 | 51 | logConfig.KafkaTopic = conf.String("kafka::topic") 52 | if len(logConfig.ESAddr) == 0 { 53 | err = fmt.Errorf("invalid es addr") 54 | return 55 | } 56 | return 57 | } 58 | -------------------------------------------------------------------------------- /logcollection/log_transfer/run.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/Shopify/sarama" 6 | "github.com/astaxie/beego/logs" 7 | ) 8 | 9 | func run() (err error) { 10 | fmt.Println(kafkaClient) 11 | 12 | partitionList, err := kafkaClient.client.Partitions(kafkaClient.topic) 13 | if err != nil { 14 | logs.Error("Failed to get the list of partitions: ", err) 15 | return 16 | } 17 | 18 | for partition := range partitionList { 19 | pc, errRet := kafkaClient.client.ConsumePartition(kafkaClient.topic, int32(partition), sarama.OffsetNewest) 20 | if errRet != nil { 21 | err = errRet 22 | logs.Error("Failed to start consumer for partition %d: %s\n", partition, err) 23 | return 24 | } 25 | defer pc.AsyncClose() 26 | kafkaClient.wg.Add(1) 27 | go func(pc sarama.PartitionConsumer) { 28 | for msg := range pc.Messages() { 29 | logs.Debug("Partition:%d, Offset:%d, Key:%s, Value:%s", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value)) 30 | fmt.Println("Partition:%d, Offset:%d, Key:%s, Value:%s", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value)) 31 | //fmt.Println() 32 | err = sendToES(kafkaClient.topic, msg.Value) 33 | if err != nil { 34 | logs.Warn("send to es failed, err:%v", err) 35 | } 36 | } 37 | fmt.Println(1) 38 | kafkaClient.wg.Done() 39 | }(pc) 40 | } 41 | 42 | //time.Sleep(time.Hour) 43 | kafkaClient.wg.Wait() 44 | return 45 | } 46 | -------------------------------------------------------------------------------- /video_server/scheduler/taskrunner/runner.go: -------------------------------------------------------------------------------- 1 | package taskrunner 2 | 3 | type Runner struct { 4 | Controller controlChan 5 | Error controlChan 6 | Data dataChan 7 | dataSize int 8 | longLived bool 9 | Dispatcher fn 10 | Executor fn 11 | } 12 | 13 | func NewRunner(dataSize int, longLived bool, dispatcher fn, executor fn) *Runner { 14 | return &Runner{ 15 | Controller: make(chan string,1), 16 | Error: make(chan string,1), 17 | Data: make(chan interface{},dataSize), 18 | dataSize: dataSize, 19 | longLived: longLived, 20 | Dispatcher: dispatcher, 21 | Executor: executor} 22 | } 23 | 24 | func (r *Runner) startDispatch() { 25 | defer func() { 26 | if !r.longLived { 27 | close(r.Controller) 28 | close(r.Data) 29 | close(r.Error) 30 | } 31 | }() 32 | 33 | for { 34 | select { 35 | case c := <-r.Controller: 36 | if c == READY_TO_DISPATCH{ 37 | err := r.Dispatcher(r.Data) 38 | if err != nil { 39 | r.Error <- CLOSE 40 | }else { 41 | r.Controller <- READY_TO_EXECUTE 42 | } 43 | } 44 | if c == READY_TO_EXECUTE{ 45 | err := r.Executor(r.Data) 46 | if err != nil { 47 | r.Error <- CLOSE 48 | }else { 49 | r.Controller <- READY_TO_DISPATCH 50 | } 51 | } 52 | case e := <-r.Error: 53 | if e == CLOSE{ 54 | return 55 | } 56 | } 57 | } 58 | } 59 | 60 | func (r *Runner) StartAll(){ 61 | r.Controller <- READY_TO_DISPATCH 62 | r.startDispatch() 63 | } -------------------------------------------------------------------------------- /logcollection/logagent/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego/logs" 6 | "golang-awesome/logcollection/logagent/kafka" 7 | "golang-awesome/logcollection/logagent/tail" 8 | ) 9 | 10 | func main(){ 11 | filename := "./logagent.conf" 12 | err := loadConf("ini",filename) 13 | if err != nil { 14 | fmt.Printf("load conf failed,err%v\n",err) 15 | panic("load conf failed") 16 | return 17 | } 18 | 19 | err = initLogger() 20 | if err!= nil{ 21 | fmt.Printf("load conf failed,err%v\n",err) 22 | panic("load log failed") 23 | return 24 | } 25 | 26 | logs.Debug("load conf succ ,config:",appConfig) 27 | 28 | collectConf, err := initEtcd(appConfig.etcdAddr, appConfig.etcdKey) 29 | if err != nil { 30 | logs.Error("init etcd failed, err:%v", err) 31 | return 32 | } 33 | 34 | err = tail.InitTail(collectConf,appConfig.chanSize) 35 | if err != nil { 36 | logs.Error("init tail failed ,err:%v\n",err) 37 | return 38 | } 39 | 40 | logs.Debug("initialize tail success!") 41 | 42 | err = kafka.InitKafka(appConfig.kafkaAddr) 43 | if err != nil { 44 | logs.Error("init kafka failed ,err:%v\n",err) 45 | return 46 | } 47 | 48 | logs.Debug("initialize kafka success!") 49 | 50 | 51 | logs.Debug("initialize all config success!") 52 | 53 | err = serverRun() 54 | if err != nil { 55 | logs.Error("serverRun failed ,err :%v\n",err) 56 | return 57 | } 58 | logs.Info("program exited") 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /seckill/SecProxy/conf/app.conf: -------------------------------------------------------------------------------- 1 | httpaddr = "0.0.0.0" 2 | httpport = 9090 3 | appname = SecProxy 4 | 5 | 6 | runmode = "${ProRunMode||dev}" 7 | autorender = false 8 | 9 | [dev] 10 | #redis黑名单相关配置 11 | redis_black_addr= 12 | redis_black_pwd = 13 | redis_black_idle = 8 14 | redis_black_active = 16 15 | redis_black_idle_timeout = 300 16 | 17 | #redis 接入层->业务逻辑层 18 | redis_proxy2layer_addr= 19 | redis_proxy2layer_pwd= 123456 20 | redis_proxy2layer_idle = 8 21 | redis_proxy2layer_active = 100 22 | redis_proxy2layer_idle_timeout = 300 23 | write_proxy2layer_goroutine_num = 32 24 | read_layer2proxy_goroutine_num = 32 25 | 26 | #redis 业务逻辑层->接入层 27 | redis_layer2proxy_addr= 28 | redis_layer2proxy_pwd= 29 | redis_layer2proxy_idle = 8 30 | redis_layer2proxy_active = 100 31 | redis_layer2proxy_idle_timeout = 300 32 | write_layer2proxy_goroutine_num = 32 33 | read_layer2proxy_goroutine_num = 32 34 | 35 | #etcd相关配置 36 | etcd_addr = 127.0.0.1:2379 37 | etcd_timeout = 5 38 | etcd_sec_key_prefix = /net/badme/backend/seckill 39 | etcd_product_key = product 40 | etcd_black_list_key = blacklist 41 | 42 | #日志文件相关配置 43 | log_path = ./logs/sec.log 44 | log_level = debug 45 | 46 | #cookie 秘钥 47 | cookie_secretkey=tyP87zZKzITuzaUjhmbqhNIDnyg6f2KP 48 | 49 | refer_whitelist=localhost,baidu.com,qq.com/secskill 50 | #频率控制阈值 51 | ip_sec_access_limit = 50 52 | user_sec_access_limit = 1 53 | 54 | ip_min_access_limit = 500 55 | user_min_access_limit = 10 56 | 57 | [prod] 58 | redis_addr=127.0.0.1:6379 59 | etcd_addr=127.0.0.1:2379 -------------------------------------------------------------------------------- /crawler/engine/concurrent.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | //并发的引擎 4 | //引擎将请求发送给调度器,调度器分发给workers,workers的结果再返回给引擎 5 | //所有的worker统一调度 6 | type Scheduler interface{ 7 | Run() 8 | Submit(request Request) 9 | GetWorkChan() chan Request 10 | Ready 11 | } 12 | 13 | type Ready interface { 14 | WorkReady(chan Request) 15 | } 16 | 17 | type ConcurrentEngine struct { 18 | MaxWorkerCount int 19 | Scheduler Scheduler 20 | ItemChan chan Item 21 | RequestWorker Processor 22 | } 23 | 24 | type Processor func(request Request)(ParserResult,error) 25 | 26 | func (c *ConcurrentEngine) Run(seed ...Request){ 27 | out := make(chan ParserResult, 1024) 28 | c.Scheduler.Run() 29 | 30 | for i :=0; i < c.MaxWorkerCount; i++{ 31 | c.createWorker(c.Scheduler.GetWorkChan(),out,c.Scheduler) 32 | } 33 | 34 | for _, r := range seed{ 35 | if IsDuplicate(r.Url){ 36 | continue 37 | } 38 | c.Scheduler.Submit(r) 39 | } 40 | 41 | for { 42 | result := <-out 43 | for _, item:= range result.Items{ 44 | go func() {c.ItemChan <- item}() 45 | } 46 | 47 | for _, r := range result.Requests{ 48 | if IsDuplicate(r.Url){ 49 | continue 50 | } 51 | c.Scheduler.Submit(r) 52 | } 53 | } 54 | } 55 | 56 | func (c *ConcurrentEngine) createWorker(in chan Request,out chan ParserResult,r Ready){ 57 | go func() { 58 | for { 59 | r.WorkReady(in) 60 | request := <- in 61 | result, err := c.RequestWorker(request) 62 | if err != nil { 63 | continue 64 | } 65 | out <- result 66 | } 67 | }() 68 | } -------------------------------------------------------------------------------- /crawler/engine/types.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | //函数类型,只要参类型、个数、顺序相同就可以 4 | type ParserFunc func(body []byte, url string) ParserResult 5 | 6 | //解析函数接口 7 | type Parser interface { 8 | Parse(contents []byte, url string) ParserResult 9 | Serialize() (name string, args interface{}) 10 | } 11 | 12 | //请求,包括url和指定的解析函数 13 | type Request struct { 14 | Url string 15 | Parse Parser 16 | } 17 | 18 | //解析结果,包括爬到的内容和url 19 | type ParserResult struct { 20 | Requests []Request 21 | Items []Item 22 | } 23 | 24 | //空的解析方法 25 | func NilParseFunc(body []byte, url string) ParserResult { 26 | return ParserResult{} 27 | } 28 | 29 | //一个页面的对象 30 | type Item struct { 31 | Url string 32 | Id string 33 | Type string 34 | Payload interface{} 35 | } 36 | 37 | type NilParse struct { 38 | } 39 | 40 | func (NilParse) Parse(contents []byte, url string) ParserResult { 41 | return ParserResult{} 42 | } 43 | 44 | func (NilParse) Serialize() (name string, args interface{}) { 45 | return "NilParse", nil 46 | } 47 | 48 | type FuncParser struct { 49 | parser ParserFunc 50 | name string 51 | } 52 | 53 | func NewFuncParser(parser ParserFunc, name string) *FuncParser { 54 | return &FuncParser{parser: parser, name: name} 55 | } 56 | 57 | func (p *FuncParser) Parse(contents []byte, url string) ParserResult { 58 | return p.parser(contents, url) 59 | } 60 | 61 | //TODO what can we return after serialized 62 | func (p *FuncParser) Serialize() (name string, args interface{}) { 63 | return p.name, nil 64 | } 65 | -------------------------------------------------------------------------------- /video_server/scheduler/taskrunner/tasks.go: -------------------------------------------------------------------------------- 1 | package taskrunner 2 | 3 | import ( 4 | "errors" 5 | "golang-awesome/video_server/scheduler/dbops" 6 | "log" 7 | "os" 8 | "path/filepath" 9 | "sync" 10 | ) 11 | 12 | func deleteVideo(vid string) error { 13 | path, _ := filepath.Abs(VIDEO_PATH + vid) 14 | log.Panicln(path) 15 | err := os.Remove(VIDEO_PATH + vid) 16 | if err != nil { 17 | log.Printf("deleting video error: %v", err) 18 | return err 19 | } 20 | return nil 21 | } 22 | 23 | func VideoClearDispathcer(dc dataChan) error { 24 | res, err := dbops.ReadVideoDeletionRecord(3) 25 | if err != nil { 26 | log.Printf("video clear dispatcher error: %s", err) 27 | } 28 | if len(res) == 0 { 29 | return errors.New("all tasks finished") 30 | } 31 | 32 | for _, id := range res { 33 | dc <- id 34 | } 35 | return nil 36 | } 37 | 38 | func VideoClearExecutor(dc dataChan) error { 39 | errMap := &sync.Map{} 40 | var err error 41 | loop: 42 | for { 43 | select { 44 | case vid := <-dc: 45 | go func(id interface{}) { 46 | if err := deleteVideo(id.(string)); err != nil { 47 | errMap.Store(id, err) 48 | return 49 | } 50 | if err := dbops.DelVideoDeletionRecord(id.(string)); err != nil { 51 | errMap.Store(id, err) 52 | return 53 | } 54 | }(vid) 55 | default: 56 | break loop 57 | } 58 | } 59 | errMap.Range(func(k, v interface{}) bool { 60 | err = v.(error) 61 | if err != nil { 62 | return false 63 | } 64 | return true 65 | }) 66 | return err 67 | } 68 | -------------------------------------------------------------------------------- /logcollection/log_transfer/es.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | 8 | elastic "gopkg.in/olivere/elastic.v5" 9 | ) 10 | 11 | type LogMessage struct { 12 | App string 13 | Topic string 14 | Message string 15 | } 16 | 17 | var ( 18 | esClient *elastic.Client 19 | count int 20 | ) 21 | 22 | func initES(addr string) (err error) { 23 | 24 | client, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(addr)) 25 | if err != nil { 26 | fmt.Println("connect es error", err) 27 | return 28 | } 29 | esClient = client 30 | return 31 | /* 32 | fmt.Println("conn es succ") 33 | for i := 0; i < 10000; i++ { 34 | tweet := Tweet{User: "olivere", Message: "Take Five"} 35 | _, err = client.Index(). 36 | Index("twitter"). 37 | Type("tweet"). 38 | Id(fmt.Sprintf("%d", i)). 39 | BodyJson(tweet). 40 | Do() 41 | if err != nil { 42 | // Handle error 43 | panic(err) 44 | return 45 | } 46 | } 47 | 48 | fmt.Println("insert succ") 49 | */ 50 | } 51 | 52 | func sendToES(topic string, data []byte) (err error) { 53 | 54 | msg := &LogMessage{} 55 | msg.Topic = topic 56 | msg.Message = string(data) 57 | count++ 58 | ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second) 59 | defer cancelFunc() 60 | _, err = esClient.Index(). 61 | Index(topic). 62 | Type(topic). 63 | Id(fmt.Sprintf("%d", count)). 64 | BodyJson(msg).Do(ctx) 65 | if err != nil { 66 | // Handle error 67 | panic(err) 68 | return 69 | } 70 | return 71 | } 72 | -------------------------------------------------------------------------------- /logcollection/etcd/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "go.etcd.io/etcd/clientv3" 8 | "golang-awesome/logcollection/logagent/tail" 9 | "time" 10 | ) 11 | 12 | var ( 13 | etcdKey = "/net/badme/logagent/config/182.61.137.53" 14 | ) 15 | 16 | func main() { 17 | 18 | cli, err := clientv3.New(clientv3.Config{ 19 | Endpoints: []string{"127.0.0.1:2379"}, 20 | DialTimeout: 5 * time.Second, 21 | }) 22 | if err != nil { 23 | fmt.Println("connect failed, err:", err) 24 | return 25 | } 26 | 27 | fmt.Println("connect success") 28 | defer cli.Close() 29 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) 30 | logconf := &tail.CollectConf{ 31 | LogPath: "/Users/qinxun/dev/dev-go/go/test.log", 32 | Topic: "test", 33 | } 34 | var confs []*tail.CollectConf 35 | confs = append(confs, logconf) 36 | bytes, err := json.Marshal(confs) 37 | _, err = cli.Put(ctx, etcdKey, string(bytes)) 38 | cancel() 39 | if err != nil { 40 | fmt.Println("put failed, err:", err) 41 | return 42 | } 43 | ctx, cancel = context.WithTimeout(context.Background(), time.Second) 44 | resp, err := cli.Get(ctx, etcdKey) 45 | cancel() 46 | if err != nil { 47 | fmt.Println("get failed, err:", err) 48 | return 49 | } 50 | for _, ev := range resp.Kvs { 51 | //var conf tail.CollectConf 52 | //err := json.Unmarshal(ev.Value, &conf) 53 | //if err != nil{ 54 | // panic(err) 55 | //} 56 | //fmt.Println("conf:",conf) 57 | fmt.Printf("%s : %s\n", ev.Key, ev.Value) 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /video_server/api/session/ops.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "fmt" 5 | "golang-awesome/video_server/api/dbops" 6 | "golang-awesome/video_server/api/defs" 7 | "golang-awesome/video_server/api/utils" 8 | "sync" 9 | "time" 10 | ) 11 | 12 | var sessionMap *sync.Map 13 | 14 | func init(){ 15 | sessionMap = &sync.Map{} 16 | } 17 | 18 | //返回毫秒数 19 | func nowInMilli() int64{ 20 | return time.Now().UnixNano()/1000000 21 | } 22 | 23 | func deleteExpireSession(sid string){ 24 | sessionMap.Delete(sid) 25 | dbops.DeleteSession(sid) 26 | } 27 | 28 | func LoadSessionsFromDB() *sync.Map{ 29 | r, err := dbops.RetrieveAllSessions() 30 | if err != nil { 31 | return nil 32 | } 33 | r.Range(func(key, value interface{}) bool { 34 | ss := value.(*defs.SimpleSession) 35 | sessionMap.Store(key,ss) 36 | return true 37 | }) 38 | return sessionMap 39 | } 40 | 41 | func GenerateNewSessionId(uname string) string{ 42 | uuid, _ := utils.NewUUID() 43 | ct := time.Now().UnixNano()/1000000 44 | ttl := ct + 30 * 60 * 1000 45 | ss := &defs.SimpleSession{UserName:uname, TTL:ttl} 46 | sessionMap.Store(uuid, ss) 47 | err := dbops.InsertSession(uuid, ttl, uname) 48 | if err != nil { 49 | return fmt.Sprintf("Error of GenerateNewSessionId: %s",err) 50 | } 51 | return uuid 52 | } 53 | 54 | func IsSessionExpired(sid string)(string,bool){ 55 | ss, ok := sessionMap.Load(sid) 56 | if ok{ 57 | ct := nowInMilli() 58 | if ss.(*defs.SimpleSession).TTL < ct { 59 | deleteExpireSession(sid) 60 | return "",true 61 | } 62 | return ss.(*defs.SimpleSession).UserName, false 63 | } 64 | return "",true 65 | } -------------------------------------------------------------------------------- /video_server/api/defs/apidef.go: -------------------------------------------------------------------------------- 1 | package defs 2 | 3 | //request 4 | type UserCredential struct { 5 | UserName string `json:"user_name"` 6 | Pwd string `json:"pwd"` 7 | } 8 | 9 | type NewComment struct { 10 | AuthorId int `json:"author_id"` 11 | Content string `json:"content"` 12 | } 13 | 14 | type NewVideo struct { 15 | AuthorId int `json:"author_id"` 16 | Name string `json:"name"` 17 | } 18 | 19 | //response 20 | type SignedUp struct { 21 | Success bool `json:"success"` 22 | SessionId string `json:"session_id"` 23 | } 24 | 25 | type UserSession struct { 26 | UserName string `json:"user_name"` 27 | SessionId string `json:"session_id"` 28 | } 29 | 30 | type UserInfo struct { 31 | Id int `json:"id"` 32 | } 33 | 34 | type SignedIn struct { 35 | Success bool `json:"success"` 36 | SessionId string `json:"session_id"` 37 | } 38 | 39 | type VideosInfo struct { 40 | Videos []*VideoInfo `json:"videos"` 41 | } 42 | 43 | type Comments struct { 44 | Comments []*Comment `json:"comments"` 45 | } 46 | 47 | //data model 48 | type User struct { 49 | Id int 50 | LoginName string 51 | Pwd string 52 | } 53 | 54 | type VideoInfo struct { 55 | Id string `json:"id"` 56 | AuthorId int `json:"author_id"` 57 | Name string `json:"name"` 58 | DisplayTime string `json:"display_time"` 59 | } 60 | 61 | type Comment struct { 62 | Id string `json:"id"` 63 | VideoId string `json:"video_id"` 64 | Author string `json:"author"` 65 | Content string `json:"content"` 66 | } 67 | 68 | type SimpleSession struct { 69 | UserName string 70 | TTL int64 71 | } 72 | -------------------------------------------------------------------------------- /seckill/SecLayer/service/init.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "github.com/astaxie/beego/logs" 5 | etcd "go.etcd.io/etcd/clientv3" 6 | "time" 7 | ) 8 | 9 | func initEtcd(conf *SecLayerConf)(err error){ 10 | cli,err :=etcd.New(etcd.Config{ 11 | Endpoints:[]string{conf.EtcdConfig.EtcdAddr}, 12 | DialTimeout:time.Duration(conf.EtcdConfig.Timeout) * time.Second, 13 | }) 14 | 15 | if err != nil{ 16 | logs.Error("connect etcd failed, err: ",err) 17 | return 18 | } 19 | 20 | secLayerContext.etcdClient = cli 21 | logs.Debug("init etcd success") 22 | return 23 | } 24 | 25 | func InitSecLayer(conf *SecLayerConf)(err error){ 26 | 27 | err = initRedis(conf) 28 | if err!= nil{ 29 | logs.Error("init redis failed, err: %v",err) 30 | return 31 | } 32 | logs.Debug("init redis success") 33 | 34 | err = initEtcd(conf) 35 | if err != nil { 36 | logs.Error("init etcd failed, err: %v",err) 37 | return 38 | } 39 | logs.Debug("init etcd success") 40 | 41 | err = loadProductFromEtcd(conf) 42 | if err!= nil { 43 | logs.Error("load product from etcd failed, err: %v",err) 44 | return 45 | } 46 | logs.Debug("load product info success") 47 | 48 | secLayerContext.secLayerConf = conf 49 | secLayerContext.Read2HandleChan = make(chan *SecRequest, 50 | secLayerContext.secLayerConf.Read2HandleChanSize) 51 | secLayerContext.Handle2WriteChan = make(chan *SecResponse, 52 | secLayerContext.secLayerConf.Handle2WriteChanSize) 53 | 54 | secLayerContext.HistoryMap = make(map[int]*UserBuyHistory,1000000) 55 | 56 | secLayerContext.productCountMgr = NewProductCountMgr() 57 | 58 | logs.Debug("init all success") 59 | return 60 | } -------------------------------------------------------------------------------- /seckill/SecProxy/service/redis_proc.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/astaxie/beego/logs" 7 | "github.com/garyburd/redigo/redis" 8 | "time" 9 | ) 10 | 11 | func WriteHandle(){ 12 | for{ 13 | req := <-secKillConf.SecReqChan 14 | conn := secKillConf.proxy2LayerRedisPool.Get() 15 | 16 | data ,err := json.Marshal(req) 17 | if err !=nil{ 18 | logs.Error("json marshal failed, err: %v, req %v",err,req) 19 | } 20 | 21 | _, err = conn.Do("LPUSH", "sec_queue", string(data)) 22 | if err!= nil{ 23 | logs.Error("lpush failed, err: %v",err) 24 | conn.Close() 25 | } 26 | conn.Close() 27 | } 28 | } 29 | 30 | func ReadHandle(){ 31 | for { 32 | conn := secKillConf.proxy2LayerRedisPool.Get() 33 | reply, err := conn.Do("RPOP", "recv_queue") 34 | data, err := redis.String(reply, err) 35 | if err!= nil { 36 | time.Sleep(time.Second) 37 | conn.Close() 38 | continue 39 | } 40 | 41 | logs.Debug("rpop from recv_queue success, data: %v",string(data)) 42 | if err != nil{ 43 | logs.Error("rpop failed, err %v",err) 44 | continue 45 | } 46 | 47 | var result SecResult 48 | err = json.Unmarshal([]byte(data),&result) 49 | 50 | if err != nil { 51 | logs.Error("json Unmarshal failed, err :%v",err) 52 | continue 53 | } 54 | userKey := fmt.Sprintf("%s_%s", result.UserId, result.ProductId) 55 | 56 | secKillConf.UserConnMapLock.Lock() 57 | resultChan, ok := secKillConf.UserConnMap[userKey] 58 | secKillConf.UserConnMapLock.Unlock() 59 | if !ok { 60 | conn.Close() 61 | logs.Warn("user not found: %s",userKey) 62 | continue 63 | } 64 | resultChan <- &result 65 | conn.Close() 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /video_server/web/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "io" 7 | "io/ioutil" 8 | "log" 9 | "net/http" 10 | ) 11 | 12 | var httpClient *http.Client 13 | 14 | func init() { 15 | httpClient = &http.Client{} 16 | } 17 | 18 | func request(b *ApiBody, w http.ResponseWriter, r *http.Request) { 19 | var resp *http.Response 20 | var err error 21 | 22 | switch b.Method { 23 | case http.MethodGet: 24 | req, _ := http.NewRequest("GET", b.Url, nil) 25 | req.Header = r.Header 26 | resp, err = httpClient.Do(req) 27 | if err != nil { 28 | log.Printf(err.Error()) 29 | return 30 | } 31 | normalResponse(w, resp) 32 | case http.MethodPost: 33 | req, _ := http.NewRequest("POST", b.Url, bytes.NewBuffer([]byte(b.ReqBody))) 34 | req.Header = r.Header 35 | resp, err = httpClient.Do(req) 36 | if err != nil { 37 | log.Printf(err.Error()) 38 | return 39 | } 40 | normalResponse(w, resp) 41 | case http.MethodDelete: 42 | req, _ := http.NewRequest("Delete", b.Url, bytes.NewBuffer([]byte(b.ReqBody))) 43 | req.Header = r.Header 44 | resp, err = httpClient.Do(req) 45 | if err != nil { 46 | log.Printf(err.Error()) 47 | return 48 | } 49 | normalResponse(w, resp) 50 | default: 51 | w.WriteHeader(http.StatusBadRequest) 52 | io.WriteString(w, "Bad api request") 53 | return 54 | } 55 | } 56 | 57 | func normalResponse(w http.ResponseWriter, r *http.Response) { 58 | res, err := ioutil.ReadAll(r.Body) 59 | if err != nil { 60 | re, _ := json.Marshal(ErrorInternalFaults) 61 | w.WriteHeader(500) 62 | io.WriteString(w, string(re)) 63 | return 64 | } 65 | w.WriteHeader(r.StatusCode) 66 | io.WriteString(w, string(res)) 67 | } 68 | -------------------------------------------------------------------------------- /logcollection/log_transfer/kafka.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strings" 5 | "sync" 6 | 7 | "github.com/Shopify/sarama" 8 | "github.com/astaxie/beego/logs" 9 | ) 10 | 11 | /* 12 | var ( 13 | wg sync.WaitGroup 14 | ) 15 | */ 16 | 17 | type KafkaClient struct { 18 | client sarama.Consumer 19 | addr string 20 | topic string 21 | wg sync.WaitGroup 22 | } 23 | 24 | var ( 25 | kafkaClient *KafkaClient 26 | ) 27 | 28 | func initKafka(addr string, topic string) (err error) { 29 | 30 | kafkaClient = &KafkaClient{} 31 | 32 | consumer, err := sarama.NewConsumer(strings.Split(addr, ","), nil) 33 | if err != nil { 34 | logs.Error("init kafka failed, err:%v", err) 35 | return 36 | } 37 | 38 | kafkaClient.client = consumer 39 | kafkaClient.addr = addr 40 | kafkaClient.topic = topic 41 | return 42 | /* 43 | partitionList, err := consumer.Partitions(topic) 44 | if err != nil { 45 | logs.Error("Failed to get the list of partitions: ", err) 46 | return 47 | } 48 | 49 | for partition := range partitionList { 50 | pc, errRet := consumer.ConsumePartition("nginx_log", int32(partition), sarama.OffsetNewest) 51 | if errRet != nil { 52 | err = errRet 53 | logs.Error("Failed to start consumer for partition %d: %s\n", partition, err) 54 | return 55 | } 56 | defer pc.AsyncClose() 57 | go func(pc sarama.PartitionConsumer) { 58 | //wg.Add(1) 59 | for msg := range pc.Messages() { 60 | logs.Debug("Partition:%d, Offset:%d, Key:%s, Value:%s", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value)) 61 | //fmt.Println() 62 | } 63 | //wg.Done() 64 | }(pc) 65 | }*/ 66 | //time.Sleep(time.Hour) 67 | //wg.Wait() 68 | //consumer.Close() 69 | //return 70 | } 71 | -------------------------------------------------------------------------------- /logcollection/etcd/watcher/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "github.com/astaxie/beego/logs" 6 | "go.etcd.io/etcd/clientv3" 7 | "go.etcd.io/etcd/mvcc/mvccpb" 8 | "golang-awesome/logcollection/logagent/tail" 9 | "time" 10 | ) 11 | 12 | const ( 13 | EtcdKey = "/logagent/conf/" 14 | ) 15 | 16 | func initEtcdWatch(){ 17 | //wg := sync.WaitGroup{} 18 | //wg.Add(1) 19 | watchKey(EtcdKey) 20 | //wg.Wait() 21 | } 22 | func watchKey(key string) { 23 | cli, err := clientv3.New(clientv3.Config{ 24 | Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, 25 | DialTimeout: 5 * time.Second, 26 | }) 27 | if err != nil { 28 | logs.Error("connect etcd failed, err:", err) 29 | return 30 | } 31 | 32 | logs.Debug("begin watch key:%s", key) 33 | for { 34 | rch := cli.Watch(context.Background(), key) 35 | var collectConf []tail.CollectConf 36 | var getConfSucc = true 37 | for wresp := range rch { 38 | logs.Debug("watch -->",wresp) 39 | for _, ev := range wresp.Events { 40 | if ev.Type == mvccpb.DELETE { 41 | logs.Warn("key[%s] 's config deleted", key) 42 | continue 43 | } 44 | 45 | if ev.Type == mvccpb.PUT && string(ev.Kv.Key) == key { 46 | //err = json.Unmarshal(ev.Kv.Value, &collectConf) 47 | if err != nil { 48 | logs.Error("key [%s], Unmarshal[%s], err:%v ", err) 49 | getConfSucc = false 50 | continue 51 | } 52 | } 53 | logs.Debug("get config from etcd, %s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value) 54 | } 55 | 56 | if getConfSucc { 57 | logs.Debug("get config from etcd succ, %v", collectConf) 58 | tail.UpdateConfig(collectConf) 59 | } 60 | } 61 | 62 | } 63 | //wg.Done() 64 | } 65 | 66 | func main(){ 67 | initEtcdWatch() 68 | } 69 | -------------------------------------------------------------------------------- /goroutine/channel/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func send(ch chan<- int, exitChan chan int) { 8 | for i := 0; i < 10; i++ { 9 | ch <- i 10 | } 11 | 12 | close(ch) 13 | a:=1 14 | exitChan <- a 15 | } 16 | 17 | func recv(ch <-chan int, exitChan chan int) { 18 | for { 19 | v, ok := <-ch 20 | if !ok { 21 | break 22 | } 23 | fmt.Println(v) 24 | } 25 | 26 | a :=1 27 | exitChan <- a 28 | close(exitChan) 29 | } 30 | 31 | func main() { 32 | 33 | var ch chan int 34 | ch = make(chan int, 10) 35 | exitChan := make(chan int, 2) 36 | 37 | go send(ch, exitChan) 38 | go recv(ch, exitChan) 39 | 40 | //for i := 0; i < 2; i++ { 41 | // i2 := <-exitChan 42 | // fmt.Print(i2) 43 | //} 44 | 45 | //if channel not close, all goroutines are asleep - deadlock 46 | //for { 47 | // //_,ok := <-exitChan 48 | // //if !ok{ 49 | // // break 50 | // //} 51 | // select { 52 | // case a := <-exitChan: 53 | // fmt.Println(a) 54 | // } 55 | //} 56 | 57 | //for{ 58 | // _,ok := <-exitChan 59 | // if !ok{ 60 | // break 61 | // } 62 | //} 63 | 64 | //loop: 65 | //for { 66 | // select { 67 | // case _, ok := <-exitChan: 68 | // if !ok { 69 | // break loop 70 | // } 71 | // } 72 | //} 73 | 74 | // 75 | //for a := range exitChan{ 76 | // fmt.Println(a) 77 | //} 78 | 79 | //for { 80 | // select { 81 | // case _, ok := <-exitChan: 82 | // if !ok { 83 | // goto exit 84 | // } 85 | // } 86 | //} 87 | //exit: 88 | 89 | //channel关闭后不会阻塞,channel的len为0,从channel中取出来的值为该类型的默认值 90 | for { 91 | ok := false 92 | select { 93 | case _, ok=<-exitChan: 94 | } 95 | 96 | if !ok{ 97 | break 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /video_server/streamserver/handlers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/julienschmidt/httprouter" 5 | "html/template" 6 | "io" 7 | "io/ioutil" 8 | "log" 9 | "net/http" 10 | "os" 11 | "time" 12 | ) 13 | 14 | func testPageHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 15 | t, err := template.ParseFiles("./upload.html") 16 | if err != nil { 17 | log.Printf("%s",err) 18 | } 19 | t.Execute(w, nil) 20 | } 21 | 22 | func streamHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 23 | vid := p.ByName("vid-id") 24 | vl := VIDEO_DIR + vid 25 | video, err := os.Open(vl) 26 | if err != nil { 27 | sendErrorResponse(w, http.StatusInternalServerError, "error of open video: "+err.Error()) 28 | return 29 | } 30 | 31 | w.Header().Set("Content-Type", "video/mp4") 32 | http.ServeContent(w, r, "", time.Now(), video) 33 | defer video.Close() 34 | } 35 | 36 | func uploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 37 | r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE) 38 | if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil { 39 | sendErrorResponse(w, http.StatusBadRequest, "file is to large") 40 | return 41 | } 42 | 43 | file, _, err := r.FormFile("file") 44 | if err != nil { 45 | sendErrorResponse(w, http.StatusInternalServerError, err.Error()) 46 | } 47 | 48 | data, err := ioutil.ReadAll(file) 49 | if err != nil { 50 | log.Printf("read file error: %v", err) 51 | sendErrorResponse(w, http.StatusInternalServerError, err.Error()) 52 | } 53 | 54 | fn := p.ByName("vid-id") 55 | err = ioutil.WriteFile(VIDEO_DIR+fn, data, 0666) 56 | if err != nil { 57 | log.Printf("write file error: %v",err) 58 | sendErrorResponse(w, http.StatusInternalServerError,err.Error()) 59 | return 60 | } 61 | 62 | w.WriteHeader(http.StatusCreated) 63 | io.WriteString(w, "Uploaded successfully") 64 | } 65 | -------------------------------------------------------------------------------- /logcollection/web_admin/views/log/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 首页 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | {{range .loglist}} 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | {{end}} 33 | 34 |
日志ID项目名称日志收集路径创建时间TOPIC
{{.LogId}}{{.AppName}}{{.LogPath}}{{.CreateTime}}{{.Topic}}
35 |
36 | 37 | 38 | 39 | 43 | 44 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /goroutine/chart/chat_server/model/mgr.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "encoding/json" 8 | 9 | "github.com/garyburd/redigo/redis" 10 | ) 11 | 12 | var ( 13 | UserTable = "users" 14 | ) 15 | 16 | type UserMgr struct { 17 | pool *redis.Pool 18 | } 19 | 20 | func NewUserMgr(pool *redis.Pool) (mgr *UserMgr) { 21 | 22 | mgr = &UserMgr{ 23 | pool: pool, 24 | } 25 | return 26 | } 27 | 28 | func (p *UserMgr) getUser(conn redis.Conn, id int) (user *User, err error) { 29 | 30 | result, err := redis.String(conn.Do("HGet", UserTable, fmt.Sprintf("%d", id))) 31 | if err != nil { 32 | if err == redis.ErrNil { 33 | err = ErrUserNotExist 34 | } 35 | return 36 | } 37 | 38 | user = &User{} 39 | err = json.Unmarshal([]byte(result), user) 40 | if err != nil { 41 | return 42 | } 43 | return 44 | } 45 | 46 | func (p *UserMgr) Login(id int, passwd string) (user *User, err error) { 47 | 48 | conn := p.pool.Get() 49 | defer conn.Close() 50 | 51 | user, err = p.getUser(conn, id) 52 | if err != nil { 53 | return 54 | } 55 | 56 | if user.UserId != id || user.Passwd != passwd { 57 | err = ErrInvalidPasswd 58 | } 59 | 60 | user.Status = UserStatusOnline 61 | user.LastLogin = fmt.Sprintf("%v", time.Now()) 62 | 63 | return 64 | } 65 | 66 | func (p *UserMgr) Register(user *User) (err error) { 67 | 68 | conn := p.pool.Get() 69 | defer conn.Close() 70 | 71 | if user == nil { 72 | fmt.Println("invalid user") 73 | err = ErrInvalidParams 74 | return 75 | } 76 | 77 | _, err = p.getUser(conn, user.UserId) 78 | if err == nil { 79 | err = ErrUserExist 80 | return 81 | } 82 | 83 | if err != ErrUserNotExist { 84 | return 85 | } 86 | 87 | data, err := json.Marshal(user) 88 | if err != nil { 89 | return 90 | } 91 | 92 | _, err = conn.Do("HSet", UserTable, fmt.Sprintf("%d", user.UserId), string(data)) 93 | if err != nil { 94 | return 95 | } 96 | return 97 | } 98 | -------------------------------------------------------------------------------- /logcollection/web_admin/views/log/apply.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 项目申请 7 | 8 | 13 | 14 | 15 |
16 |
17 |
18 |
19 | 20 |
21 | 22 |
23 |
24 |
25 | 26 |
27 | 28 |
29 |
30 |
31 | 32 |
33 | 34 |
35 |
36 |
37 |
38 | 39 | 40 |
41 |
42 |
43 |
44 |
45 | 46 | 47 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /crawler-distributed/distributed.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "golang-awesome/crawler-distributed/config" 6 | "golang-awesome/crawler-distributed/persist/client" 7 | "golang-awesome/crawler-distributed/rpcsupport" 8 | worker "golang-awesome/crawler-distributed/worker/client" 9 | "golang-awesome/crawler/engine" 10 | "golang-awesome/crawler/scheduler" 11 | "golang-awesome/crawler/zhenai/parser" 12 | "log" 13 | "net/rpc" 14 | "strings" 15 | ) 16 | 17 | func createClientPool(hosts []string) chan *rpc.Client{ 18 | var clients []*rpc.Client 19 | for _, h := range hosts{ 20 | client, err := rpcsupport.NewClient(h) 21 | if err != nil { 22 | log.Printf("error connection to %s : %s",h,err) 23 | }else { 24 | clients = append(clients, client) 25 | log.Printf("connected to %s",h) 26 | } 27 | } 28 | out := make(chan *rpc.Client) 29 | //持续分发客户端 30 | go func() { 31 | for{ 32 | for _, c := range clients { 33 | out <- c 34 | } 35 | } 36 | }() 37 | return out 38 | } 39 | 40 | var hosts = flag.String("hosts", ":9002","多个工作节点的端口,以都好分隔,如:9002,:9003") 41 | 42 | func main(){ 43 | flag.Parse() 44 | itemChan, err := client.ItemSaver(config.ItemSaverPort) 45 | if err != nil{ 46 | panic(err) 47 | } 48 | log.Printf("connected item saver at: %v",config.ItemSaverPort) 49 | 50 | pool := createClientPool(strings.Split(*hosts,",")) 51 | 52 | processor:= worker.CreateProcessor(pool) 53 | 54 | var seed []engine.Request 55 | seed = []engine.Request{ 56 | { 57 | Url:"http://www.zhenai.com/zhenghun", 58 | Parse: engine.NewFuncParser(parser.ParseCityList,"ParseCityList"), 59 | }, 60 | //{ 61 | // Url: "http://www.zhenai.com/zhenghun/henan", 62 | // Parse: engine.NewFuncParser(parser.ParseCity, "ParseCity"), 63 | //}, 64 | //{ 65 | // Url: "http://www.zhenai.com/zhenghun/beijing", 66 | // Parse: engine.NewFuncParser(parser.ParseCity, "ParseCity"), 67 | //}, 68 | } 69 | 70 | e := engine.ConcurrentEngine{ 71 | MaxWorkerCount:100, 72 | Scheduler:&scheduler.QueuedScheduler{}, 73 | ItemChan:itemChan, 74 | RequestWorker:processor, 75 | } 76 | e.Run(seed...) 77 | } 78 | -------------------------------------------------------------------------------- /goroutine/chart/chat_client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/binary" 5 | "encoding/json" 6 | "errors" 7 | "net" 8 | "fmt" 9 | "golang-awesome/goroutine/chart/proto" 10 | ) 11 | 12 | func readPackage(conn net.Conn) (msg proto.Message, err error) { 13 | var buf [8192]byte 14 | n, err := conn.Read(buf[0:4]) 15 | if n != 4 { 16 | err = errors.New("read header failed") 17 | return 18 | } 19 | fmt.Println("read package:", buf[0:4]) 20 | 21 | var packLen uint32 22 | packLen = binary.BigEndian.Uint32(buf[0:4]) 23 | 24 | fmt.Printf("receive len:%d", packLen) 25 | n, err = conn.Read(buf[0:packLen]) 26 | if n != int(packLen) { 27 | err = errors.New("read body failed") 28 | return 29 | } 30 | 31 | fmt.Printf("receive data:%s\n", string(buf[0:packLen])) 32 | err = json.Unmarshal(buf[0:packLen], &msg) 33 | if err != nil { 34 | fmt.Println("unmarshal failed, err:", err) 35 | } 36 | return 37 | } 38 | 39 | func login(conn net.Conn) (err error) { 40 | var msg proto.Message 41 | msg.Cmd = proto.UserLogin 42 | 43 | var loginCmd proto.LoginCmd 44 | loginCmd.Id = 1 45 | loginCmd.Passwd = "123456789" 46 | 47 | data, err := json.Marshal(loginCmd) 48 | if err != nil { 49 | return 50 | } 51 | 52 | msg.Data = string(data) 53 | data, err = json.Marshal(msg) 54 | if err != nil { 55 | return 56 | } 57 | 58 | var buf [4]byte 59 | packLen := uint32(len(data)) 60 | 61 | fmt.Println("packlen:", packLen) 62 | binary.BigEndian.PutUint32(buf[0:4], packLen) 63 | 64 | n, err := conn.Write(buf[:]) 65 | if err != nil || n != 4 { 66 | fmt.Println("write data failed") 67 | return 68 | } 69 | 70 | _, err = conn.Write([]byte(data)) 71 | if err != nil { 72 | return 73 | } 74 | 75 | msg, err = readPackage(conn) 76 | if err != nil { 77 | fmt.Println("read package failed, err:", err) 78 | } 79 | 80 | fmt.Println(msg) 81 | return 82 | } 83 | 84 | func main() { 85 | conn, err := net.Dial("tcp", "localhost:10000") 86 | if err != nil { 87 | fmt.Println("Error dialing", err.Error()) 88 | return 89 | } 90 | 91 | err = login(conn) 92 | if err != nil { 93 | fmt.Println("login failed, err:", err) 94 | return 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /seckill/SecProxy/service/antispam.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego/logs" 6 | "sync" 7 | ) 8 | 9 | type SecLimitMgr struct { 10 | UserLimitMap map[int]*Limit 11 | IpLimitMap map[string]*Limit 12 | lock sync.Mutex 13 | } 14 | 15 | func antiSpam(req *SecRequest)( err error){ 16 | _,ok := secKillConf.idBlackMap[req.UserId] 17 | if ok { 18 | err = fmt.Errorf("invalid request") 19 | logs.Error("userId[%d] is block by id black",req.UserId) 20 | return 21 | } 22 | 23 | _,ok = secKillConf.ipBlackMap[req.ClientAddr] 24 | if ok { 25 | err = fmt.Errorf("invalid request") 26 | logs.Error("userId[%d] ip[%s] id block by ip black",req.UserId,req.ClientAddr) 27 | return 28 | } 29 | 30 | secKillConf.secLimitMgr.lock.Lock() 31 | //uid 频率控制,防刷 32 | limit,ok := secKillConf.secLimitMgr.UserLimitMap[req.UserId] 33 | if !ok { 34 | limit = &Limit{ 35 | secLimit: &SecLimit{}, 36 | minLimit: &MinLimit{}, 37 | } 38 | 39 | secKillConf.secLimitMgr.UserLimitMap[req.UserId] = limit 40 | } 41 | secIdCount := limit.secLimit.Count(req.AccessTime.Unix()) 42 | minIdCount := limit.minLimit.Count(req.AccessTime.Unix()) 43 | 44 | //ip 频率控制 45 | limit, ok = secKillConf.secLimitMgr.IpLimitMap[req.ClientAddr] 46 | if !ok { 47 | limit = &Limit{ 48 | secLimit:&SecLimit{}, 49 | minLimit:&MinLimit{}, 50 | } 51 | secKillConf.secLimitMgr.IpLimitMap[req.ClientAddr] = limit 52 | } 53 | 54 | secIpCount := limit.secLimit.Count(req.AccessTime.Unix()) 55 | minIpCount := limit.minLimit.Count(req.AccessTime.Unix()) 56 | 57 | secKillConf.secLimitMgr.lock.Unlock() 58 | 59 | if secIpCount > secKillConf.AccessLimitConf.IPSecAccessLimit { 60 | err = fmt.Errorf("invalid request") 61 | return 62 | } 63 | 64 | if minIpCount > secKillConf.AccessLimitConf.IPMinAccessLimit { 65 | err = fmt.Errorf("invalid request") 66 | return 67 | } 68 | 69 | if secIdCount > secKillConf.AccessLimitConf.UserSecAccessLimit { 70 | err = fmt.Errorf("invalid request") 71 | return 72 | } 73 | 74 | if minIdCount > secKillConf.AccessLimitConf.UserMinAccessLimit { 75 | err = fmt.Errorf("invalid request") 76 | return 77 | } 78 | 79 | return 80 | } 81 | -------------------------------------------------------------------------------- /logcollection/web_admin/controllers/AppController/app.go: -------------------------------------------------------------------------------- 1 | package AppController 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego" 6 | "github.com/astaxie/beego/logs" 7 | "golang-awesome/logcollection/web_admin/models" 8 | "strings" 9 | ) 10 | 11 | type AppController struct { 12 | beego.Controller 13 | } 14 | 15 | func (a *AppController) AppList(){ 16 | logs.Debug("enter index controller") 17 | 18 | a.Layout = "layout/layout.html" 19 | appList, err := models.GetAllAppInfo() 20 | if err != nil { 21 | a.Data["Error"] = fmt.Sprintf("服务器繁忙") 22 | a.TplName = "app/error.html" 23 | 24 | logs.Warn("get app list failed, err:%v", err) 25 | return 26 | } 27 | 28 | logs.Debug("get app list succ, data:%v", appList) 29 | a.Data["applist"] = appList 30 | 31 | a.TplName = "app/index.html" 32 | } 33 | 34 | func (a *AppController) AppApply(){ 35 | logs.Debug("enter apply controller") 36 | a.Layout = "layout/layout.html" 37 | a.TplName = "app/apply.html" 38 | } 39 | 40 | func (a *AppController) AppCreate(){ 41 | logs.Debug("enter appCreate controller") 42 | appName := a.GetString("appName") 43 | appType := a.GetString("appType") 44 | developPath := a.GetString("devPath") 45 | ipstr := a.GetString("iplist") 46 | 47 | a.Layout = "layout/layout.html" 48 | 49 | if len(appName) == 0 || len(appType) == 0 || len(developPath) == 0 || len(ipstr) == 0 { 50 | a.Data["Error"] = fmt.Sprintf("非法参数") 51 | a.TplName = "app/error.html" 52 | 53 | logs.Warn("invalid parameter") 54 | return 55 | } 56 | 57 | appInfo := &models.AppInfo{} 58 | appInfo.AppName = appName 59 | appInfo.AppType = appType 60 | appInfo.DevelopPath = developPath 61 | appInfo.IP = strings.Split(ipstr, ",") 62 | 63 | err := models.CreateApp(appInfo) 64 | if err != nil { 65 | a.Data["Error"] = fmt.Errorf(err.Error()) 66 | a.TplName = "app/error.html" 67 | return 68 | } 69 | 70 | a.Redirect("/app/list", 302) 71 | } 72 | 73 | 74 | func (a *AppController) TestRestful(){ 75 | appList, err := models.GetAllAppInfo() 76 | if err != nil{ 77 | logs.Warn("get appInfo failed ,err:",err) 78 | return 79 | } 80 | a.Data["json"] = map[string]interface{}{"success": 200, "data": appList} 81 | a.ServeJSON() 82 | } 83 | -------------------------------------------------------------------------------- /goroutine/maze/maze.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | func readMaze(fileName string)[][]int{ 9 | file, err := os.Open(fileName) 10 | if err != nil{ 11 | panic(err) 12 | } 13 | 14 | var row, col int 15 | fmt.Fscanf(file,"%d %d", &row, &col) 16 | 17 | maze := make([][]int,row) 18 | for i := range maze{ 19 | maze[i] = make([]int, col) 20 | for j := range maze[i]{ 21 | fmt.Fscanf(file,"%d",&maze[i][j]) 22 | } 23 | } 24 | return maze 25 | } 26 | 27 | type point struct { 28 | i, j int 29 | } 30 | 31 | //directions, up -> left -> down -> right 32 | var dirs = [4]point{ 33 | {-1,0},{0,-1},{1,0},{0,1}} 34 | 35 | 36 | func (p point) add(r point) point{ 37 | return point{p.i +r.i,p.j+r.j} 38 | } 39 | 40 | func (p point) at(gird [][]int) (int, bool){ 41 | if p.i < 0 || p.i >= len(gird){ 42 | return 0,false 43 | } 44 | 45 | if p.j < 0 || p.j >= len(gird[p.i]){ 46 | return 0,false 47 | } 48 | return gird[p.i][p.j],true 49 | } 50 | 51 | func walk(maze [][]int,start,end point) [][]int{ 52 | steps := make([][]int,len(maze)) 53 | for i:= range steps{ 54 | steps[i] = make([]int,len(maze[i])) 55 | } 56 | 57 | Q := []point{start} 58 | for len(Q) > 0{ 59 | cur := Q[0] 60 | Q = Q[1:] 61 | 62 | if cur == end{ 63 | break 64 | } 65 | for _, dir := range dirs{ 66 | next := cur.add(dir) 67 | // maze at next is zero 68 | val, ok := next.at(maze) 69 | if !ok || val == 1 { 70 | continue 71 | } 72 | // and step at next is zero 73 | val, ok = next.at(steps) 74 | if !ok || val !=0 { 75 | continue 76 | } 77 | // and next != start 78 | if next == start { 79 | continue 80 | } 81 | curSteps,_ := cur.at(steps) 82 | steps[next.i][next.j] = curSteps + 1 83 | Q = append(Q,next) 84 | } 85 | } 86 | return steps 87 | } 88 | 89 | 90 | 91 | func main(){ 92 | maze := readMaze( "goroutine/maze/maze.dat") 93 | steps := walk(maze,point{0,0},point{len(maze) - 1,len(maze[0]) - 1}) 94 | 95 | for _,row := range steps{ 96 | for _, val := range row { 97 | fmt.Printf("%3d",val) 98 | } 99 | fmt.Println() 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /crawler-distributed/worker/types.go: -------------------------------------------------------------------------------- 1 | package worker 2 | 3 | import ( 4 | "github.com/pkg/errors" 5 | "golang-awesome/crawler/engine" 6 | "golang-awesome/crawler/zhenai/parser" 7 | "log" 8 | ) 9 | 10 | type SerializedParser struct{ 11 | Name string 12 | Args interface{} 13 | } 14 | 15 | type Request struct { 16 | Url string 17 | Parser SerializedParser 18 | } 19 | 20 | type ParseResult struct { 21 | Items []engine.Item 22 | Requests []Request 23 | } 24 | 25 | func SerializeRequest(r engine.Request) Request{ 26 | name, args := r.Parse.Serialize() 27 | return Request{ 28 | Url:r.Url, 29 | Parser:SerializedParser{ 30 | Name:name, 31 | Args:args, 32 | }, 33 | } 34 | } 35 | 36 | func SerializeResult(r engine.ParserResult) (p ParseResult){ 37 | p.Items = r.Items 38 | for _, req := range r.Requests{ 39 | p.Requests = append(p.Requests, SerializeRequest(req)) 40 | } 41 | 42 | return p 43 | } 44 | 45 | 46 | func deserializeParser(p SerializedParser)(engine.Parser, error){ 47 | switch p.Name { 48 | case "ParseCity": 49 | return engine.NewFuncParser(parser.ParseCity,p.Name),nil 50 | case "ParseCityList": 51 | return engine.NewFuncParser(parser.ParseCityList,p.Name),nil 52 | case "ProfileParser": 53 | if userName, ok := p.Args.(string);ok{ 54 | return parser.NewProfileParser(userName),nil 55 | }else { 56 | return nil,errors.New("invalid args for profileParser") 57 | } 58 | case "NilParser": 59 | return engine.NilParse{},nil 60 | default: 61 | return nil, errors.New("unknown parser name") 62 | } 63 | 64 | } 65 | 66 | func DeserializeRequest(r Request)(engine.Request,error){ 67 | parse,err := deserializeParser(r.Parser) 68 | if err != nil { 69 | return engine.Request{}, err 70 | } 71 | req := engine.Request{ 72 | Url: r.Url, 73 | Parse:parse, 74 | } 75 | return req, nil 76 | } 77 | 78 | func DeserializeResult(r ParseResult) engine.ParserResult{ 79 | result := engine.ParserResult{ 80 | Items: r.Items, 81 | } 82 | 83 | for _, req := range r.Requests{ 84 | ereq, err := DeserializeRequest(req) 85 | if err != nil { 86 | log.Printf("error deserialize request: %v",err) 87 | continue 88 | } 89 | result.Requests = append(result.Requests,ereq) 90 | } 91 | return result 92 | } 93 | -------------------------------------------------------------------------------- /logcollection/logagent/main/config.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "github.com/astaxie/beego/config" 7 | "golang-awesome/logcollection/logagent/tail" 8 | ) 9 | 10 | var ( 11 | appConfig *Config 12 | ) 13 | 14 | type Config struct { 15 | logLevel string 16 | logPath string 17 | chanSize int 18 | kafkaAddr string 19 | etcdAddr string 20 | etcdKey string 21 | collectConf []tail.CollectConf 22 | } 23 | 24 | 25 | func loadCollectConf(conf config.Configer) (err error) { 26 | var cc tail.CollectConf 27 | cc.LogPath = conf.String("collect::log_path") 28 | if len(cc.LogPath) == 0 { 29 | err = errors.New("invalid collect::log_path") 30 | return 31 | } 32 | 33 | cc.Topic = conf.String("collect::topic") 34 | if len(cc.Topic) == 0 { 35 | err = errors.New("invalid collect::topic") 36 | return 37 | } 38 | 39 | appConfig.collectConf = append(appConfig.collectConf, cc) 40 | return 41 | } 42 | 43 | func loadConf(confType string, filename string) (err error) { 44 | conf, err := config.NewConfig(confType, filename) 45 | if err != nil { 46 | fmt.Println("new config failed ,err :", err) 47 | return 48 | } 49 | 50 | appConfig = &Config{} 51 | appConfig.logLevel = conf.String("logs::log_level") 52 | if len(appConfig.logLevel) == 0 { 53 | appConfig.logLevel = "debug" 54 | } 55 | 56 | appConfig.logPath = conf.String("logs::log_path") 57 | if len(appConfig.logPath) == 0 { 58 | appConfig.logPath = "./logs" 59 | } 60 | 61 | appConfig.chanSize, err = conf.Int("collect::chan_size") 62 | if err != nil { 63 | appConfig.chanSize = 100 64 | } 65 | 66 | appConfig.kafkaAddr= conf.String("kafka::server_addr") 67 | if len(appConfig.kafkaAddr) == 0 { 68 | err = fmt.Errorf("invalid kafka address") 69 | return 70 | } 71 | 72 | appConfig.etcdAddr= conf.String("etcd::addr") 73 | if len(appConfig.etcdAddr) == 0 { 74 | err = fmt.Errorf("invalid etcd addr") 75 | return 76 | } 77 | 78 | appConfig.etcdKey= conf.String("etcd::configKey") 79 | if len(appConfig.etcdKey) == 0 { 80 | err = fmt.Errorf("invalid etcd key") 81 | return 82 | } 83 | 84 | err = loadCollectConf(conf) 85 | if err != nil { 86 | fmt.Printf("load collect conf failed, err:%v\n", err) 87 | return 88 | } 89 | return 90 | } 91 | -------------------------------------------------------------------------------- /video_server/api/dbops/iternal.go: -------------------------------------------------------------------------------- 1 | package dbops 2 | 3 | import ( 4 | "database/sql" 5 | "golang-awesome/video_server/api/defs" 6 | "log" 7 | "strconv" 8 | "sync" 9 | ) 10 | 11 | func InsertSession(sid string, ttl int64, uname string)(err error ){ 12 | ttlstr := strconv.FormatInt(ttl, 10) 13 | stmtIns, err := dbConn.Prepare("insert into sessions (session_id, TTL, login_name) values (?,?,?)") 14 | if err != nil { 15 | return 16 | } 17 | _, err = stmtIns.Exec(sid, ttlstr, uname) 18 | defer stmtIns.Close() 19 | return 20 | } 21 | 22 | func RetrieveSession(sid string)(session *defs.SimpleSession, err error){ 23 | stmtOut, err := dbConn.Prepare("select TTL, login_name from sessions where session_id = ?") 24 | if err != nil { 25 | return 26 | } 27 | var ttl, uname string 28 | err = stmtOut.QueryRow(sid).Scan(&ttl, &uname) 29 | if err != nil && err != sql.ErrNoRows{ 30 | return 31 | } 32 | if res, err := strconv.ParseInt(ttl,10,64); err == nil { 33 | session.TTL = res 34 | session.UserName = uname 35 | }else { 36 | return 37 | } 38 | 39 | defer stmtOut.Close() 40 | return 41 | } 42 | 43 | func RetrieveAllSessions()(m *sync.Map,err error){ 44 | stmtOut, err := dbConn.Prepare("select * from sessions") 45 | if err != nil { 46 | log.Printf("%s",err) 47 | return 48 | } 49 | rows, err := stmtOut.Query() 50 | if err != nil { 51 | log.Printf("%s",err) 52 | return 53 | } 54 | 55 | for rows.Next() { 56 | var id, ttlstr, login_name string 57 | if err := rows.Scan(&id, &ttlstr, &login_name); err != nil { 58 | log.Printf("retrieve sessions error: %s",err) 59 | break 60 | } 61 | if ttl, err := strconv.ParseInt(ttlstr, 10, 64); err != nil { 62 | ss := &defs.SimpleSession{ 63 | UserName:login_name, 64 | TTL: ttl, 65 | } 66 | m.Store(id, ss) 67 | log.Printf("session id: %s, ttl: %d",id,ss.TTL) 68 | }else{ 69 | log.Printf("parse TTL error: %s",err) 70 | break 71 | } 72 | } 73 | return 74 | } 75 | 76 | func DeleteSession(sid string)(err error){ 77 | stmtOut, err := dbConn.Prepare("delete from sessions where session_id =?") 78 | if err != nil { 79 | return 80 | } 81 | if _, err := stmtOut.Query(sid); err != nil { 82 | return 83 | } 84 | 85 | defer stmtOut.Close() 86 | return 87 | } 88 | -------------------------------------------------------------------------------- /logcollection/web_admin/views/app/apply.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 项目申请 7 | 8 | 13 | 14 | 15 |
16 |
17 |
18 |
19 | 20 |
21 | 22 |
23 |
24 |
25 | 26 |
27 | 28 |
29 |
30 |
31 | 32 |
33 | 34 |
35 |
36 |
37 | 38 |
39 | 40 |
41 |
42 |
43 |
44 | 45 | 46 |
47 |
48 |
49 |
50 |
51 | 52 | 53 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /video_server/web/handlers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/julienschmidt/httprouter" 6 | "html/template" 7 | "io" 8 | "io/ioutil" 9 | "log" 10 | "net/http" 11 | "net/http/httputil" 12 | "net/url" 13 | ) 14 | 15 | type HomePage struct { 16 | Name string 17 | } 18 | 19 | type UserPage struct { 20 | Name string 21 | } 22 | 23 | func homeHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 24 | cname, err := r.Cookie("username") 25 | sid, err := r.Cookie("session") 26 | if err != nil { 27 | p := &HomePage{Name: "JAYCE"} 28 | t, e := template.ParseFiles("./templates/home.html") 29 | if e != nil { 30 | log.Printf("Parsing template home.html error: %s", e) 31 | return 32 | } 33 | t.Execute(w, p) 34 | return 35 | } 36 | 37 | if len(cname.Value) != 0 && len(sid.Value) != 0 { 38 | http.Redirect(w, r, "/userhome", http.StatusFound) 39 | return 40 | } 41 | } 42 | 43 | func userHomeHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { 44 | cname, err := r.Cookie("username") 45 | _, err = r.Cookie("session") 46 | if err != nil { 47 | http.Redirect(w, r, "/", http.StatusFound) 48 | return 49 | } 50 | 51 | fname := r.FormValue("username") 52 | var p *UserPage 53 | if len(cname.Value) != 0 { 54 | p = &UserPage{Name: cname.Value} 55 | } else if len(fname) != 0 { 56 | p = &UserPage{Name: fname} 57 | } 58 | files, err := template.ParseFiles("./templates/userhome.html") 59 | if err != nil { 60 | log.Printf("parsing userhome.html error: %s", err) 61 | return 62 | } 63 | 64 | files.Execute(w, p) 65 | } 66 | 67 | func apiHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { 68 | if r.Method != http.MethodPost { 69 | re, _ := json.Marshal(ErrorRequestNotRecognized) 70 | io.WriteString(w, string(re)) 71 | return 72 | } 73 | 74 | res, _ := ioutil.ReadAll(r.Body) 75 | apiBody := &ApiBody{} 76 | if err := json.Unmarshal(res, apiBody); err != nil { 77 | re, _ := json.Marshal(ErrorRequestBodyParseFailed) 78 | io.WriteString(w, string(re)) 79 | return 80 | } 81 | request(apiBody, w, r) 82 | defer r.Body.Close() 83 | } 84 | 85 | func proxyHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { 86 | parse, _ := url.Parse("http://127.0.0.1:9000/") 87 | proxy := httputil.NewSingleHostReverseProxy(parse) 88 | proxy.ServeHTTP(w, r) 89 | } 90 | -------------------------------------------------------------------------------- /seckill/SecProxy/service/config.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "github.com/garyburd/redigo/redis" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | const ( 10 | ProductStatusNormal = 0 11 | ProductStatusSaleOut = 1 12 | ProductStatusForceSaleOut = 2 13 | ) 14 | 15 | type RedisConf struct { 16 | RedisAddr string 17 | RedisPwd string 18 | RedisMaxIdle int 19 | RedisMaxActive int 20 | RedisIdleTimeout int 21 | } 22 | 23 | type EtcdConf struct { 24 | EtcdAddr string 25 | Timeout int 26 | EtcdSecKeyPrefix string 27 | EtcdSecProductKey string 28 | } 29 | 30 | type AccessLimitConf struct { 31 | IPSecAccessLimit int 32 | UserSecAccessLimit int 33 | IPMinAccessLimit int 34 | UserMinAccessLimit int 35 | } 36 | 37 | type SecProductInfoConf struct { 38 | ProductId int 39 | StartTime int64 40 | EndTime int64 41 | Status int 42 | Total int 43 | Left int 44 | } 45 | 46 | type SecKillConf struct { 47 | RedisBlackConf RedisConf 48 | RedisProxy2LayerConf RedisConf 49 | RedisLayer2ProxyConf RedisConf 50 | 51 | EtcdConf EtcdConf 52 | LogPath string 53 | LogLevel string 54 | SecProductInfoMap map[int]*SecProductInfoConf 55 | RWSecProductLock sync.RWMutex 56 | CookieSecretKey string 57 | 58 | ReferWhiteList []string 59 | 60 | ipBlackMap map[string]bool 61 | idBlackMap map[int]bool 62 | 63 | AccessLimitConf AccessLimitConf 64 | blackRedisPool *redis.Pool 65 | proxy2LayerRedisPool *redis.Pool 66 | layer2ProxyRedisPool *redis.Pool 67 | 68 | secLimitMgr *SecLimitMgr 69 | 70 | RWBlackLock sync.RWMutex 71 | WriteProxy2LayerGoroutineNum int 72 | ReadProxy2LayerGoroutineNum int 73 | 74 | SecReqChan chan*SecRequest 75 | SecReqChanSize int 76 | 77 | UserConnMap map[string]chan *SecResult 78 | UserConnMapLock sync.Mutex 79 | } 80 | 81 | type SecRequest struct { 82 | ProductId int 83 | Source string 84 | AuthCode string 85 | SecTime string 86 | Nance string 87 | UserId int 88 | UserAuthSign string 89 | AccessTime time.Time 90 | ClientAddr string 91 | ClientReferer string 92 | CloseNotify <-chan bool `json:"-"` 93 | 94 | ResultChan chan *SecResult `json:"-"` 95 | } 96 | 97 | type SecResult struct{ 98 | ProductId int 99 | UserId int 100 | Code int 101 | Token string 102 | } -------------------------------------------------------------------------------- /logcollection/web_admin/models/app.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "github.com/astaxie/beego/logs" 5 | "github.com/jmoiron/sqlx" 6 | ) 7 | 8 | type AppInfo struct { 9 | AppId int `db:"app_id" json:"appId""` 10 | AppName string `db:"app_name" json:"appName"` 11 | AppType string `db:"app_type" json:"appType"` 12 | CreateTime string `db:"create_time" json:"createTime"` 13 | DevelopPath string `db:"dev_path" json:"developPath"` 14 | IP []string 15 | } 16 | 17 | var ( 18 | Db *sqlx.DB 19 | ) 20 | 21 | func InitDb(db *sqlx.DB) { 22 | Db = db 23 | } 24 | 25 | func GetAllAppInfo() (appList []AppInfo, err error) { 26 | err = Db.Select(&appList, "select app_id, app_name, app_type, create_time, dev_path from tbl_app_info") 27 | if err != nil { 28 | logs.Warn("Get All App Info failed, err:%v", err) 29 | return 30 | } 31 | return 32 | } 33 | 34 | func CreateApp(info *AppInfo)(err error){ 35 | 36 | tx, err := Db.Begin() 37 | if err != nil{ 38 | logs.Warn("createApp failed, Db.Begin error: %v",err) 39 | return 40 | } 41 | 42 | //事务提交或者回滚 43 | defer func(){ 44 | if err != nil{ 45 | tx.Rollback() 46 | return 47 | } 48 | tx.Commit() 49 | }() 50 | 51 | result, err := tx.Exec("insert into tbl_app_info(app_name,app_type,dev_path) values (?,?,?)", 52 | info.AppName, info.AppType, info.DevelopPath) 53 | if err != nil{ 54 | logs.Warn("insert into tbl_app_info failed ,err:%v",err) 55 | return 56 | } 57 | 58 | id, err := result.LastInsertId() 59 | if err != nil{ 60 | logs.Warn("get lastInsertId failed, err:%v",err) 61 | return 62 | } 63 | for _,ip := range info.IP{ 64 | _, err = tx.Exec("insert into tbl_app_ip (app_id,ip) values (?,?)", id, ip) 65 | if err != nil { 66 | logs.Warn("insert into app_tbl_ip failed, err%v",err) 67 | } 68 | return 69 | } 70 | 71 | return 72 | } 73 | 74 | 75 | func GetIPInfoByName(appName string) (iplist []string, err error) { 76 | 77 | var appId []int 78 | err = Db.Select(&appId, "select app_id from tbl_app_info where app_name=?", appName) 79 | if err != nil || len(appId) == 0 { 80 | logs.Warn("select app_id failed, Db.Exec error:%v", err) 81 | return 82 | } 83 | 84 | err = Db.Select(&iplist, "select ip from tbl_app_ip where app_id=?", appId[0]) 85 | if err != nil { 86 | logs.Warn("Get All App Info failed, err:%v", err) 87 | return 88 | } 89 | 90 | logs.Warn("get appId ",iplist) 91 | return 92 | } -------------------------------------------------------------------------------- /logcollection/web_admin/controllers/LogController/log.go: -------------------------------------------------------------------------------- 1 | package LogController 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego" 6 | "github.com/astaxie/beego/logs" 7 | "golang-awesome/logcollection/web_admin/models" 8 | ) 9 | 10 | type LogController struct { 11 | beego.Controller 12 | } 13 | 14 | func (a *LogController) LogList() { 15 | logs.Debug("enter logList controller") 16 | a.Layout = "layout/layout.html" 17 | a.Layout = "layout/layout.html" 18 | logList, err := models.GetAllLogInfo() 19 | if err != nil { 20 | a.Data["Error"] = fmt.Sprintf("服务器繁忙") 21 | a.TplName = "app/error.html" 22 | 23 | logs.Warn("get app list failed, err:%v", err) 24 | return 25 | } 26 | 27 | logs.Debug("get log list succ, data:%v", logList) 28 | a.Data["loglist"] = logList 29 | 30 | a.TplName = "log/index.html" 31 | } 32 | 33 | func (a *LogController) LogApply() { 34 | logs.Debug(" enter logApply controller") 35 | a.Layout = "layout/layout.html" 36 | a.TplName = "log/apply.html" 37 | 38 | } 39 | 40 | func (a *LogController) LogCreate() { 41 | logs.Debug("enter logCreate controller") 42 | appName := a.GetString("appName") 43 | logPath := a.GetString("logPath") 44 | topic := a.GetString("topic") 45 | 46 | a.Layout = "layout/layout.html" 47 | if len(appName) == 0 || len(logPath) == 0 || len(topic) == 0 { 48 | a.Data["Error"] = fmt.Sprintf("非法参数") 49 | a.TplName = "log/error.html" 50 | 51 | logs.Warn("invalid parameter") 52 | return 53 | } 54 | 55 | logInfo := &models.LogInfo{ 56 | AppName: appName, 57 | LogPath: logPath, 58 | Topic: topic, 59 | } 60 | 61 | err := models.CreateLog(logInfo) 62 | logs.Debug(err) 63 | if err != nil { 64 | a.Data["Error"] = fmt.Errorf(err.Error()) 65 | logs.Warn("create logInfo failed, err%v", err) 66 | a.TplName = "app/error.html" 67 | return 68 | } 69 | 70 | iplist, err := models.GetIPInfoByName(appName) 71 | if err != nil || len(iplist) == 0{ 72 | a.Data["Error"] = fmt.Sprintf("获取项目ip失败,数据库繁忙") 73 | a.TplName = "log/error.html" 74 | 75 | logs.Warn("invalid parameter") 76 | return 77 | } 78 | keyFormat := "/net/badme/logagent/config/%s" 79 | 80 | logs.Debug(" get iplist:",iplist) 81 | 82 | for _, ip := range iplist { 83 | key := fmt.Sprintf(keyFormat, ip) 84 | err = models.SetLogConfToEtcd(key, logInfo) 85 | if err != nil { 86 | logs.Warn("Set log conf to etcd failed, err:%v", err) 87 | continue 88 | } 89 | } 90 | a.Redirect("/log/list", 302) 91 | 92 | } 93 | -------------------------------------------------------------------------------- /seckill/SecProxy/tools/setconf/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | etcdClient "go.etcd.io/etcd/clientv3" 8 | "time" 9 | 10 | 11 | ) 12 | 13 | const ( 14 | EtcdKey = "/net/badme/backend/seckill/product" 15 | ) 16 | 17 | type SecProductInfoConf = struct { 18 | ProductId int 19 | StartTime int64 20 | EndTime int64 21 | Status int 22 | Total int 23 | Left int 24 | OnePersonBuyLimit int 25 | BuyRate float64 26 | //每秒组多能卖多少个 27 | SoldMaxLimit int 28 | } 29 | 30 | 31 | func SetLogConfToEtcd() { 32 | cli, err := etcdClient.New(etcdClient.Config{ 33 | Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, 34 | DialTimeout: 5 * time.Second, 35 | }) 36 | if err != nil { 37 | fmt.Println("connect failed, err:", err) 38 | return 39 | } 40 | 41 | fmt.Println("connect succ") 42 | defer cli.Close() 43 | 44 | now := time.Now().Unix() 45 | var SecProductInfoConfArr []SecProductInfoConf 46 | SecProductInfoConfArr = append( 47 | SecProductInfoConfArr, 48 | SecProductInfoConf{ 49 | ProductId: 1001, 50 | StartTime: now - 60, 51 | EndTime: now + 3600, 52 | Status: 0, 53 | Total: 10, 54 | OnePersonBuyLimit:1, 55 | SoldMaxLimit:10000, 56 | BuyRate: 0.5, 57 | }, 58 | ) 59 | SecProductInfoConfArr = append( 60 | SecProductInfoConfArr, 61 | SecProductInfoConf{ 62 | ProductId: 1002, 63 | StartTime: now - 60, 64 | EndTime: now + 3600, 65 | Status: 0, 66 | Total: 10, 67 | OnePersonBuyLimit:1, 68 | SoldMaxLimit:10000, 69 | BuyRate: 0.5, 70 | }, 71 | ) 72 | 73 | data, err := json.Marshal(SecProductInfoConfArr) 74 | if err != nil { 75 | fmt.Println("json failed, ", err) 76 | return 77 | } 78 | 79 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) 80 | //cli.Delete(ctx, EtcdKey) 81 | //return 82 | _, err = cli.Put(ctx, EtcdKey, string(data)) 83 | cancel() 84 | if err != nil { 85 | fmt.Println("put failed, err:", err) 86 | return 87 | } 88 | 89 | ctx, cancel = context.WithTimeout(context.Background(), time.Second) 90 | resp, err := cli.Get(ctx, EtcdKey) 91 | cancel() 92 | if err != nil { 93 | fmt.Println("get failed, err:", err) 94 | return 95 | } 96 | for _, ev := range resp.Kvs { 97 | fmt.Printf("%s : %s\n", ev.Key, ev.Value) 98 | } 99 | } 100 | 101 | func main() { 102 | SetLogConfToEtcd() 103 | } 104 | -------------------------------------------------------------------------------- /logcollection/web_admin/views/layout/layout.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 首页 7 | 8 | 9 | 10 |
11 |
12 | 13 | 16 | 29 |
30 | 31 |
32 |
33 | 49 |
50 |
51 | 52 |
53 | 54 |
55 | {{.LayoutContent}} 56 |
57 |
58 | 59 | 62 |
63 | 64 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /logcollection/web_admin/views/app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 首页 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | {{range .applist}} 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | {{end}} 35 | 36 |
项目ID项目名称项目类型创建时间部署路径操作
{{.AppId}}{{.AppName}}{{.AppType}}{{.CreateTime}}{{.DevelopPath}}
37 |
38 | 39 | 40 | 41 | 45 | 46 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /seckill/SecLayer/service/product.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "github.com/astaxie/beego/logs" 7 | "go.etcd.io/etcd/mvcc/mvccpb" 8 | "time" 9 | ) 10 | 11 | func loadProductFromEtcd(conf *SecLayerConf)(err error){ 12 | 13 | logs.Debug("start get product from etcd") 14 | ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*10) 15 | defer cancelFunc() 16 | 17 | resp,err := secLayerContext.etcdClient.Get(ctx,conf.EtcdConfig.EtcdSecProductKey) 18 | if err!= nil{ 19 | logs.Debug("get [%s] from etcd failed, err: %v",conf.EtcdConfig.EtcdSecProductKey,err) 20 | return 21 | } 22 | 23 | logs.Debug("get from etcd success, resp: %v",resp) 24 | var secProductInfo []SecProductInfoConf 25 | for k,v := range resp.Kvs{ 26 | logs.Debug("key[%v] value[%v]",k,v) 27 | err = json.Unmarshal(v.Value,&secProductInfo) 28 | if err!= nil { 29 | logs.Error("Unmarshal sec product info failed, err: %v",err) 30 | return 31 | } 32 | 33 | logs.Debug("sec info conf is [%v]",secProductInfo) 34 | } 35 | 36 | updateSecProductInfo(conf,secProductInfo) 37 | logs.Debug("update product info success, data:%v",err) 38 | 39 | initSecProductWatcher(conf) 40 | logs.Debug("init etcd watcher success") 41 | return 42 | } 43 | 44 | 45 | func updateSecProductInfo(conf *SecLayerConf,secProductIndo []SecProductInfoConf){ 46 | tmp := make(map[int]*SecProductInfoConf,1024) 47 | for _,v :=range secProductIndo{ 48 | productInfo := v 49 | productInfo.secLimit = &SecLimit{} 50 | tmp[v.ProductId] = &productInfo 51 | } 52 | 53 | secLayerContext.RWSecProductLock.Lock() 54 | conf.SecProductInfoMap = tmp 55 | secLayerContext.RWSecProductLock.Unlock() 56 | } 57 | 58 | func initSecProductWatcher(conf *SecLayerConf){ 59 | go watchSecProductKey(conf) 60 | } 61 | 62 | func watchSecProductKey(conf *SecLayerConf){ 63 | 64 | key := conf.EtcdConfig.EtcdSecProductKey 65 | logs.Debug("begin watch key: %s",key) 66 | var err error 67 | for{ 68 | rch := secLayerContext.etcdClient.Watch(context.Background(),key) 69 | var secProductInfo []SecProductInfoConf 70 | var getConfSucc = true 71 | 72 | for wresp := range rch{ 73 | for _,ev := range wresp.Events{ 74 | if ev.Type == mvccpb.DELETE{ 75 | logs.Warn("key[%s] 's config deleted ",key) 76 | continue 77 | } 78 | 79 | if ev.Type ==mvccpb.PUT && string(ev.Kv.Key) == key{ 80 | err = json.Unmarshal(ev.Kv.Value,&secProductInfo) 81 | if err !=nil{ 82 | logs.Error("key [%s] ,Unmarshal [%s] ,err: %v",err) 83 | getConfSucc = false 84 | continue 85 | } 86 | } 87 | 88 | logs.Debug("get config from etcd, %s %q: %q\n",ev.Type,ev.Kv.Key,ev.Kv.Value) 89 | } 90 | 91 | if getConfSucc { 92 | logs.Debug("get config from etcd success, %v",secProductInfo) 93 | updateSecProductInfo(conf,secProductInfo) 94 | } 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /seckill/SecProxy/controller/skill.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego" 6 | "github.com/astaxie/beego/logs" 7 | "golang-awesome/seckill/SecProxy/service" 8 | "strings" 9 | "time" 10 | ) 11 | 12 | type SkillController struct { 13 | beego.Controller 14 | } 15 | 16 | func (p *SkillController) SecKill(){ 17 | 18 | productId,err := p.GetInt("product_id") 19 | result := make(map[string]interface{}) 20 | result["code"] = 0 21 | result["message"] = "success" 22 | 23 | defer func() { 24 | p.Data["json"] =result 25 | p.ServeJSON() 26 | }() 27 | 28 | if err !=nil{ 29 | result["code"] =service.ErrInvalidRequest 30 | result["message"] = "invalid product_id" 31 | return 32 | } 33 | 34 | source :=p.GetString("src") 35 | authCode := p.GetString("authcode") 36 | secTime :=p.GetString("time") 37 | nance := p.GetString("nance") 38 | 39 | secRequest := service.NewSecRequest() 40 | secRequest.AuthCode =authCode 41 | secRequest.Nance = nance 42 | secRequest.ProductId = productId 43 | secRequest.SecTime = secTime 44 | secRequest.Source =source 45 | secRequest.UserAuthSign = p.Ctx.GetCookie("userAuthSign") 46 | secRequest.UserId,_ = p.GetInt("user_id") 47 | secRequest.AccessTime = time.Now() 48 | if len(p.Ctx.Request.RemoteAddr) >0{ 49 | secRequest.ClientAddr = strings.Split(p.Ctx.Request.RemoteAddr,":")[0] 50 | } 51 | secRequest.ClientReferer = p.Ctx.Request.Referer() 52 | secRequest.CloseNotify = p.Ctx.ResponseWriter.CloseNotify() 53 | 54 | logs.Debug("client request: [%v]",secRequest) 55 | if err !=nil{ 56 | result["code"] = service.ErrInvalidRequest 57 | result["message"] = fmt.Sprintf("invalid cookokie : userid") 58 | return 59 | } 60 | 61 | data,code,err := service.SecKill(secRequest) 62 | if err != nil { 63 | result["code"] = code 64 | result["message"] = err.Error() 65 | return 66 | } 67 | result["data"] = data 68 | result["code"] = code 69 | return 70 | } 71 | 72 | func (p *SkillController) SecInfo(){ 73 | 74 | productId ,err := p.GetInt("product_id") 75 | result := make(map[string]interface{}) 76 | logs.Debug("product_id:%d",productId) 77 | 78 | result["code"] = 0 79 | result["message"] = "success" 80 | 81 | defer func(){ 82 | p.Data["json"] = result 83 | p.ServeJSON() 84 | }() 85 | 86 | if err != nil { 87 | data, code, err := service.SecInfoList() 88 | if err != nil { 89 | result["code"] = code 90 | result["message"] = err.Error() 91 | 92 | logs.Error("invalid request, get product_id failed, err:%v",err) 93 | return 94 | } 95 | result["code"] = code 96 | result["data"] = data 97 | }else{ 98 | data, code, err := service.SecInfo(productId) 99 | if err != nil { 100 | result["code"] = code 101 | result["message"] = err.Error() 102 | 103 | logs.Error("invalid request,get product_id falied, err :%v",err) 104 | return 105 | } 106 | 107 | result["data"] = data 108 | result["code"] = code 109 | } 110 | } -------------------------------------------------------------------------------- /logcollection/web_admin/models/log.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "github.com/astaxie/beego/logs" 7 | etcdclient "go.etcd.io/etcd/clientv3" 8 | "golang-awesome/logcollection/logagent/tail" 9 | "time" 10 | ) 11 | 12 | var( 13 | etcdClient *etcdclient.Client 14 | ) 15 | type LogInfo struct { 16 | AppId int `db:"app_id" json:"app_id"` 17 | AppName string `db:"app_name"` 18 | LogId int `db:"log_id"` 19 | Status int `db:"status"` 20 | CreateTime string `db:"create_time"` 21 | LogPath string `db:"log_path"` 22 | Topic string `db:"topic"` 23 | } 24 | 25 | func InitEtcd(client *etcdclient.Client) { 26 | etcdClient = client 27 | } 28 | 29 | 30 | func GetAllLogInfo() (loglist []LogInfo, err error) { 31 | err = Db.Select(&loglist, 32 | "select a.app_id, b.app_name, a.create_time, a.topic, a.log_id, a.status, a.log_path from tbl_log_info a, tbl_app_info b where a.app_id=b.app_id") 33 | if err != nil { 34 | logs.Warn("Get All App Info failed, err:%v", err) 35 | return 36 | } 37 | return 38 | } 39 | 40 | func CreateLog(info *LogInfo) (err error){ 41 | tx, err := Db.Begin() 42 | 43 | if err != nil{ 44 | logs.Warn("create log failed,err %v",err) 45 | return 46 | } 47 | 48 | defer func(){ 49 | if err != nil { 50 | tx.Rollback() 51 | return 52 | } 53 | tx.Commit() 54 | }() 55 | 56 | var appList []AppInfo 57 | err = Db.Select(&appList, "select app_id,app_name from tbl_app_info where app_name = ?", info.AppName) 58 | 59 | if err != nil || len(appList) == 0{ 60 | logs.Warn("select appInfo failed, err:%v",err) 61 | return 62 | } 63 | info.AppId = appList[0].AppId 64 | info.AppName = appList[0].AppName 65 | logs.Debug(info.AppId) 66 | result, err := tx.Exec("insert into tbl_log_info (app_id,app_name,log_path,topic) values (?,?,?,?)", 67 | info.AppId, info.AppName,info.LogPath, info.Topic) 68 | 69 | if err != nil { 70 | logs.Warn("insert into tbl_log_info falied, err %v",err) 71 | return 72 | } 73 | 74 | _, err = result.LastInsertId() 75 | 76 | if err != nil{ 77 | logs.Warn("get last insert id failes, err %v",err) 78 | return 79 | } 80 | 81 | return 82 | } 83 | 84 | func SetLogConfToEtcd(etcdKey string,info *LogInfo)(err error){ 85 | 86 | var logConfArr []tail.CollectConf 87 | 88 | logConfArr = append( 89 | logConfArr, 90 | tail.CollectConf{ 91 | LogPath:info.LogPath, 92 | Topic:info.Topic, 93 | }, 94 | ) 95 | logs.Warn("etcdctl:",etcdKey) 96 | bytes, err := json.Marshal(logConfArr) 97 | if err != nil { 98 | logs.Warn("marshal log conf failed, err%v",err) 99 | return 100 | } 101 | 102 | ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second) 103 | _, err = etcdClient.Put(ctx, etcdKey, string(bytes)) 104 | cancelFunc() 105 | 106 | if err != nil { 107 | logs.Warn("put log conf to etcd failed, err%v",err) 108 | return 109 | } 110 | 111 | logs.Debug("put etcd success, data:%v",string(bytes)) 112 | 113 | return 114 | } -------------------------------------------------------------------------------- /logcollection/logagent/main/etcd.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "github.com/astaxie/beego/logs" 7 | "go.etcd.io/etcd/clientv3" 8 | "go.etcd.io/etcd/mvcc/mvccpb" 9 | "golang-awesome/logcollection/logagent/tail" 10 | "time" 11 | ) 12 | 13 | type EtcdClient struct { 14 | client *clientv3.Client 15 | keys []string 16 | } 17 | 18 | var ( 19 | etcdClient *EtcdClient 20 | ) 21 | 22 | func initEtcd(addr,key string)(collectConf tail.CollectConf,err error){ 23 | client, err := clientv3.New(clientv3.Config{ 24 | Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, 25 | DialTimeout: 5 * time.Second, 26 | }) 27 | 28 | if err != nil { 29 | logs.Error("connect etcd failed, err:",err) 30 | 31 | } 32 | 33 | etcdClient =&EtcdClient{ 34 | client:client, 35 | } 36 | 37 | //if strings.HasSuffix(key,"/") == false { 38 | // key = key + "/" 39 | //} 40 | 41 | //for _,ip := range localIPArray{ 42 | //etcdKey := fmt.Sprintf("%s%s", key, ip) 43 | //etcdKey := fmt.Sprintf("%s", key) 44 | etcdClient.keys = append(etcdClient.keys, key) 45 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) 46 | resp, err := client.Get(ctx, key) 47 | if err != nil { 48 | logs.Error("client get from etcd failed, err:%v", err) 49 | } 50 | cancel() 51 | logs.Debug("resps from etcd:%v", resp.Kvs) 52 | for _, v := range resp.Kvs { 53 | if string(v.Key) == key { 54 | logs.Debug("v.Key:",v.Key) 55 | logs.Debug("v.Value:",v.Value) 56 | err = json.Unmarshal(v.Value, &collectConf) 57 | if err != nil { 58 | logs.Error("unmarshal failed, err:%v", err) 59 | continue 60 | } 61 | 62 | logs.Debug("log config is %v", collectConf) 63 | } 64 | } 65 | //} 66 | 67 | initEtcdWatcher() 68 | return 69 | } 70 | 71 | func initEtcdWatcher() { 72 | 73 | for _, key := range etcdClient.keys { 74 | logs.Debug("etcd key :" ,key) 75 | go watchKey(key) 76 | } 77 | } 78 | 79 | func watchKey(key string) { 80 | 81 | cli, err := clientv3.New(clientv3.Config{ 82 | Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, 83 | DialTimeout: 5 * time.Second, 84 | }) 85 | if err != nil { 86 | logs.Error("connect etcd failed, err:", err) 87 | return 88 | } 89 | 90 | logs.Debug("begin watch key:%s", key) 91 | for { 92 | rch := cli.Watch(context.Background(), key) 93 | var collectConf []tail.CollectConf 94 | var getConfSucc = true 95 | for wresp := range rch { 96 | for _, ev := range wresp.Events { 97 | if ev.Type == mvccpb.DELETE { 98 | logs.Warn("key[%s] 's config deleted", key) 99 | continue 100 | } 101 | 102 | if ev.Type == mvccpb.PUT && string(ev.Kv.Key) == key { 103 | err = json.Unmarshal(ev.Kv.Value, &collectConf) 104 | if err != nil { 105 | logs.Error("key [%s], Unmarshal[%s], err:%v ", err) 106 | getConfSucc = false 107 | continue 108 | } 109 | } 110 | logs.Debug("get config from etcd, %s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value) 111 | } 112 | 113 | if getConfSucc { 114 | logs.Debug("get config from etcd succ, %v", collectConf) 115 | tail.UpdateConfig(collectConf) 116 | } 117 | } 118 | 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /crawler/zhenai/parser/profile.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "golang-awesome/crawler/engine" 5 | "golang-awesome/crawler/model" 6 | "regexp" 7 | ) 8 | //
离异
9 | //var ageRe = regexp.MustCompile(`年龄:(\d+)岁`) 10 | //var heightRe = regexp.MustCompile(`身高:(\d+)CM`) 11 | //var incomeRe = regexp.MustCompile(`月收入:([^<]+)`) 12 | //var weightRe = regexp.MustCompile(`体重:([^<]+)KG`) //体重:-- 13 | //var genderRe = regexp.MustCompile(`性别:([^<]+)`) 14 | //var xinzuoRe = regexp.MustCompile(`星座:([^<]+)`) 15 | //var marriageRe = regexp.MustCompile(`婚况:([^<]+)`) 16 | //var educationRe = regexp.MustCompile(`学历:([^<]+)`) 17 | //var occupationRe = regexp.MustCompile(`职业: ([^<]+)`) 18 | //var hokouRe = regexp.MustCompile(`籍贯:([^<]+)`) 19 | //var houseRe = regexp.MustCompile(`住房条件:([^<]+)`) 20 | //var carRe = regexp.MustCompile(`是否购车:([^<]+)`) 21 | //var IdRe = regexp.MustCompile(`
ID:([^<]+)
`) 22 | var Re = regexp.MustCompile(`
([^<]+)
`) 23 | 24 | 25 | func ParseProfile(contents []byte, url, name string) engine.ParserResult{ 26 | profile := &model.Profile{} 27 | profile.Name = name 28 | //idsubmatch := IdRe.FindSubmatch(contents) 29 | //profile.Id = string(idsubmatch[1]) 30 | submatch := Re.FindAllSubmatch(contents, -1) 31 | if len(submatch) > 0{ 32 | profile.Marriage = string(submatch[0][1]) 33 | profile.Age = string(submatch[1][1]) 34 | profile.Xingzuo = string(submatch[2][1]) 35 | profile.Height = string(submatch[3][1]) 36 | profile.Weight = string(submatch[4][1]) 37 | profile.Hukou = string(submatch[5][1]) 38 | profile.Income = string(submatch[6][1]) 39 | profile.Education = string(submatch[len(submatch)-1][1]) 40 | } 41 | 42 | 43 | item := engine.Item{ 44 | Url:url, 45 | Payload:profile, 46 | Type:"zhenai", 47 | Id:profile.Id, 48 | } 49 | rs := engine.ParserResult{} 50 | rs.Items = []engine.Item{item} 51 | // 取本页面内,猜你喜欢的的 52 | //var guessRe = regexp.MustCompile(`href="(http://album.zhenai.com/u/\w+)"[^>]*>([^<]+)`) 53 | //ms := guessRe.FindAllSubmatch(contents, -1) 54 | //for _, m := range ms { 55 | // rs.Requests = append(rs.Requests, engine.Request{ 56 | // Url: string(m[1]), 57 | // Parse: NewProfileParser(string(m[2])), 58 | // }) 59 | //} 60 | return rs 61 | } 62 | 63 | //func extractString(contents []byte, re *regexp.Regexp) string{ 64 | // match := re.FindSubmatch(contents) 65 | // if len(match) >= 2 { 66 | // return string(match[1]) 67 | // }else { 68 | // return "" 69 | // 70 | // } 71 | //} 72 | 73 | type ProfileParser struct{ 74 | userName string 75 | } 76 | 77 | func NewProfileParser(userName string) *ProfileParser { 78 | return &ProfileParser{userName: 79 | userName} 80 | } 81 | 82 | func (p *ProfileParser) Parse(contents []byte, url string) engine.ParserResult { 83 | return ParseProfile(contents, url, p.userName) 84 | } 85 | 86 | func (p *ProfileParser) Serialize() (name string, args interface{}) { 87 | return "ProfileParser", p.userName 88 | } 89 | 90 | -------------------------------------------------------------------------------- /logcollection/logagent/tail/tail.go: -------------------------------------------------------------------------------- 1 | package tail 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego/logs" 6 | "github.com/hpcloud/tail" 7 | "sync" 8 | "time" 9 | ) 10 | 11 | const ( 12 | StatusNormal = 1 13 | StatusDelete = 2 14 | ) 15 | 16 | type CollectConf struct { 17 | LogPath string `json:"logpath"` 18 | Topic string `json:"topic"` 19 | } 20 | 21 | type TailObj struct { 22 | tail *tail.Tail 23 | conf CollectConf 24 | status int 25 | exitChan chan int 26 | } 27 | 28 | type TextMsg struct { 29 | Msg string 30 | Topic string 31 | } 32 | type TailObjMgr struct { 33 | tailObjs []*TailObj 34 | msgChan chan *TextMsg 35 | lock sync.Mutex 36 | } 37 | 38 | var ( 39 | tailObjMgr *TailObjMgr 40 | ) 41 | 42 | func GetOneLine() (msg *TextMsg) { 43 | msg = <-tailObjMgr.msgChan 44 | return 45 | } 46 | 47 | func UpdateConfig(confs []CollectConf) (err error) { 48 | tailObjMgr.lock.Lock() 49 | defer tailObjMgr.lock.Unlock() 50 | 51 | for _, oneConf := range confs { 52 | var isRunning = false 53 | for _, obj := range tailObjMgr.tailObjs { 54 | if oneConf.LogPath == obj.conf.LogPath { 55 | isRunning = true 56 | break 57 | } 58 | } 59 | if isRunning { 60 | continue 61 | } 62 | 63 | createNewTask(oneConf) 64 | } 65 | 66 | var tailObjs []*TailObj 67 | for _, obj := range tailObjMgr.tailObjs { 68 | obj.status = StatusDelete 69 | for _, oneConf := range confs { 70 | if oneConf.LogPath == obj.conf.LogPath { 71 | obj.status = StatusNormal 72 | break 73 | } 74 | } 75 | if obj.status == StatusDelete { 76 | obj.exitChan <- 1 77 | continue 78 | } 79 | tailObjs = append(tailObjs, obj) 80 | } 81 | tailObjMgr.tailObjs = tailObjs 82 | return 83 | } 84 | 85 | func createNewTask(conf CollectConf) { 86 | 87 | obj := &TailObj{ 88 | conf: conf, 89 | exitChan: make(chan int, 1), 90 | } 91 | 92 | file, e := tail.TailFile(conf.LogPath, tail.Config{ 93 | ReOpen: true, 94 | Follow: true, 95 | //Location: &tail.SeekInfo{Offset:0,Whence:2,}, 96 | MustExist: false, 97 | Poll: true, 98 | }) 99 | 100 | if e != nil { 101 | logs.Error("collect filename[%s] failed ,err:%v", e) 102 | return 103 | } 104 | obj.tail = file 105 | tailObjMgr.tailObjs = append(tailObjMgr.tailObjs, obj) 106 | 107 | go readFromTail(obj) 108 | } 109 | 110 | func InitTail(conf []CollectConf, chanSize int) (err error) { 111 | 112 | if len(conf) == 0 { 113 | err = fmt.Errorf("invalid config for log collect: conf:%v", conf) 114 | return 115 | } 116 | 117 | tailObjMgr = &TailObjMgr{ 118 | msgChan: make(chan *TextMsg, chanSize), 119 | } 120 | 121 | for _, v := range conf { 122 | obj := &TailObj{ 123 | conf: v, 124 | } 125 | 126 | tails, errTail := tail.TailFile(v.LogPath, tail.Config{ 127 | ReOpen: true, 128 | Follow: true, 129 | //Location: &tail.SeekInfo{Offset:0,Whence:2,}, 130 | MustExist: false, 131 | Poll: true, 132 | }) 133 | 134 | if errTail != nil { 135 | err = errTail 136 | return 137 | } 138 | 139 | obj.tail = tails 140 | 141 | tailObjMgr.tailObjs = append(tailObjMgr.tailObjs, obj) 142 | 143 | go readFromTail(obj) 144 | } 145 | return 146 | } 147 | 148 | func readFromTail(tailObj *TailObj) { 149 | for { 150 | lines, ok := <-tailObj.tail.Lines 151 | if !ok { 152 | logs.Warn("tail file close reopen ,filename:%s\n", tailObj.tail.Filename) 153 | time.Sleep(100 * time.Millisecond) 154 | continue 155 | } 156 | 157 | textMsg := &TextMsg{ 158 | Msg: lines.Text, 159 | Topic: tailObj.conf.Topic, 160 | } 161 | 162 | tailObjMgr.msgChan <- textMsg 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /goroutine/chart/chat_server/main/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/binary" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "net" 9 | ) 10 | 11 | type Client struct { 12 | conn net.Conn 13 | buf [8192]byte 14 | } 15 | 16 | func (p *Client) readPackage() (msg Message, err error) { 17 | 18 | n, err := p.conn.Read(p.buf[0:4]) 19 | if n != 4 { 20 | err = errors.New("read header failed") 21 | return 22 | } 23 | fmt.Println("read package:", p.buf[0:4]) 24 | 25 | var packLen uint32 26 | packLen = binary.BigEndian.Uint32(p.buf[0:4]) 27 | 28 | fmt.Printf("receive len:%d", packLen) 29 | n, err = p.conn.Read(p.buf[0:packLen]) 30 | if n != int(packLen) { 31 | err = errors.New("read body failed") 32 | return 33 | } 34 | 35 | fmt.Printf("receive data:%s\n", string(p.buf[0:packLen])) 36 | err = json.Unmarshal(p.buf[0:packLen], &msg) 37 | if err != nil { 38 | fmt.Println("unmarshal failed, err:", err) 39 | } 40 | return 41 | } 42 | 43 | func (p *Client) writePackage(data []byte) (err error) { 44 | 45 | packLen := uint32(len(data)) 46 | 47 | binary.BigEndian.PutUint32(p.buf[0:4], packLen) 48 | n, err := p.conn.Write(p.buf[0:4]) 49 | if err != nil { 50 | fmt.Println("write data failed") 51 | return 52 | } 53 | 54 | n, err = p.conn.Write(data) 55 | if err != nil { 56 | fmt.Println("write data failed") 57 | return 58 | } 59 | 60 | if n != int(packLen) { 61 | fmt.Println("write data not finished") 62 | err = errors.New("write data not fninshed") 63 | return 64 | } 65 | 66 | return 67 | } 68 | 69 | func (p *Client) Process() (err error) { 70 | 71 | for { 72 | var msg Message 73 | msg, err = p.readPackage() 74 | if err != nil { 75 | return err 76 | } 77 | 78 | err = p.processMsg(msg) 79 | if err != nil { 80 | return 81 | } 82 | } 83 | } 84 | 85 | func (p *Client) processMsg(msg Message) (err error) { 86 | 87 | switch msg.Cmd { 88 | case UserLogin: 89 | err = p.login(msg) 90 | case UserRegister: 91 | err = p.register(msg) 92 | default: 93 | err = errors.New("unsupport message") 94 | return 95 | } 96 | return 97 | } 98 | 99 | func (p *Client) loginResp(err error) { 100 | var respMsg Message 101 | respMsg.Cmd = UserLoginRes 102 | 103 | var loginRes LoginCmdRes 104 | loginRes.Code = 200 105 | 106 | if err != nil { 107 | loginRes.Code = 500 108 | loginRes.Error = fmt.Sprintf("%v", err) 109 | } 110 | 111 | data, err := json.Marshal(loginRes) 112 | if err != nil { 113 | fmt.Println("marshal failed, ", err) 114 | return 115 | } 116 | 117 | respMsg.Data = string(data) 118 | data, err = json.Marshal(respMsg) 119 | if err != nil { 120 | fmt.Println("marshal failed, ", err) 121 | return 122 | } 123 | err = p.writePackage(data) 124 | if err != nil { 125 | fmt.Println("send failed, ", err) 126 | return 127 | } 128 | } 129 | 130 | func (p *Client) login(msg Message) (err error) { 131 | defer func() { 132 | p.loginResp(err) 133 | }() 134 | 135 | fmt.Printf("recv user login request, data:%v", msg) 136 | var cmd LoginCmd 137 | err = json.Unmarshal([]byte(msg.Data), &cmd) 138 | if err != nil { 139 | return 140 | } 141 | 142 | _, err = mgr.Login(cmd.Id, cmd.Passwd) 143 | if err != nil { 144 | return 145 | } 146 | 147 | return 148 | } 149 | 150 | func (p *Client) register(msg Message) (err error) { 151 | var cmd RegisterCmd 152 | err = json.Unmarshal([]byte(msg.Data), &cmd) 153 | if err != nil { 154 | return 155 | } 156 | 157 | err = mgr.Register(&cmd.User) 158 | if err != nil { 159 | return 160 | } 161 | 162 | return 163 | } 164 | -------------------------------------------------------------------------------- /seckill/SecProxy/service/service.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego/logs" 6 | "time" 7 | ) 8 | 9 | var ( 10 | secKillConf *SecKillConf 11 | ) 12 | 13 | func NewSecRequest() (secRequest *SecRequest) { 14 | secRequest = &SecRequest{ 15 | ResultChan: make(chan *SecResult, 1), 16 | } 17 | return 18 | } 19 | 20 | func SecInfoList() (data []map[string]interface{}, code int, err error) { 21 | secKillConf.RWBlackLock.RLock() 22 | defer secKillConf.RWBlackLock.RUnlock() 23 | 24 | for _, v := range secKillConf.SecProductInfoMap { 25 | item, _, err := SecInfoById(v.ProductId) 26 | if err != nil { 27 | logs.Error("get product_id[%d] failed, err:%v", err) 28 | continue 29 | } 30 | 31 | logs.Debug("get product[%d], result[%v], all[%v] v[%v]", v.ProductId, item, secKillConf.SecProductInfoMap, v) 32 | data = append(data, item) 33 | } 34 | 35 | return 36 | } 37 | 38 | func SecInfoById(productId int) (data map[string]interface{}, code int, err error) { 39 | secKillConf.RWBlackLock.RLock() 40 | defer secKillConf.RWBlackLock.RUnlock() 41 | 42 | v, ok := secKillConf.SecProductInfoMap[productId] 43 | if !ok { 44 | code = ErrNotFoundProductId 45 | err = fmt.Errorf("not found product id: %d", productId) 46 | return 47 | } 48 | 49 | start := false 50 | end := false 51 | status := "success" 52 | 53 | now := time.Now().Unix() 54 | if now-v.StartTime < 0 { 55 | start = false 56 | end = false 57 | status = "sec kill is not start" 58 | code = ErrActiveNotStart 59 | } 60 | 61 | if now-v.StartTime > 0 { 62 | start = true 63 | } 64 | 65 | if now-v.EndTime > 0 { 66 | start = false 67 | end = true 68 | status = "sec kill is already end" 69 | code = ErrActiveAlreadyEnd 70 | } 71 | 72 | if v.Status == ProductStatusForceSaleOut || v.Status == ProductStatusSaleOut { 73 | start = false 74 | end = true 75 | status = "product is sale out" 76 | code = ErrActiveSaleOut 77 | } 78 | 79 | data = make(map[string]interface{}) 80 | data["product_id"] = productId 81 | data["start"] = start 82 | data["end"] = end 83 | data["status"] = status 84 | 85 | return 86 | } 87 | 88 | func SecInfo(productId int) (data []map[string]interface{}, code int, err error) { 89 | secKillConf.RWSecProductLock.RLock() 90 | defer secKillConf.RWSecProductLock.RUnlock() 91 | 92 | item, code, err := SecInfoById(productId) 93 | 94 | if err != nil { 95 | return 96 | } 97 | data = append(data, item) 98 | return 99 | } 100 | 101 | func SecKill(req *SecRequest) (data map[string]interface{}, code int, err error) { 102 | 103 | //secKillConf.RWSecProductLock.RLock() 104 | //defer secKillConf.RWSecProductLock.RUnlock() 105 | 106 | //err = antiSpam(req) 107 | //if err != nil { 108 | // code = ErrUserServiceBusy 109 | // logs.Warn("userId[%d] invalid, check failed, req[%v]", req.UserId, req) 110 | // return 111 | //} 112 | 113 | data, code, err = SecInfoById(req.ProductId) 114 | if code != 0 { 115 | logs.Warn("userId[%d] secInfoBy id failed, req[%v]", req.UserId, req) 116 | return 117 | } 118 | 119 | userKey := fmt.Sprintf("%s_%s", req.UserId, req.ProductId) 120 | secKillConf.RWSecProductLock.RLock() 121 | secKillConf.UserConnMap[userKey] = req.ResultChan 122 | secKillConf.RWSecProductLock.RUnlock() 123 | 124 | secKillConf.SecReqChan <- req 125 | ticker := time.NewTicker(time.Second * 10) 126 | 127 | defer func() { 128 | ticker.Stop() 129 | secKillConf.UserConnMapLock.Lock() 130 | delete(secKillConf.UserConnMap, userKey) 131 | secKillConf.UserConnMapLock.Unlock() 132 | }() 133 | 134 | select { 135 | case <-ticker.C: 136 | code = ErrProcessTimeout 137 | err = fmt.Errorf("request timeout") 138 | return 139 | 140 | case <-req.CloseNotify: 141 | code = ErrClientClosed 142 | err = fmt.Errorf("client already closed") 143 | return 144 | case result := <-req.ResultChan: 145 | code = result.Code 146 | data["product_id"] = result.ProductId 147 | data["token"] = result.Token 148 | data["user_id"] = result.UserId 149 | return 150 | } 151 | return 152 | } 153 | -------------------------------------------------------------------------------- /video_server/templates/home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 105 | 110 | 111 | 112 | 113 | 114 |
115 | Home 116 | {{.Name}} 117 | Help 118 |
119 | 120 |
121 |

Welcome to MOVIEDASH

122 |
123 | 124 |
125 |
126 |

Register

127 |
128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 |
136 |

By creating an account you agree to our Terms & Privacy.

137 | 138 | 139 |
140 | 141 | 144 |
145 | 146 | 167 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /seckill/SecProxy/load/init.go: -------------------------------------------------------------------------------- 1 | package load 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "github.com/astaxie/beego/logs" 8 | 9 | etcd "go.etcd.io/etcd/clientv3" 10 | "go.etcd.io/etcd/mvcc/mvccpb" 11 | "golang-awesome/seckill/SecProxy/service" 12 | "time" 13 | ) 14 | 15 | var ( 16 | //redisClient *redis.Client 17 | //redisPool *redis.Pool 18 | etcdClient *etcd.Client 19 | ) 20 | 21 | //func initRedis()(err error){ 22 | // redisClient = redis.NewClient(&redis.Options{ 23 | // Addr: secKillConf.RedisConf.RedisAddr, 24 | // Password: "123456", // no password set 25 | // DB: 0, // use default DB 26 | // }) 27 | // 28 | // pong, err := redisClient.Ping().Result() 29 | // 30 | // fmt.Println(pong, err) 31 | // 32 | // if err != nil { 33 | // logs.Error("ping redis failed,err :%v",err) 34 | // return 35 | // } 36 | // 37 | // return 38 | //} 39 | 40 | //func initRedis() (err error) { 41 | // redisPool = &redis.Pool{ 42 | // MaxIdle: secKillConf.RedisConf.RedisMaxIdle, 43 | // MaxActive: secKillConf.RedisConf.RedisMaxActive, 44 | // IdleTimeout: time.Duration(secKillConf.RedisConf.RedisIdleTimeout) * time.Second, 45 | // Dial: func() (redis.Conn, error) { 46 | // redis.Dial("tcp", secKillConf.RedisConf.RedisAddr) 47 | // c, err := redis.Dial("tcp", secKillConf.RedisConf.RedisAddr) 48 | // if err != nil { 49 | // return nil, err 50 | // } 51 | // if _, err := c.Do("AUTH", secKillConf.RedisConf.RedisPwd); err != nil { 52 | // c.Close() 53 | // return nil, err 54 | // } 55 | // return c, err 56 | // }, 57 | // } 58 | // 59 | // conn := redisPool.Get() 60 | // defer conn.Close() 61 | // 62 | // _, err = conn.Do("ping") 63 | // if err != nil { 64 | // logs.Error("ping redis failed, err:%v", err) 65 | // return 66 | // } 67 | // 68 | // return 69 | //} 70 | 71 | 72 | func initEtcd()(err error){ 73 | logs.Debug("etcd timeout: %v ",time.Duration(secKillConf.EtcdConf.Timeout) * time.Second) 74 | client, err := etcd.New(etcd.Config{ 75 | Endpoints: []string{secKillConf.EtcdConf.EtcdAddr}, 76 | DialTimeout: time.Duration(secKillConf.EtcdConf.Timeout) * time.Millisecond, 77 | }) 78 | 79 | if err != nil { 80 | logs.Error("connect etcd failed ,err:", err) 81 | return 82 | } 83 | 84 | etcdClient = client 85 | return 86 | } 87 | 88 | func convertLogLevel (level string) int { 89 | switch level{ 90 | case "debug": 91 | return logs.LevelDebug 92 | case "warn": 93 | return logs.LevelWarn 94 | case "info": 95 | return logs.LevelInfo 96 | case "trace": 97 | return logs.LevelTrace 98 | default: 99 | return logs.LevelDebug 100 | } 101 | } 102 | 103 | 104 | func initLogger() (err error){ 105 | config := make(map[string]interface{}) 106 | config["filename"] = secKillConf.LogPath 107 | config["level"] = convertLogLevel(secKillConf.LogLevel) 108 | 109 | bytes, err := json.Marshal(config) 110 | if err != nil { 111 | fmt.Println(" marshal failed,err: ",err) 112 | return 113 | } 114 | 115 | logs.SetLogger(logs.AdapterFile,string(bytes)) 116 | logs.SetLogger(logs.AdapterConsole,string(bytes)) 117 | 118 | return 119 | } 120 | 121 | 122 | func loadSecConf() (err error){ 123 | response, err := etcdClient.Get(context.Background(), secKillConf.EtcdConf.EtcdSecProductKey) 124 | if err != nil { 125 | logs.Debug("get [%s] from etcd failed, err:%v ",secKillConf.EtcdConf.EtcdSecProductKey,err) 126 | return 127 | } 128 | var secProductInfo []service.SecProductInfoConf 129 | for k,v := range response.Kvs{ 130 | logs.Debug("key[%s] value[%s]",k,v) 131 | err = json.Unmarshal(v.Value, &secProductInfo) 132 | if err != nil { 133 | logs.Debug("Unmarshal sec producr info failed, err:%v ",err) 134 | return 135 | } 136 | logs.Debug("sec info conf is [%v]",secProductInfo) 137 | } 138 | updateSecProductInfo(secProductInfo) 139 | return 140 | } 141 | 142 | func InitSecKill()(err error){ 143 | err = initLogger() 144 | if err != nil{ 145 | fmt.Println("load logger failed,err: %v",err) 146 | return 147 | } 148 | 149 | //err = initRedis() 150 | //if err != nil{ 151 | // fmt.Println("load redis failed,err: %v",err) 152 | // return 153 | //} 154 | 155 | err = initEtcd() 156 | if err != nil{ 157 | fmt.Println("load etcd failed,err: %v",err) 158 | return 159 | } 160 | 161 | err = loadSecConf() 162 | if err != nil { 163 | logs.Error("load sec conf failed, err:%v", err) 164 | return 165 | } 166 | service.InitService(secKillConf) 167 | 168 | initSecProductWatcher() 169 | 170 | logs.Info("load sec success") 171 | return 172 | } 173 | 174 | func initSecProductWatcher(){ 175 | go watchSecProductKey(secKillConf.EtcdConf.EtcdSecProductKey) 176 | } 177 | 178 | func watchSecProductKey(key string) { 179 | logs.Debug("begin watch key: %s",key) 180 | 181 | for { 182 | watchChan := etcdClient.Watch(context.Background(), key) 183 | var secProductInfo []service.SecProductInfoConf 184 | var getConfSucc = true 185 | 186 | for wresp := range watchChan { 187 | for _,ev := range wresp.Events { 188 | if ev.Type == mvccpb.DELETE{ 189 | logs.Warn("key[%s]'s config deleted",key) 190 | continue 191 | } 192 | if ev.Type == mvccpb.PUT && string(ev.Kv.Key) == key { 193 | err := json.Unmarshal(ev.Kv.Value,&secProductInfo) 194 | if err != nil { 195 | logs.Error("key[%s],Unmarshal[%s] failed,err: %v",ev.Kv.Key,ev.Kv.Value,err) 196 | getConfSucc = false 197 | continue 198 | } 199 | } 200 | logs.Debug("get config from etcd,%s %q: %q\n",ev.Type,ev.Kv.Key,ev.Kv.Value) 201 | } 202 | 203 | if getConfSucc { 204 | logs.Debug("get config from etcd success, %v",secProductInfo) 205 | updateSecProductInfo(secProductInfo) 206 | } 207 | } 208 | } 209 | } 210 | 211 | func updateSecProductInfo(confs []service.SecProductInfoConf) { 212 | var tmp = make(map[int]*service.SecProductInfoConf,1024) 213 | 214 | for _,v :=range confs{ 215 | product := v 216 | tmp[v.ProductId] = &product 217 | } 218 | 219 | secKillConf.RWSecProductLock.Lock() 220 | secKillConf.SecProductInfoMap = tmp 221 | secKillConf.RWSecProductLock.Unlock() 222 | } -------------------------------------------------------------------------------- /video_server/api/dbops/api.go: -------------------------------------------------------------------------------- 1 | package dbops 2 | 3 | import ( 4 | "database/sql" 5 | "golang-awesome/video_server/api/defs" 6 | "golang-awesome/video_server/api/utils" 7 | "log" 8 | "time" 9 | ) 10 | 11 | func AddUserCredential(loginName string, pwd string) error { 12 | stmtIns, err := dbConn.Prepare("INSERT INTO users(login_name,pwd) values (?,?)") 13 | if err != nil { 14 | return err 15 | } 16 | 17 | _, err = stmtIns.Exec(loginName, pwd) 18 | if err != nil { 19 | return err 20 | } 21 | defer stmtIns.Close() 22 | return nil 23 | } 24 | 25 | func GetUserCredential(loginName string) (string, error) { 26 | stmtOut, err := dbConn.Prepare("select pwd from users where login_name = ?") 27 | if err != nil { 28 | log.Printf("%s", err) 29 | return "", err 30 | } 31 | 32 | var pwd string 33 | err = stmtOut.QueryRow(loginName).Scan(&pwd) 34 | if err != nil { 35 | return "", nil 36 | } 37 | 38 | defer stmtOut.Close() 39 | return pwd, nil 40 | } 41 | 42 | func DeleteUser(loginName, pwd string) (err error) { 43 | stmtDel, err := dbConn.Prepare("DELETE FROM users WHERE login_name = ? and pwd = ?") 44 | if err != nil { 45 | log.Printf("Delete user error: %s", err) 46 | return 47 | } 48 | 49 | _, err = stmtDel.Exec(loginName, pwd) 50 | if err != nil { 51 | log.Printf("Delete user error: %s", err) 52 | return 53 | } 54 | 55 | defer stmtDel.Close() 56 | return 57 | } 58 | 59 | func GetUser(loginName string) (user *defs.User, err error) { 60 | stmtOut, err := dbConn.Prepare("select id, pwd from users where login_name = ?") 61 | if err != nil { 62 | log.Printf("%s", err) 63 | return 64 | } 65 | 66 | var id int 67 | var pwd string 68 | err = stmtOut.QueryRow(loginName).Scan(&id, &pwd) 69 | if err != nil && err != sql.ErrNoRows { 70 | log.Printf("%s", err) 71 | return 72 | } 73 | if err == sql.ErrNoRows { 74 | return 75 | } 76 | 77 | user = &defs.User{Id: id, LoginName: loginName, Pwd: pwd} 78 | defer stmtOut.Close() 79 | return 80 | } 81 | 82 | func AddNewVideo(aid int, name string) (video *defs.VideoInfo, err error) { 83 | vid, err := utils.NewUUID() 84 | if err != nil { 85 | return 86 | } 87 | t := time.Now() 88 | ctime := t.Format("Jan 02 2006, 15:04:05") 89 | stmtIns, err := dbConn.Prepare(`insert into video_info 90 | (id, author_id, name, display_ctime) values (?,?,?,?)`) 91 | if err != nil { 92 | log.Printf("%s", err) 93 | return 94 | } 95 | _, err = stmtIns.Exec(vid, aid, name, ctime) 96 | if err != nil { 97 | return 98 | } 99 | video = &defs.VideoInfo{Id: vid, AuthorId: aid, Name: name, DisplayTime: ctime} 100 | defer stmtIns.Close() 101 | return 102 | } 103 | 104 | func GetVideoInfo(vid string) (video *defs.VideoInfo, err error) { 105 | stmtOut, err := dbConn.Prepare("select author_id, name, display_ctime from video_info where vid = ?") 106 | if err != nil { 107 | return 108 | } 109 | 110 | var aid int 111 | var dct, name string 112 | err = stmtOut.QueryRow(vid).Scan(&aid, &name, &dct) 113 | if err != nil && err != sql.ErrNoRows { 114 | return 115 | } 116 | 117 | if err == sql.ErrNoRows { 118 | return nil, nil 119 | } 120 | defer stmtOut.Close() 121 | video = &defs.VideoInfo{ 122 | Id: vid, 123 | AuthorId: aid, 124 | Name: name, 125 | DisplayTime: dct, 126 | } 127 | return 128 | } 129 | 130 | func ListVideoInfo(uname string, from, to int)(videos []*defs.VideoInfo, err error){ 131 | stmtOut, err := dbConn.Prepare(`select v.id, v.author_id, v.name,v.display_ctime from video_info v 132 | inner join users u on v.author_id = u.id where u.login_name = ? and v.create_time > FROM_UNIXTIME(?) 133 | and v.create_time <= FROM_UNIXTIME(?) order by v.create_time desc `) 134 | if err != nil { 135 | log.Printf("%s",err) 136 | return 137 | } 138 | 139 | rows, err := stmtOut.Query(uname, from, to) 140 | if err != nil { 141 | log.Printf("%s",err) 142 | return 143 | } 144 | 145 | for rows.Next() { 146 | var id, name, ctime string 147 | var aid int 148 | if err := rows.Scan(&id, &aid, &name, &ctime); err != nil { 149 | log.Printf("%s",err) 150 | return 151 | } 152 | video := &defs.VideoInfo{ 153 | Id:id, 154 | AuthorId:aid, 155 | Name:name, 156 | DisplayTime:ctime, 157 | } 158 | videos = append(videos,video) 159 | } 160 | defer stmtOut.Close() 161 | return 162 | } 163 | 164 | func DeleteVideoInfo(vid string) (err error){ 165 | stmtDel, err := dbConn.Prepare("delete from video_info where id = ?") 166 | if err != nil { 167 | log.Printf("%s",err) 168 | return 169 | } 170 | 171 | _, err = stmtDel.Exec(vid) 172 | if err != nil { 173 | log.Printf("%s",err) 174 | return 175 | } 176 | 177 | defer stmtDel.Close() 178 | return 179 | } 180 | 181 | func AddNewComments(vid string, aid int,content string) (err error){ 182 | id, err := utils.NewUUID() 183 | if err != nil { 184 | log.Printf("%s",err) 185 | return 186 | } 187 | 188 | stmtIns, err := dbConn.Prepare("insert into comments(id, video_id, author_id, content) values (?,?,?,?)") 189 | if err != nil { 190 | log.Printf("%s",err) 191 | return 192 | } 193 | 194 | _, err = stmtIns.Exec(id,vid,aid,content) 195 | if err != nil { 196 | log.Printf("%s",err) 197 | return 198 | } 199 | defer stmtIns.Close() 200 | return 201 | } 202 | 203 | func ListComments(vid string, from ,to int)(comments []*defs.Comment, err error){ 204 | stmtOut, err := dbConn.Prepare(`select c.id, u.login_name, c.content from comments c 205 | inner join users u on c.author_id = u.id where c.video_id = ? and c.time > 206 | FROM_UNIXTIME(?) and c.time <= FROM_UNIXTIME(?) order by c.time desc`) 207 | 208 | rows, err := stmtOut.Query(vid, from, to) 209 | if err != nil { 210 | log.Printf("%s",err) 211 | return 212 | } 213 | 214 | for rows.Next() { 215 | var id, name, content string 216 | if err := rows.Scan(&id, &name, &content); err != nil { 217 | return 218 | } 219 | comment := &defs.Comment{ 220 | Id:id, 221 | VideoId:vid, 222 | Author:name, 223 | Content:content, 224 | } 225 | comments = append(comments,comment) 226 | } 227 | defer stmtOut.Close() 228 | return 229 | } -------------------------------------------------------------------------------- /video_server/api/handlers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/julienschmidt/httprouter" 6 | "golang-awesome/video_server/api/dbops" 7 | "golang-awesome/video_server/api/defs" 8 | "golang-awesome/video_server/api/session" 9 | "golang-awesome/video_server/api/utils" 10 | "io/ioutil" 11 | "log" 12 | "net/http" 13 | ) 14 | 15 | func CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 16 | //首先从request里面读出create user 相关的body 17 | res, _ := ioutil.ReadAll(r.Body) 18 | ubody := &defs.UserCredential{} 19 | 20 | if err := json.Unmarshal(res, ubody); err != nil { 21 | sendErrorResponse(w, defs.ErrorRequestBodyParseFailed) 22 | return 23 | } 24 | 25 | if err := dbops.AddUserCredential(ubody.UserName, ubody.Pwd); err != nil { 26 | sendErrorResponse(w, defs.ErrorDBError) 27 | } 28 | 29 | id := session.GenerateNewSessionId(ubody.UserName) 30 | su := &defs.SignedUp{Success: true, SessionId: id} 31 | 32 | if resp, err := json.Marshal(su); err != nil { 33 | sendErrorResponse(w, defs.ErrorInternalFaults) 34 | return 35 | } else { 36 | sendNormalResponse(w, string(resp), 201) 37 | } 38 | } 39 | 40 | func Login(w http.ResponseWriter, r *http.Request, params httprouter.Params) { 41 | res, _ := ioutil.ReadAll(r.Body) 42 | log.Printf("%s", res) 43 | ubody := &defs.UserCredential{} 44 | 45 | if err := json.Unmarshal(res, ubody); err != nil { 46 | log.Panicf("%s", err) 47 | sendErrorResponse(w, defs.ErrorRequestBodyParseFailed) 48 | return 49 | } 50 | 51 | uname := params.ByName("username") 52 | log.Panicf("login url name: %s", uname) 53 | log.Printf("login body name: %s", ubody.UserName) 54 | if uname != ubody.UserName { 55 | sendErrorResponse(w, defs.ErrorNotAuthUser) 56 | return 57 | } 58 | 59 | log.Printf("%s", ubody.UserName) 60 | pwd, err := dbops.GetUserCredential(ubody.UserName) 61 | log.Printf("login pwd: %s", pwd) 62 | log.Printf("login body pwd: %s", ubody.Pwd) 63 | if err != nil || len(pwd) == 0 || pwd != ubody.Pwd { 64 | sendErrorResponse(w, defs.ErrorNotAuthUser) 65 | return 66 | } 67 | 68 | id := session.GenerateNewSessionId(ubody.UserName) 69 | si := &defs.SignedIn{Success: true, SessionId: id} 70 | if resp, err := json.Marshal(si); err != nil { 71 | sendErrorResponse(w, defs.ErrorInternalFaults) 72 | } else { 73 | sendNormalResponse(w, string(resp), 200) 74 | } 75 | } 76 | 77 | func GetUserInfo(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 78 | if !ValidateUser(w, r) { 79 | log.Printf("unauthorized user\n") 80 | return 81 | } 82 | 83 | uname := p.ByName("username") 84 | u, err := dbops.GetUser(uname) 85 | if err != nil { 86 | log.Printf("error in GetUserInfo: %s", err) 87 | sendErrorResponse(w, defs.ErrorDBError) 88 | return 89 | } 90 | 91 | ui := defs.UserInfo{Id: u.Id} 92 | if resp, err := json.Marshal(ui); err != nil { 93 | sendErrorResponse(w, defs.ErrorInternalFaults) 94 | } else { 95 | sendNormalResponse(w, string(resp), 200) 96 | } 97 | } 98 | 99 | func AddNewVideo(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 100 | if !ValidateUser(w, r) { 101 | log.Printf("unauthorized user\n") 102 | return 103 | } 104 | 105 | res, _ := ioutil.ReadAll(r.Body) 106 | nvbody := &defs.NewVideo{} 107 | if err := json.Unmarshal(res, nvbody); err != nil { 108 | sendErrorResponse(w, defs.ErrorRequestBodyParseFailed) 109 | return 110 | } 111 | 112 | vi, err := dbops.AddNewVideo(nvbody.AuthorId, nvbody.Name) 113 | log.Printf("author id: %d, name: %s \n", nvbody.AuthorId, nvbody.Name) 114 | if err != nil { 115 | log.Printf("error in AddNewVideo: %s", err) 116 | sendErrorResponse(w, defs.ErrorDBError) 117 | return 118 | } 119 | 120 | if resp, err := json.Marshal(vi); err != nil { 121 | sendErrorResponse(w, defs.ErrorInternalFaults) 122 | } else { 123 | sendNormalResponse(w, string(resp), 201) 124 | } 125 | } 126 | 127 | func ListAllVideos(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 128 | if !ValidateUser(w, r) { 129 | log.Printf("unauthirized user\n") 130 | return 131 | } 132 | 133 | uname := p.ByName("username") 134 | vs, err := dbops.ListVideoInfo(uname, 0, utils.GetCurrentTimestampSec()) 135 | if err != nil { 136 | log.Printf("error in ListAllVideos: %s", err) 137 | sendErrorResponse(w, defs.ErrorDBError) 138 | return 139 | } 140 | 141 | vsi := &defs.VideosInfo{Videos: vs} 142 | if resp, err := json.Marshal(vsi); err != nil { 143 | sendErrorResponse(w, defs.ErrorInternalFaults) 144 | } else { 145 | sendNormalResponse(w, string(resp), 200) 146 | } 147 | } 148 | 149 | func DeleteVideo(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 150 | if !ValidateUser(w, r) { 151 | return 152 | } 153 | 154 | vid := p.ByName("vid-id") 155 | err := dbops.DeleteVideoInfo(vid) 156 | if err != nil { 157 | log.Printf("error in DeleteVideo: %s", err) 158 | sendErrorResponse(w, defs.ErrorDBError) 159 | return 160 | } 161 | 162 | go utils.SendDeleteVideoRequest(vid) 163 | sendNormalResponse(w, "", 204) 164 | } 165 | 166 | func PostComment(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 167 | if !ValidateUser(w, r) { 168 | return 169 | } 170 | reqBody, _ := ioutil.ReadAll(r.Body) 171 | cbody := &defs.NewComment{} 172 | if err := json.Unmarshal(reqBody, cbody); err != nil { 173 | log.Printf("%s", err) 174 | sendErrorResponse(w, defs.ErrorRequestBodyParseFailed) 175 | return 176 | } 177 | vid := p.ByName("vid-id") 178 | if err := dbops.AddNewComments(vid, cbody.AuthorId, cbody.Content); err != nil { 179 | log.Printf("%s", err) 180 | sendErrorResponse(w, defs.ErrorDBError) 181 | } else { 182 | sendNormalResponse(w, "ok", 201) 183 | } 184 | 185 | } 186 | 187 | func ShowComments(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 188 | if !ValidateUser(w, r) { 189 | return 190 | } 191 | 192 | vid := p.ByName("vid-id") 193 | cm, err := dbops.ListComments(vid, 0, utils.GetCurrentTimestampSec()) 194 | if err != nil { 195 | log.Printf("error in ShowComments: %s", err) 196 | sendErrorResponse(w, defs.ErrorDBError) 197 | return 198 | } 199 | 200 | cms := &defs.Comments{Comments: cm} 201 | if resp, err := json.Marshal(cms); err != nil { 202 | sendErrorResponse(w, defs.ErrorInternalFaults) 203 | } else { 204 | sendNormalResponse(w, string(resp), 200) 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /seckill/SecProxy/service/init.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "github.com/astaxie/beego/logs" 5 | "github.com/garyburd/redigo/redis" 6 | "strconv" 7 | "time" 8 | ) 9 | 10 | func InitService(serviceConf *SecKillConf)(err error){ 11 | secKillConf = serviceConf 12 | 13 | err = loadBalckList() 14 | if err != nil{ 15 | logs.Error("load black list err: %v",err) 16 | return 17 | } 18 | logs.Debug("init service success, config:%v",serviceConf) 19 | 20 | err = initProxy2LayerRedis() 21 | if err != nil{ 22 | logs.Error("load proxy2layer redis pool failed, err: %v",err) 23 | return 24 | } 25 | 26 | secKillConf.secLimitMgr = &SecLimitMgr{ 27 | UserLimitMap:make(map[int]*Limit,10000), 28 | IpLimitMap: make(map[string]*Limit,10000), 29 | } 30 | secKillConf.SecReqChan = make(chan *SecRequest,secKillConf.SecReqChanSize) 31 | secKillConf.UserConnMap = make (map[string]chan *SecResult,10000) 32 | 33 | initRedisProcessFunc() 34 | return 35 | } 36 | 37 | func loadBalckList()(err error){ 38 | secKillConf.ipBlackMap = make(map[string]bool,10000) 39 | secKillConf.idBlackMap = make(map[int]bool,10000) 40 | 41 | err = initBlackRedis() 42 | 43 | if err != nil{ 44 | logs.Error("init black redis failed, err:%v",err) 45 | return 46 | } 47 | 48 | conn := secKillConf.blackRedisPool.Get() 49 | defer conn.Close() 50 | 51 | reply, err := conn.Do("hgetall", "id_black_list") 52 | idlist,err :=redis.Strings(reply,err) 53 | if err != nil { 54 | logs.Warn("hget all black id failed, err %v",err) 55 | return 56 | } 57 | 58 | for _,v :=range idlist{ 59 | id, err := strconv.Atoi(v) 60 | if err != nil { 61 | logs.Warn("invalid user id [%v]",id) 62 | continue 63 | } 64 | secKillConf.idBlackMap[id] = true 65 | } 66 | 67 | reply, err = conn.Do("hgetall", "ip_black_list") 68 | iplist,err :=redis.Strings(reply,err) 69 | if err != nil { 70 | logs.Warn("hget all black ip failed, err %v",err) 71 | return 72 | } 73 | 74 | for _,v :=range iplist{ 75 | secKillConf.ipBlackMap[v] = true 76 | } 77 | 78 | go syncIpBLackList() 79 | go syncIdBLackList() 80 | return 81 | } 82 | 83 | //用redis的BLPOP阻塞弹出,达到watch效果 84 | func syncIpBLackList(){ 85 | var ipList []string 86 | lastTime := time.Now().Unix() 87 | for{ 88 | conn := secKillConf.blackRedisPool.Get() 89 | defer conn.Close() 90 | replay,err := conn.Do("BLPOP","blackiplist",time.Second) 91 | ip,err :=redis.String(replay,err) 92 | if err != nil { 93 | continue 94 | } 95 | 96 | curTime := time.Now().Unix() 97 | ipList = append(ipList,ip) 98 | 99 | if len(ipList) >100 || curTime -lastTime >5{ 100 | secKillConf.RWBlackLock.Lock() 101 | for _,v :=range ipList{ 102 | secKillConf.ipBlackMap[v] = true 103 | } 104 | secKillConf.RWBlackLock.Unlock() 105 | 106 | lastTime = curTime 107 | logs.Info("sync ip list from redis success, ip[%v]",ipList) 108 | } 109 | } 110 | } 111 | 112 | func syncIdBLackList(){ 113 | for{ 114 | conn := secKillConf.blackRedisPool.Get() 115 | defer conn.Close() 116 | reply,err := conn.Do("BLPOP","blackidlist",time.Second) 117 | id,err := redis.Int(reply,err) 118 | if err != nil{ 119 | continue 120 | } 121 | secKillConf.RWBlackLock.Lock() 122 | secKillConf.idBlackMap[id] = true 123 | secKillConf.RWBlackLock.Unlock() 124 | logs.Info("sync id list from redis success, ip[%v]",id) 125 | } 126 | } 127 | 128 | func initRedisProcessFunc(){ 129 | for i :=0 ;ili,.layui-laydate-range .layui-laydate-main{display:inline-block;vertical-align:middle}.layui-laydate-list{position:absolute;left:0;top:0;width:100%;height:100%;padding:10px;background-color:#fff}.layui-laydate-list>li{position:relative;width:33.3%;height:36px;line-height:36px;margin:3px 0;text-align:center;cursor:pointer}.laydate-month-list>li{width:25%;margin:17px 0}.laydate-time-list>li{height:100%;margin:0;line-height:normal;cursor:default}.laydate-time-list p{position:relative;top:-4px;line-height:29px}.laydate-time-list ol{height:181px;overflow:hidden}.laydate-time-list>li:hover ol{overflow-y:auto}.laydate-time-list ol li{width:130%;padding-left:33px;line-height:30px;text-align:left;cursor:pointer}.layui-laydate-hint{position:absolute;top:115px;left:50%;width:250px;margin-left:-125px;line-height:20px;padding:15px;text-align:center;font-size:12px}.layui-laydate-range{width:546px}.layui-laydate-range .laydate-main-list-0 .laydate-next-m,.layui-laydate-range .laydate-main-list-0 .laydate-next-y,.layui-laydate-range .laydate-main-list-1 .laydate-prev-m,.layui-laydate-range .laydate-main-list-1 .laydate-prev-y{display:none}.layui-laydate-range .laydate-main-list-1 .layui-laydate-content{border-left:1px solid #e2e2e2}.layui-laydate,.layui-laydate-hint{border:1px solid #d2d2d2;box-shadow:0 2px 4px rgba(0,0,0,.12);background-color:#fff;color:#666}.layui-laydate-header{border-bottom:1px solid #e2e2e2}.layui-laydate-header i:hover,.layui-laydate-header span:hover{color:#5FB878}.layui-laydate-content{border-top:none 0;border-bottom:none 0}.layui-laydate-content th{font-weight:400;color:#333}.layui-laydate-content td{color:#666}.layui-laydate-content td.laydate-selected{background-color:#00F7DE}.laydate-selected:hover{background-color:#00F7DE!important}.layui-laydate-content td:hover,.layui-laydate-list li:hover{background-color:#eaeaea;color:#333}.laydate-time-list li ol{margin:0;padding:0;border:1px solid #e2e2e2;border-left-width:0}.laydate-time-list li:first-child ol{border-left-width:1px}.laydate-time-list>li:hover{background:0 0}.layui-laydate-content .laydate-day-next,.layui-laydate-content .laydate-day-prev{color:#d2d2d2}.laydate-selected.laydate-day-next,.laydate-selected.laydate-day-prev{background-color:#f8f8f8!important}.layui-laydate-footer{border-top:1px solid #e2e2e2}.layui-laydate-hint{color:#FF5722}.laydate-day-mark::after{background-color:#5FB878}.layui-laydate-content td.layui-this .laydate-day-mark::after{display:none}.layui-laydate-footer span[lay-type=date]{color:#5FB878}.layui-laydate .layui-this{background-color:#009688!important;color:#fff!important}.layui-laydate .laydate-disabled,.layui-laydate .laydate-disabled:hover{background:0 0!important;color:#d2d2d2!important;cursor:not-allowed!important;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none}.laydate-theme-molv{border:none}.laydate-theme-molv.layui-laydate-range{width:548px}.laydate-theme-molv .layui-laydate-main{width:274px}.laydate-theme-molv .layui-laydate-header{border:none;background-color:#009688}.laydate-theme-molv .layui-laydate-header i,.laydate-theme-molv .layui-laydate-header span{color:#f6f6f6}.laydate-theme-molv .layui-laydate-header i:hover,.laydate-theme-molv .layui-laydate-header span:hover{color:#fff}.laydate-theme-molv .layui-laydate-content{border:1px solid #e2e2e2;border-top:none;border-bottom:none}.laydate-theme-molv .laydate-main-list-1 .layui-laydate-content{border-left:none}.laydate-theme-grid .laydate-month-list>li,.laydate-theme-grid .laydate-year-list>li,.laydate-theme-grid .layui-laydate-content td,.laydate-theme-grid .layui-laydate-content thead,.laydate-theme-molv .layui-laydate-footer{border:1px solid #e2e2e2}.laydate-theme-grid .laydate-selected,.laydate-theme-grid .laydate-selected:hover{background-color:#f2f2f2!important;color:#009688!important}.laydate-theme-grid .laydate-selected.laydate-day-next,.laydate-theme-grid .laydate-selected.laydate-day-prev{color:#d2d2d2!important}.laydate-theme-grid .laydate-month-list,.laydate-theme-grid .laydate-year-list{margin:1px 0 0 1px}.laydate-theme-grid .laydate-month-list>li,.laydate-theme-grid .laydate-year-list>li{margin:0 -1px -1px 0}.laydate-theme-grid .laydate-year-list>li{height:43px;line-height:43px}.laydate-theme-grid .laydate-month-list>li{height:71px;line-height:71px} --------------------------------------------------------------------------------