栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

尽管可以使用通道执行此操作,但我更希望使用受互斥锁保护的哈希(映射),因为在这种情况下更容易实现。

为您提供一个想法并助您一臂之力:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/594959.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号