访问URL时终止go例程

时间:2018-10-01 06:33:43

标签: go

我使用Go制作了一个简单的Web应用程序。用户访问URL时会执行goroutine,例如/inspection/start/。当用户访问网址goroutine时如何停止/inspection/stop/

我听说过channel,但是我不确定该怎么做。

代码如下:

func inspection_form_handler(w http.ResponseWriter, r *http.Request) {
    if r.FormValue("save") != "" {
        airport_id := getCurrentAirportId(r)

        r.ParseForm()
        if airport_id != nil {
            if r.FormValue("action") == "add"{
                go read_serial_port()
            }

            // redirect back to the list
            http.Redirect(w, r, "/airport#inspect", http.StatusSeeOther)
        }
    }
}

常规功能

func read_serial_port(){
    c := &serial.Config{Name:"/dev/ttyACM0", Baud:9600}
    s, err := serial.OpenPort(c)

    if err != nil {
        log.Fatal(err)
    }

    filename:= randSeq(10)+".txt"
    file, _ := os.Create("output/"+filename)

    defer file.Close();

    for{
        buf := make([]byte, 128)
        n, err := s.Read(buf)

        if err != nil {
            log.Fatal(err)
        }

        log.Printf("%s", string(buf[:n]))

        fmt.Fprintf(file, string(buf[:n]))

        time.Sleep(100 * time.Millisecond)
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用时间行情指示器和上下文来实现它

func read_serial_port(c context.Context){
    c := &serial.Config{Name:"/dev/ttyACM0", Baud:9600}
    s, err := serial.OpenPort(c)

    if err != nil {
        log.Fatal(err)
    }

    filename:= randSeq(10)+".txt"
    file, _ := os.Create("output/"+filename)

    defer file.Close();

    ticker := time.NewTicker(100 * time.Millisecond)
    defer ticker.Stop()

    for{
        select {
        case <-c.Done():
            break
        case <-ticker.C:
            buf := make([]byte, 128)
            n, err := s.Read(buf)

            if err != nil {
                log.Fatal(err)
            }

            log.Printf("%s", string(buf[:n]))

            fmt.Fprintf(file, string(buf[:n]))

            time.Sleep(100 * time.Millisecond)
        }
    }
}

然后您需要添加另一条路线来调用取消功能

if r.FormValue("action") == "add"{
    c, cnl := context.WithCancel(context.Background())
    // need to access this cancel function to use it in another route
    ExportedFunction = cnl
    go read_serial_port()
}

然后通过以下方式取消它:

func abortingMission(w http.ResponseWriter, r *http.Request) {
    ExportedFunction()
}

也不要在函数名称中使用下划线

相关问题