Go言語と、Framework [echo]を利用してAPIを作成しております。
特定のデータごとのタイマーを、Web APIを利用して実装したいと考えております。
処理の流れとしましては下記のような実装を考えております。
1.タイマー開始用のAPIにパラメーター付きでアクセスし、goroutineで、別プロセスを起動
2.タイマー停止用のAPIにパラメーター付きでアクセスし、既に動いているgoroutineを検知し、プロセスを停止
実際に実装を行い別プロセス毎に、動かせているような実装はできました?…。
しかし、2の処理を行うと、プログラムが停止しません。
そもそも、実現しようとしていることに無理があるのかもしれませんが、
アドバイスを頂けると幸いです。
大変、お手数をおかけしますが、宜しくお願い致します。
▼main.go
go
1 2 3package main 4 5import ( 6 "sample/handler" 7 8 _ "github.com/go-sql-driver/mysql" 9 "github.com/labstack/echo" 10 "sample/data" 11) 12 13func main() { 14 15 // トップディレクトリ 16 e := echo.New() 17 18 ch := make(chan bool) 19 20 // 製品を監視するタイマー 21 var ids = make([]*data.Ids, 0) 22 23 e.GET("start", handler.Start(ch, ids)) 24 e.GET("stop", handler.Stop(ch, ids)) 25 26 e.Logger.Fatal(e.Start(":1323")) 27} 28 29
▼handler/start.go
Go
1 2package handler 3 4import ( 5 "github.com/labstack/echo" 6 "net/http" 7 "fmt" 8 "time" 9 "strconv" 10 "sample/data" 11) 12 13func Start(ch chan bool, ids []*data.Ids) echo.HandlerFunc { 14 15 return func(c echo.Context) error { 16 17 id := c.QueryParam("id") 18 limit, _ := strconv.Atoi(c.QueryParam("limit")) 19 20 go func() { 21 22 //result = append(result, &(data.Ids{Id: v.Id})) 23 ids = append(ids, &(data.Ids{Id:id})) 24 25 t := time.NewTicker(3 * time.Second) // 1秒おきにチェック 26 n := 0 27 for { 28 select { 29 case <-t.C: 30 if ( limit < n) { 31 fmt.Print("over") 32 } 33 fmt.Print("id =" + id) 34 fmt.Println(n) 35 n++ 36 case <-ch: 37 fmt.Println("stop") 38 39 t.Stop() 40 } 41 } 42 43 }() 44 45 return c.JSON(http.StatusCreated, "ok") 46 } 47 48} 49
▼handler/stop.go
Go
1package handler 2 3import ( 4 "github.com/labstack/echo" 5 "net/http" 6 "sample/data" 7 "fmt" 8) 9 10func Stop(ch chan bool, ids []*data.Ids) echo.HandlerFunc { 11 12 return func(c echo.Context) error { 13 id := c.QueryParam("id") 14 arrayRemove(ids, id) 15 16 ch <- true 17 return c.JSON(http.StatusCreated, "ok") 18 } 19 20} 21 22func arrayRemove(arr []*data.Ids, str string) []*data.Ids { 23 24 fmt.Println("remove") 25 26 result := make([]*data.Ids, 0) 27 for _, v := range arr { 28 if v.Id != str { 29 result = append(result, &(data.Ids{Id: v.Id})) 30 fmt.Println(v.Id) 31 } 32 } 33 return result 34}
▼sample/data/ids.go
Go
1package data 2 3type Ids struct { 4 Id string 5}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。