功能
知识点
- 如何发起一个服务
- 错误处理的综合应用
- 网络基础的IO操作
目录结构
project
handler/
- handler
- web.go
- index.html
- go.mod
代码
package main
import (
"carmen.com/study/web/hander"
"net/http"
"os"
)
type appHandler func(writer http.ResponseWriter, request *http.Request) error
//错误处理
func errWrapper(handler appHandler) func(http.ResponseWriter,*http.Request){
return func(writer http.ResponseWriter, request *http.Request) {
err := handler(writer,request)
if err != nil{
//log.Warning("Error handler request: %s",err)
code := http.StatusOK
msg := ""
switch {
case os.IsNotExist(err):
code = http.StatusNotFound
msg = http.StatusText(code)
default:
code = http.StatusInternalServerError
msg = http.StatusText(code)
}
http.Error(writer,msg,code)
}
}
}
//文件服务器
func main() {
http.HandleFunc("/",
errWrapper(hander.HandlerfileList))
err := http.ListenAndServe(":8080",nil)
if err != nil {
panic(err)
}
}
package hander
import (
"io/ioutil"
"net/http"
"os"
)
func HandlerfileList(writer http.ResponseWriter,request *http.Request) error {
//业务逻辑
//处理业务
path := request.URL.Path[len("/"):]
file, err := os.Open(path)
if err != nil {
return err
//在http服务顺,panic会被保护,程序无法终止,需要修改错误处理方式
//panic(err)
//http.Error会将错误输出到前端
//http.Error(writer,err.Error(),http.StatusInternalServerError)
}
defer file.Close()
all,err := ioutil.ReadAll(file)
if err != nil {
return err
}
writer.Write(all)
return nil
}
<html>
<body>
<b>hello world</b>
</body>
</html>
运行程序
go build
web.exe
访问浏览
http://localhost:8080/index.html
网友评论