Golang http.HandleFunc:处理查询

colleagues!

Example code is standard:

func echo(w http.ResponseWriter, r *http.Request) {
    c, _ := upgrader.Upgrade(w, r, nil)
    defer c.Close()
    for {       
        _, message, _ := c.ReadMessage()
        log.Printf("recv: %s", message)
        if string(message) == "qwerty"{
            func (){
                fmt.Println("in func 1")
                time.Sleep(time.Second * 10) // here method performs some work
            }()
        }
        if string(message) == "asdfg"{
            func (){
                fmt.Println("in func 2")
                time.Sleep(time.Second * 10) // here method performs some work
            }()
        }

    }
}

func main() {

    http.HandleFunc("/echo", echo)  
    log.Println("Socket waiting connection on * : 3000")
    log.Fatal(http.ListenAndServe(":3000", nil))

}

I have such a trouble. My application is not multitask for a user. User must request a method and wait while system is busy. But while called method is still working, if the same client calls another method, server buffers its request and method 2 starts as soon as previous one is completed. However, I need another behavior from the application: if any method performance is not completed, client must recieve a message, that previous query is still in progress and his new query must be dropped. How can I modify echo func to prevent multitasking? Only one request calls function. If any function still works, another requests drops with message to client to try later.

First off, you have an infinite for loop without any break clause.

You cannot prevent clients from sending subsequent requests to your server without help from session or cookie management. What I would do is assigning cookies to clients when they visit your server and make the cookie required for visiting other resources. Once a client sends a request successfully, update data in the cookie to reflect that current client has a process that is running in the background. You may need some session managements as well on the server side as clients may clear cookies.