To create a custom HTTP server with routing and request handling in Go, you can use the net/http
package. Below is an example of how you can achieve this:
import (
"fmt"
"log"
"net/http"
)
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Home Page!")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is the About Page!")
}
func router() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("/", homeHandler)
mux.HandleFunc("/about", aboutHandler)
return mux
}
func main() {
server := &http.Server{
Addr: ":8080",
Handler: router(),
}
log.Println("Server started on http://localhost:8080")
log.Fatal(server.ListenAndServe())
}
Now, when you access http://localhost:8080
, you will see the "Welcome to the Home Page!" message, and when you access http://localhost:8080/about
, you will see the "This is the About Page!" message.
This example demonstrates the basic setup for creating a custom HTTP server with routing and request handling in Go. You can expand on this by adding more routes and handlers as per your requirements.