Go by Example: HTTP Server

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
	})

	http.ListenAndServe(":8080", nil)
}

This example starts an HTTP server that listens on port 8080 and responds to incoming requests. The http.HandleFunc function is used to register a function that will handle incoming requests. This function writes a message to the http.ResponseWriter indicating the requested URL path. The http.ListenAndServe function is used to start the HTTP server and listen for incoming requests. The second argument to ListenAndServe, nil, is used to indicate that the server should use the default router.

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Welcome to the homepage!\n")
	})

	http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "About page\n")
	})

	http.ListenAndServe(":8080", nil)
}

This example is similar to the previous example, but it includes two handlers functions, one for the home page (“/”) and one for the about page (“/about”). Each handler function writes a different message to the http.ResponseWriter indicating the type of page that was requested. The http.ListenAndServe function is used to start the HTTP server and listen for incoming requests as before.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *