ListenAndServe. A simple web server has many uses—it can be used to develop local websites. With the net http package in Golang, we can develop simple web servers.
Notes, HandleFunc. With http.HandleFunc we can register functions to handle URLs for the web server. We call ListenAndServe to start the server.
An example. To begin we import the "net/http" package. In main() we invoke HandleFunc 3 times. We specify 3 methods (test0, test1, and test2).
Detail For each func used with HandleFunc, we receive 2 arguments. We can use the ResponseWriter to write a response.
And We can test the http.Request for more information like the URL and its Path.
package main
import (
"fmt"
"html"
"log"
"net/http"
)
func test0(w http.ResponseWriter, r *http.Request) {
// Handles top-level page.
fmt.Fprintf(w, "You are on the home page")
}
func test1(w http.ResponseWriter, r *http.Request) {
// Handles about page.// ... Get the path from the URL of the request.
path := html.EscapeString(r.URL.Path)
fmt.Fprintf(w, "Now you are on: %q", path)
}
func test2(w http.ResponseWriter, r *http.Request) {
// Handles "images" page.
fmt.Fprintf(w, "Image page")
}
func main() {
// Add handle funcs for 3 pages.
http.HandleFunc("/", test0)
http.HandleFunc("/about", test1)
http.HandleFunc("/images", test2)
// Run the web server.
log.Fatal(http.ListenAndServe(":8080", nil))
}
Notes, log.Fatal. We call http.ListenAndServe within the log.Fatal method call. We specify the server port 8080—this is used in your web browser.
Tip After running Go on the program, open your web browser and type in the localhost domain.
Then Go to "/about" and "images" on the localhost domain. The pages should show the messages from the test methods.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 1, 2022 (edit link).