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

除了编写一个简单的http服务器之外,golang的绝对初学者.我正在研究Go作为编写异步过程的可能性.如果可以,请提供一个如何实现这一目标的快速示例:

Http请求’a’进来,根据此请求中的POST有效负载启动操作(在post或url中使用某种唯一标识符).由’a’启动的异步过程将使用原始唯一标识符(请求’b’)响应同一服务器,而请求’a’仍然打开.我想根据请求’b’响应将该响应传达回请求’a’.

解决方法

虽然可以通过频道完成此操作,
我更喜欢受互斥锁保护的哈希(map),
因为在这种情况下它更容易.

给你一个想法,让你去:

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)
    }
}

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s &quot;strings&quot; import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...