To create an HTTP server and add a custom header to the response in Go, you can follow these steps:
net/http
packagew.Header().Set()
method inside the handler functionhttp.ListenAndServe()
methodHere's an example code snippets to illustrate it:
main.go422 chars26 lines
In this example, the handler
function is registered to the root endpoint ("/"
) using the http.HandleFunc()
method. Inside the handler
function, we set a custom header using the w.Header().Set()
method and write the response body using the fmt.Fprintf()
method.
When the server starts using the http.ListenAndServe()
method, it listens on port 8080
.
gistlibby LogSnag