ListenAndServe
A simple web server has many uses—it can be used to develop local websites. With the net http package in Go, we can develop simple web servers.
With http.HandleFunc
we can register functions to handle URLs for the web server. We call ListenAndServe
to start the server.
To begin we import the "net/http" package. In main()
we invoke HandleFunc
3 times. We specify 3 methods (test0, test1, and test2).
func
used with HandleFunc
, we receive 2 arguments. We can use the ResponseWriter
to write a response.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)) }
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.
http://localhost:8080 http://localhost:8080/about http://localhost:8080/images
We can write an image to the response in Go. In a HandleFunc
, we can call Header()
and then Set the Content-type.
package main import ( "bufio" "io/ioutil" "log" "net/http" "os" ) func Image(w http.ResponseWriter, r *http.Request) { // Open a JPG file. f, _ := os.Open("/home/sam/coin.jpg") // Read the entire JPG file into memory. reader := bufio.NewReader(f) content, _ := ioutil.ReadAll(reader) // Set the Content Type header. w.Header().Set("Content-Type", "image/jpeg") // Write the image to the response. w.Write(content) } func main() { // Use this URL. http.HandleFunc("/image", Image) // Run. log.Fatal(http.ListenAndServe(":8080", nil)) }
Building a simple server in Go is not difficult. And for many projects, a simple server can be used to make development easier.