Go Programming/Simple Web App

From Wikibooks, open books for an open world
Jump to navigation Jump to search

There are multiple packages in the standard library. One of those packages is called net/http. The package can be used to make simple web applications. Here is a simple example that will output Hello world! when localhost:8080 is visited.

package main

import (
   "fmt"
   "log"
   "net/http"
)

func helloFunc(w http.ResponseWriter, r *http.Request) {
   fmt.Fprintf(w, "Hello world!")
}

func main() {
	http.HandleFunc("/", helloFunc)
	http.ListenAndServe(":8080", nil)
}

You might see some new things that appeared.

import (
   "fmt"
   "net/http"
)

As you see, the fmt package has been imported again. However, the net/http package has also been imported.

func helloFunc(w http.ResponseWriter, r *http.Request)

A function called helloFunc is declared. The http.ResponseWriter type is used in the function to construct an HTTP response. The *http.Request is a pointer to a HTTP request received by a server or something be sent by a client.

fmt.Fprintf(w, "Hello world!")

In this line, the string "Hello world!" is being written to the ResponseWriter in order for it to be displayed in the output.

func main() {
	http.HandleFunc("/", helloFunc)
	http.ListenAndServe(":8080", nil)
}

The main function has been declared with two actions. The handler function, helloFunc has been connected to the "/" route. Finally, the ListenAndServe has been called with a port that is "8080" and no router has been given to the second parameter.

Now, when the program is ran, Hello world! is expected to be shown on the website: localhost:8080.