golang之手写web服务器

简单的web服务器:

package main

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

func sayHello(w http.ResponseWriter ,r *http.Request){
    //_,_ = fmt.Fprintln(w,"<h1>hello golang</h1>")   // 直接将字符串内容返回到页面
    b,_ :=ioutil.ReadFile("./hello.txt")              // 读取文件,并将内容赋值给变量b,b的值是byte类型
    _,_ = fmt.Fprintln(w,string(b))
}
func main(){
    http.HandleFunc("/hello",sayHello)
    err := http.ListenAndServe(":9000",nil)
    if err !=nil{
        fmt.Printf("监听失败:%v",err)
        return
    }
}

 

浏览器访问URL:http://127.0.0.1:9000/hello

posted @ 2021-05-31 15:40  *年少轻狂*  阅读(94)  评论(0)    收藏  举报