Web Server in Go


package main
import (
    "fmt"
    "log"
    "net/http"
)
func main() {
    // fun() function to incoming URLs that beg in with /
    http.HandleFunc ("/", fun)

    // start server listening for incoming requests on port 8000
    log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func fun(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf (w, "hi")
}
            

1 Endpoint to increment, other to return(synchronization)


package main
import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

var mu sync.Mutex
var count int

func main() {
    // fun() function to incoming URLs that beg in with /
    http.HandleFunc ("/", fun)      //Increment
    http.HandleFunc ("/count", counter)      //return counter

    // start server listening for incoming requests on port 8000
    log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

//SYNCHRONIZATION
// server runs the handler for each incoming request in a separate goroutine so that it can serve multiple
// requests simultaneously. if two concurrent requests try to update count at the same
// time, it might not be incremented consistently. Race condition
// To avoid this problem, we must ensure that at most one goroutine
// accesses the variable at a time, which is the purpose of the mu.Lock() and mu.Unlock() calls
func fun(w http.ResponseWriter, r *http.Request) {
    mu.Lock()
    count++
    fmt.Fprintf (w, "incremented")
    mu.Unlock()
}
func counter(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf (w, count)
}