golang HTTP (一) ListenAndServe NewServeMux http.HandleFunc

  • 请求是长路径优先。如果没有匹配到,所有的请求都会匹配到/
  • http.ListenAndServe(":8080", nil)第二个参数为nil,表示使用默认的路由。如果第三方代码也注册这个请求,会导致网络被劫持
  • http.NewServeMux()自定义Mux才是生产环境使用的。
go 复制代码
package main

import (
        "net/http"
        "fmt"
)

func main(){
        http.HandleFunc("/",indexHandle)
        http.HandleFunc("/login", loginHandle)
        err := http.ListenAndServe(":8080", nil)
        fmt.Println(err)

}

func indexHandle(res http.ResponseWriter, req *http.Request){
        path := req.URL.Path

        if path != "/" {
                fmt.Fprintln(res, "Not found")
        }
        fmt.Fprintln(res,"index")
}

func loginHandle(res http.ResponseWriter, req *http.Request){
        fmt.Fprintln(res,"login")
}
go 复制代码
package main

import "net/http"

func main() {
        // *http.ServeMux
        newMux := http.NewServeMux()
        newMux.HandleFunc("/", Index)

        _ = http.ListenAndServe(":8080", newMux)
}

func Index(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("hello world"))
}
scss 复制代码
package main

import (
        "net/http"
)

func main(){
        // *net.ServerMux
        serveMux := http.NewServeMux()
        serveMux.HandleFunc("/",Index)
        serveMux.HandleFunc("/login",Login)
        http.ListenAndServe(":8080", serveMux)
}

func Index(w http.ResponseWriter,r *http.Request){
        if r.URL.Path != "/" {
                http.NotFound(w,r)
                return
        }
        html := `
        <h1> 欢迎来到博客网</h1>
        <p>首页<a href="/"> </a></p>
        <p>登录<a href="/login"> </a></p>
        `

        w.Write([]byte(html))
}

func Login(w http.ResponseWriter, r *http.Request){
        html := `
        <h1><a href="/">回到首页</a><h1>
        <p><input type="text"/></p>
        `
        w.Write([]byte(html))
}
相关推荐
一条小小yu7 小时前
Spring IoC的理解
java·后端·spring
茉莉玫瑰花茶8 小时前
GO [ 方法 ]
开发语言·后端·golang
Wx-bishekaifayuan8 小时前
django个性化旅游路线推荐平台49005-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Eric_见嘉8 小时前
在职前端 Skill 和 MCP 分享
前端·后端·agent
孟健10 小时前
出海开发者资金合规:从港卡结汇到完税申报实操
后端·架构
乌暮10 小时前
深入理解 Java 泛型:把「万能盒子」用对、用稳
java·开发语言·后端·学习
架构技术专栏10 小时前
Skill 有效性与稳定性评估:用对照、重复与证据判断价值
后端
拔剑纵狂歌11 小时前
ClickHouse system.query_log 字段详解与排障实践
后端·clickhouse·1024程序员节
再吃一根胡萝卜11 小时前
把本地 RAG 问答做"准":多轮指代消解 + 云端语义向量 + TXT 章节切分
后端
怕浪猫11 小时前
2026年9月面18个后端
后端·面试·github