Go语言里面提供了net/http包,我们通过http包来搭建一个的Web服务器。

package main
import(
    "fmt"
    "net/http"
    "log"
    "os"
    "os/signal"
    "syscall"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {        
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    fmt.Fprintf(w,"<hr/>")
    fmt.Fprintf(w, "<h1>Hello https://const.net.cn!</h1>")
}    

func main(){
    fmt.Println("first web server demo.")
    // 创建系统信号接收器
    done := make(chan os.Signal)
    signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
    go func() {
        <-done 
        fmt.Println("Shutdown server")
        os.Exit(1)
    }()
    fs := http.FileServer(http.Dir("e:/")) 
    http.Handle("/static/", http.StripPrefix("/static/", fs))
    http.HandleFunc("/", sayhelloName) 
    err := http.ListenAndServe(":8080", nil) 
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

访问http://127.0.0.1:8080/

效果如下:
2021-06-12_170307.png

访问http://127.0.0.1:8080/static/
效果如下:
2021-06-12_170344.png

本文链接地址:https://const.net.cn/32.html

标签: none

添加新评论