dpkajqd31574096 2013-07-26 20:51
浏览 158
已采纳

Golang:异步HTTP服务器中的共享通信

Absolute beginner to golang other than writing a simple http server. I'm researching Go as a possibility for writing an async process. If you could please provide a quick sample of how this might be accomplished:

Http request 'a' comes in, an operation is started based on POST payload in this request (with some sort of unique identifier in post or url). The async process started by 'a' will respond back to same server with original unique identifier (request 'b') while request 'a' is still open. I'd like to communicate that response back to request 'a' based on request 'b' response.

  • 写回答

1条回答 默认 最新

  • dsu5188 2013-07-29 17:26
    关注

    Although it is possible to do this with channels, I would prefer a hash (map) that is protected by a mutex, since it is easier in this case.

    To give you an idea and get you going:

    package main
    
    import (
        "fmt"
        "net/http"
        "sync"
    )
    
    type state struct {
        *sync.Mutex // inherits locking methods
        Vals map[string]string // map ids to values
    }
    
    var State = &state{&sync.Mutex{}, map[string]string{}}
    
    func get(rw http.ResponseWriter, req *http.Request) {
        State.Lock()
        defer State.Unlock() // ensure the lock is removed after leaving the the function
        id := req.URL.Query().Get("id") // if you need other types, take a look at strconv package
        val := State.Vals[id]
        delete(State.Vals, id)
        rw.Write([]byte("got: " + val))
    }
    
    func post(rw http.ResponseWriter, req *http.Request) {
        State.Lock()
        defer State.Unlock()
        id := req.FormValue("id")
        State.Vals[id] = req.FormValue("val")
        rw.Write([]byte("go to http://localhost:8080/?id=42"))
    }
    
    var form = `<html>
        <body>
            <form action="/" method="POST">
                ID: <input name="id" value="42" /><br />
                Val: <input name="val" /><br />
                <input type="submit" value="submit"/>
            </form>
        </body>
    </html>`
    
    func formHandler(rw http.ResponseWriter, req *http.Request) {
        rw.Write([]byte(form))
    }
    
    // for real routing take a look at gorilla/mux package
    func handler(rw http.ResponseWriter, req *http.Request) {
        switch req.Method {
        case "POST":
            post(rw, req)
        case "GET":
            if req.URL.String() == "/form" {
                formHandler(rw, req)
                return
            }
            get(rw, req)
        }
    }
    
    func main() {
        fmt.Println("go to http://localhost:8080/form")
        // thats the default webserver of the net/http package, but you may
        // create custom servers as well
        err := http.ListenAndServe("localhost:8080", http.HandlerFunc(handler))
        if err != nil {
            fmt.Println(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)