Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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.</p> <p>To give you an idea and get you going:</p> <pre><code>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 = &amp;state{&amp;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 = `&lt;html&gt; &lt;body&gt; &lt;form action="/" method="POST"&gt; ID: &lt;input name="id" value="42" /&gt;&lt;br /&gt; Val: &lt;input name="val" /&gt;&lt;br /&gt; &lt;input type="submit" value="submit"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;` 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) } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload