return a text response from a http server in go

To return a text response from an http server in Go, you can follow these steps:

  1. Start by importing the necessary packages, including "net/http" and "fmt".
  2. Write a handler function that takes two arguments: a ResponseWriter interface and a pointer to a Request struct. Inside the handler function, use the Write method of the ResponseWriter interface to write the text response that you want to send back to the client.
  3. Next, create a new server instance using the NewServer function from the http package, and register your handler function using the HandleFunc method.
  4. Finally, call the ListenAndServe method on your server instance and specify the port number that you want your server to listen on.

Here's an example code snippet that demonstrates how to return a simple "Hello, World!" text response from an http server in Go:

main.go
package main

import (
	"fmt"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, World!")
}

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

In this example, we define a handler function called "helloHandler" that takes a ResponseWriter interface and a pointer to a Request struct. The function writes the "Hello, World!" string to the ResponseWriter interface using the Fprintf method.

We then use the HandleFunc method to register the helloHandler function as the handler for the root path ("/") of our server.

Finally, we call the ListenAndServe method on our server instance and specify the port number that we want our server to listen on. When a client makes a request to our server, the "Hello, World!" string will be returned as the response.

related categories

gistlibby LogSnag