go http server example

Language:
Go
16 views
0 favorites
2 hours ago

Code Implementation

Go
package main

import (
    "fmt"
    "net/http"
)

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

func main() {
    http.HandleFunc("/", helloHandler)
    http.ListenAndServe(":80", nil)
}

This example provides a basic Go language HTTP service code snippet. In Go, the net/http package offers all the necessary tools for building an HTTP server. An HTTP server is software that can receive HTTP requests and return HTTP responses. It typically runs on a web server, processes requests from clients, and returns corresponding resources or data based on the content of the requests.

#HTTP

Snippet Description

Code Analysis

  • Import Packages: We import the fmt and net/http packages. fmt is used for formatted output, while net/http handles HTTP requests and responses.
  • Define Handler Function: helloHandler is a handler function that takes two parameters: http.ResponseWriter and *http.Request. http.ResponseWriter is used to send responses to the client, and *http.Request contains all the information about the client's request.
  • Register Route: http.HandleFunc("/", helloHandler) binds the root path "/" to the helloHandler function. When a client accesses the root path, the server will call the helloHandler function to process the request.
  • Start HTTP Server: http.ListenAndServe(":80", nil) starts the server and listens on port 80. nil indicates using the default multiplexer (DefaultServeMux).

Execution

Save the above code as main.go, and run the following command in the terminal:

go run main.go

Open a browser and visit http://localhost:80; you will see "Hello, World" displayed on the page.

Comments

Loading...