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))
}
相关推荐
颜酱3 小时前
07 | 把字段与指标同步到 Qdrant(生成阶段)
前端·人工智能·后端
Larcher3 小时前
从“加载模型”界面到端侧推理:拆解一个 React + WebGPU 大模型 Demo
javascript·后端
Larcher4 小时前
从状态快照到惰性初始化:读懂 React useState 的三个关键场景
javascript·人工智能·后端
lazy H4 小时前
Git clone 怎么用?克隆项目及常见问题完整教程
大数据·git·后端·学习·搜索引擎·github
wang09074 小时前
自己动手写一个spring之aop_1
java·后端·spring
神奇小汤圆4 小时前
IDEA 运行报 Command line is too long?别慌,两招搞定(附原理)
后端
SelectDB5 小时前
Apache Doris 4.1 全面增强 Iceberg:支持 UPDATE、MERGE INTO 与 Iceberg V3
后端
Conan在掘金5 小时前
ArkTS 进阶之道(13):ForEach 循环渲染边界——为啥 build 里不能写 for 循环
后端
妙码生花5 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(四十一):增加管理员账号管理接口
后端·go·gin
用户0678260743275 小时前
APP版本管理全链路(后端设计)
后端