TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang ListenAndServe Examples (HandleFunc)

Use the net http package to create a web server. Invoke ListenAndServe and call HandleFunc.
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).

HandleFunc: 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.

Golang program that uses http.ListenAndServe 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.

Type into browser: http://localhost:8080 http://localhost:8080/about http://localhost:8080/images
Header, image content type. We can write an image to the response in Golang. In a HandleFunc, we can call Header() and then Set the Content-type.

Here: We read in a local image from the disk. We write its bytes to the response when the "image" path is accessed.

And: Checking the headers, we can see that the response has the correct content type of "image/jpeg."

Golang program that uses Header, writes image 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)) }
A summary. Building a simple server in Go is not difficult. And for many projects, a simple server can be used to make development easier.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf