type MyHandler struct{} func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func main() { handler := &MyHandler{} http.ListenAndServe(":8080", handler) }
func handleRequest(w http.ResponseWriter, r *http.Request) { response := "This is a sample response." w.Write([]byte(response)) } func main() { http.HandleFunc("/", handleRequest) http.ListenAndServe(":8080", nil) }This example uses a function instead of a struct to handle incoming HTTP requests. It defines a function `handleRequest` that takes in a `ResponseWriter` and `Request` object, creates a response string, and writes it to the response writer. It then uses the `http.HandleFunc` method to map incoming requests to the `handleRequest` function and starts a listener at port 8080. Both examples use the `net/http` package in Go.