golang同时监听TCP、HTTP端口提供服务

项目入口 main.go 中,之前是监听 TCP 连接,代码大致如下:

package main

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

func main() {
    http.HandleFunc("/hi", Router)

    go http.ListenAndServe("127.0.0.1:8080", nil)

    server, err := net.Listen("tcp", "127.0.0.1:9090")
    if err != nil {
        panic(err)
    }
    defer server.Close()

    for {
        conn, err := server.Accept()
        if err != nil {
            continue
        }
        go handleConn(conn)
    }
}

func Router(resp http.ResponseWriter, request *http.Request) {
    resp.Write([]byte("hello world"))
}

func handleConn(conn net.Conn) {
    fmt.Println(conn.RemoteAddr().String())
}

你可能感兴趣的:(golang同时监听TCP、HTTP端口提供服务)