Home >Backend Development >Golang >Use the http.Server function to create an HTTP server object that can listen to the specified address and port.

Use the http.Server function to create an HTTP server object that can listen to the specified address and port.

PHPz
PHPzOriginal
2023-07-24 13:05:121669browse

Use the http.Server function to create an HTTP server object that can listen to the specified address and port

In Go language, we can use the http.Server function to create an HTTP server that can listen to the specified address and port. object. The http.Server function receives a parameter of type http.Handler, that is, we can pass in our custom handler to handle HTTP requests.

The following is a sample code showing how to use the http.Server function to create a simple HTTP server object and listen to the specified address and port:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    // 定义处理HTTP请求的处理程序
    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    })

    // 创建HTTP服务器对象
    server := &http.Server{
        Addr:    "localhost:8080", // 监听的地址和端口
        Handler: handler,          // 指定处理程序
    }

    // 启动服务器
    log.Println("Starting server on", server.Addr)
    err := server.ListenAndServe()
    if err != nil {
        log.Fatal("Server error:", err)
    }
}

In the above code, we first define A handler for handling HTTP requests is created. This handler uses the http.HandlerFunc function to convert a function to the http.Handler type. In this handler, we simply write the "Hello, World!" string into the ResponseWriter as the content of the response.

Then, we use the http.Server structure to create an HTTP server object, in which we specify the listening address and port and the handler.

Finally, we start the server by calling server.ListenAndServe() and use the log package to output the server's startup information. If an error occurs during startup, we use the log.Fatal function to output the error message and exit the program.

In actual applications, we can define more complex handlers and routing rules according to needs to achieve more powerful HTTP server functions.

The above is the detailed content of Use the http.Server function to create an HTTP server object that can listen to the specified address and port.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn