写一个简单的网络文件服务器,用Go语言写一个简单的HTTP服务器,及静态文件服务器...

本文介绍了如何使用Go语言创建一个简单的Web服务器,通过`http.ServeMux`处理不同URL路径的请求,包括'/hello', '/bye'和'/static'。重点讲解了ServeMux的工作原理和如何实现基本的HTTP请求处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package main

import (

// "fmt"

"io"

"log"

"net/http"

"os"

"regexp"

"time"

)

func main() {

serveMux := http.NewServeMux()

serveMux.HandleFunc("/", SayHello)

serveMux.HandleFunc("/bye", SayBye)

// serveMux.HandleFunc("/static", StaticServer)

server := http.Server{

Addr: ":8080",

Handler: serveMux,

ReadTimeout: 5 * time.Second,

}

err := server.ListenAndServe()

if err != nil {

log.Fatal(err)

}

}

func SayHello(w http.ResponseWriter, r *http.Request) {

if ok, _ := regexp.MatchString("/static/", r.URL.String()); ok {

StaticServer(w, r)

return

}

io.WriteString(w, "hello world")

}

func SayBye(w http.ResponseWriter, r *http.Request) {

io.WriteString(w, "Byebye")

}

func StaticServer(w http.ResponseWriter, r *http.Request) {

wd, err := os.Getwd()

if err != nil {

log.Fatal(err)

}

http.StripPrefix("/static/",

http.FileServer(http.Dir(wd))).ServeHTTP(w, r)

}

// http.ListenAndServe(addr string, handler Handler)

// handlerhttp.Handlerinterface(ServeHTTP)

// handler single实现了ServeHTTP

// http.ListenAndServe(":8080", single) 所以可以这样

// NewServeMuxhttp.ServeMux实现了ServeHTTP

// http.ListenAndServe(":8080", mux) 所以可以这样

// http.Server包含了Handler 即http.DefaultServeMux

// DefaultServeMuxServeMux实现了ServeHTTP

// http.ListenAndServe(addr string, handler Handler)

// 底层 Http.Server

// 调用server.ListenAndServe()

// 所以 最后还是调用

// Http.Server 结构体 下的 ListenAndServe() 方法

// 参数 addr, handler 主要为了赋值

// 主要方法为Handler下的ServeHTTP方法

// 负责总控

有疑问加站长微信联系(非本文作者)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值