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

Golang:异步http服务器中的共享通信,第1张

概述除了编写一个简单的http服务器之外,golang的绝对初学者.我正在研究Go作为编写异步过程的可能性.如果可以,请提供一个如何实现这一目标的快速示例: Http请求’a’进来,根据此请求中的POST有效负载启动 *** 作(在post或url中使用某种唯一标识符).由’a’启动的异步过程将使用原始唯一标识符(请求’b’)响应同一服务器,而请求’a’仍然打开.我想根据请求’b’响应将该响应传达回请求’a’ 除了编写一个简单的http服务器之外,golang的绝对初学者.我正在研究Go作为编写异步过程的可能性.如果可以,请提供一个如何实现这一目标的快速示例:

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

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

给你一个想法,让你去:

package mainimport (    "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 packagefunc 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)    }}
总结

以上是内存溢出为你收集整理的Golang:异步http服务器中的共享通信全部内容,希望文章能够帮你解决Golang:异步http服务器中的共享通信所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1264989.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存