To create an HTTP server in Go, you can use the built-in net/http
package. Here's a step-by-step guide to creating an HTTP server to handle incoming HTTP requests:
import (
"fmt"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Write your logic to handle the request here
fmt.Fprintf(w, "Hello, World!")
}
main()
function, create a new HTTP server and register the request handler function with a specific route:func main() {
http.HandleFunc("/", handler) // Route "/" will be handled by the handler function
log.Fatal(http.ListenAndServe(":8080", nil)) // Start the server on port 8080
}
go run main.go
in your terminal.Now, your HTTP server is running and listening for incoming HTTP requests on http://localhost:8080/
. When a request is made to that URL, the server will execute the logic defined in the handler()
function and send the response back to the client.
You can customize the server by adding more routes and request handlers as needed. The http.ResponseWriter
parameter allows you to send a response back to the client, and the http.Request
parameter provides access to the request details such as URL parameters, headers, and body.