伟明部落格

Go编写最简单的Http服务器

--发布于 2022-03-23 11:28:34

使用的是go1.15.linux-amd64.tar.gz

md5: 8b2c0485156e542c934404a9274d9a04

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(":8000", nil)
}

改进版

package main

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

func HelloHandler(w http.ResponseWriter, r *http.Request) {
    timestamp := time.Now().Format("2006-01-02 15:04:05.000")
    fmt.Fprintf(w, "Hello World, Your Addr[%s], Now[%s]\n", r.RemoteAddr, timestamp)
}

func main() {
    http.HandleFunc("/", HelloHandler)
    http.ListenAndServe(":8000", nil)
}
--更新于 2023-03-09 10:51:41