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))
}
相关推荐
CodeSheep9 分钟前
正式确认了,海康已经全员邮件通知,试行965工作模式
前端·后端·程序员
会编程的吕洞宾11 分钟前
Spring AI 多轮对话总失忆?ChatMemory 持久化实战
java·人工智能·经验分享·后端·spring
阮靓仔15 分钟前
【Spring Boot】Spring Boot 集成 Caffeine 缓存
spring boot·后端·缓存
青山木21 分钟前
JVM 内存区域全解:堆、栈、方法区、直接内存的职责划分与常见报错
java·开发语言·jvm·后端·内存·堆·方法区
FYKJ_20101 小时前
django乌鲁木齐市二手房房价可视化平台84751-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·信息可视化·django·课程设计
FYKJ_20103 小时前
springboot高校实验室综合管理系统86531-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·spring·课程设计
parade岁月4 小时前
没有称手工具了怎么办?搓一个!AI 时代顺手造了个单文件 Mermaid ER 查看器
数据库·后端
金銀銅鐵9 小时前
类实例里还有什么——putfield、getfield 与对象传递
java·jvm·后端
皮皮林55110 小时前
你还在使用 WebSocket 实现实时消息推送吗?
后端
码事漫谈10 小时前
token账单到底要怎么看
后端