return a html response from a http server in go

Here's an example code snippet that demonstrates how to return a simple HTML response from an HTTP server in Go:

main.go
package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<h1>Hello, world!</h1>")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
242 chars
16 lines

In this example, we define a handler function that takes an http.ResponseWriter and an http.Request. The http.ResponseWriter is used to send the HTTP response, and the http.Request contains information about the incoming request.

Inside the handler function, we use the fmt.Fprintf function to write a simple HTML string to the http.ResponseWriter. This string will be sent back to the client as the HTTP response body.

Finally, we use the http.HandleFunc function to associate the handler function with the root URL path ("/"). We then start the HTTP server by calling http.ListenAndServe, passing nil as the second argument, which uses the default HTTP handler.

By running this program and visiting http://localhost:8080 in your browser, you should see "Hello, world!" displayed in a large heading.

gistlibby LogSnag