Stateful http handler demo
This commit is contained in:
parent
5c73ef922e
commit
c9cd13747f
1 changed files with 26 additions and 2 deletions
|
@ -1,6 +1,7 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
@ -9,6 +10,26 @@ import (
|
||||||
_ "github.com/mattn/go-sqlite3"
|
_ "github.com/mattn/go-sqlite3"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// The button state as represented in memory
|
||||||
|
type ButtonState struct {
|
||||||
|
pressCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is what a handler with a receiver looks like
|
||||||
|
// Keep in mind that concurrent state access is not (usually) safe
|
||||||
|
// And will in pracice be guarded by a mutex
|
||||||
|
func (b *ButtonState) pressHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
b.pressCount++
|
||||||
|
response, err := json.Marshal(b.pressCount)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Request received")
|
||||||
|
io.WriteString(w, string(response))
|
||||||
|
}
|
||||||
|
|
||||||
// This is what a handler looks like
|
// This is what a handler looks like
|
||||||
func handler(w http.ResponseWriter, r *http.Request) {
|
func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Println("Request received")
|
fmt.Println("Request received")
|
||||||
|
@ -17,15 +38,18 @@ func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
database.DbConnect()
|
database.DbConnect()
|
||||||
|
b := &ButtonState{pressCount: 0}
|
||||||
|
|
||||||
// Mounting the handler
|
// Mounting the handlers
|
||||||
fs := http.FileServer(http.Dir("static"))
|
fs := http.FileServer(http.Dir("static"))
|
||||||
http.Handle("/", fs)
|
http.Handle("/", fs)
|
||||||
http.HandleFunc("/hello", handler)
|
http.HandleFunc("/hello", handler)
|
||||||
|
http.HandleFunc("/button", b.pressHandler)
|
||||||
|
|
||||||
// Start the server on port 8080
|
// Start the server on port 8080
|
||||||
println("Currently listening on http://localhost:8080")
|
println("Currently listening on http://localhost:8080")
|
||||||
println("Visit http://localhost:8080/hello to see the handler in action")
|
println("Visit http://localhost:8080/hello to see the hello handler in action")
|
||||||
|
println("Visit http://localhost:8080/button to see the button handler in action")
|
||||||
println("Press Ctrl+C to stop the server")
|
println("Press Ctrl+C to stop the server")
|
||||||
err := http.ListenAndServe(":8080", nil)
|
err := http.ListenAndServe(":8080", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
Loading…
Reference in a new issue