Better button handler server-side
This commit is contained in:
		
							parent
							
								
									ebe2a42f91
								
							
						
					
					
						commit
						4554ddab6d
					
				
					 1 changed files with 8 additions and 5 deletions
				
			
		|  | @ -12,15 +12,18 @@ import ( | |||
| 
 | ||||
| // The button state as represented in memory | ||||
| type ButtonState struct { | ||||
| 	pressCount int | ||||
| 	PressCount int `json:"pressCount"` | ||||
| } | ||||
| 
 | ||||
| // 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 r.Method != "POST" { | ||||
| 		b.PressCount++ | ||||
| 	} | ||||
| 
 | ||||
| 	response, err := json.Marshal(b) | ||||
| 	if err != nil { | ||||
| 		http.Error(w, err.Error(), http.StatusInternalServerError) | ||||
| 		return | ||||
|  | @ -38,13 +41,13 @@ func handler(w http.ResponseWriter, r *http.Request) { | |||
| 
 | ||||
| func main() { | ||||
| 	database.DbConnect() | ||||
| 	b := &ButtonState{pressCount: 0} | ||||
| 	b := &ButtonState{PressCount: 0} | ||||
| 
 | ||||
| 	// Mounting the handlers | ||||
| 	fs := http.FileServer(http.Dir("static")) | ||||
| 	http.Handle("/", fs) | ||||
| 	http.HandleFunc("/hello", handler) | ||||
| 	http.HandleFunc("/button", b.pressHandler) | ||||
| 	http.HandleFunc("/api/button", b.pressHandler) | ||||
| 
 | ||||
| 	// Start the server on port 8080 | ||||
| 	println("Currently listening on http://localhost:8080") | ||||
|  |  | |||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue
	
	 Imbus
						Imbus