GO学习笔记(16) - 简易静态文件web应用

2021-07-06  本文已影响0人  卡门001

功能

知识点

目录结构

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
上一篇下一篇

猜你喜欢

热点阅读