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))
}
相关推荐
量化分析码农29 分钟前
股票历史数据的复权参数对照:多级别返回的字段与数值差异
java·javascript·后端
程序员cxuan1 小时前
讲真,智能路由这事儿,还得看基元律动
人工智能·后端·程序员
vaskilab2 小时前
Schema 全绿,Agent 却把参数编造了
后端
Java与AI落地2 小时前
Spring AI 上手:给现有 Java 服务加一个能用的 AI 接口
后端
Swot2 小时前
SvelteKit 数据流研究:`+page.js` 和 `+page.server.js` 到底谁在跑,数据又去了哪儿
前端·后端
一条Go2 小时前
历史告警归档:为什么"删掉主库行"是最后一步
后端·架构·github
nice_lcj5202 小时前
【从零理解 Spring AI · 16】Agent 与工作流:什么该写死,什么该让模型决定
java·人工智能·后端·spring ai·ai应用开发
梦醒江南2 小时前
Agent 调工具报 504 之后:测试如何设计网络抖动下的幂等与补偿验证?
后端·agent·ai编程
站大爷IP2 小时前
Python的内存分析把我坑惨了,原来tracemalloc和memory_profiler的区别这么大
后端
Captaincc2 小时前
转译:《软件工程师现在该怎么办》
前端·后端·ai编程