func handler(w http.ResponseWriter, r *http.Request) { // Write a response to the client fmt.Fprintf(w, "Hello, World!") } func main() { // Register the handler function with the default ServeMux http.HandleFunc("/", handler) // Start the server and listen for incoming HTTP requests http.ListenAndServe(":8080", nil) }
type MyHandler struct{} func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "This is my server!") } func main() { handler := &MyHandler{} // Create a new HTTP server with our handler server := &http.Server{ Addr: ":8080", Handler: handler, } // Start the server and listen for incoming requests server.ListenAndServe() }This example defines a custom handler by creating a struct that implements the ServeHTTP method of the http.Handler interface. We then create a new HTTP server with our handler and start it listening for incoming requests on port 8080. In both examples, the net/http package is used to implement an HTTP server and handle incoming requests. The package provides a rich set of features for working with HTTP including support for cookies, sessions, and middleware.