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))
}
相关推荐
再吃一根胡萝卜5 小时前
从最左前缀到地址索引:我对 MySQL 索引的一次完整复盘
后端
郡杰5 小时前
Spring Boot 请求流转与 RESTful
后端
再吃一根胡萝卜5 小时前
Redis 都有哪些用处?都会用在什么地方?
后端
再吃一根胡萝卜5 小时前
分布式与分布式锁:从访问量到数据一致性
后端
再吃一根胡萝卜5 小时前
分库分表:为什么我不建议一上来就分表
后端
再吃一根胡萝卜5 小时前
MySQL 慢查询优化:从定位到根治的完整思路
后端
Nturmoils6 小时前
订单查询丢数据,查了半天原来是 WHERE 惹的祸
数据库·后端
叫我Paul就好6 小时前
自从用上 Agents View 之后, 我的心力交瘁感消失了
后端
SamDeepThinking7 小时前
组合还是继承?我在项目里主要看这两个判断
java·后端·面试
niuju7 小时前
一种基于 Agent 的需求规范化闭环实践:让合规与规范内建于流程
后端