create a http server and add a custom header to the response in go

To create an HTTP server and add a custom header to the response in Go, you can follow these steps:

  • Import the net/http package
  • Create a handler function to return the response
  • Add a custom header using the w.Header().Set() method inside the handler function
  • Start the server using the http.ListenAndServe() method

Here's an example code snippets to illustrate it:

main.go
package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	// Set the custom header
	w.Header().Set("X-Custom-Header", "Hello, World!")
	
	// Write the response body
	fmt.Fprintf(w, "Hello, World!")
}

func main() {
	// Register the handler function
	http.HandleFunc("/", handler)

	// Start the server
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}
422 chars
26 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.

related categories

gistlibby LogSnag