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))
}
相关推荐
mldong6 分钟前
Go 开发者也有自己的轻量工作流引擎了:go get 一行,5 分钟跑通一条审批流
后端·go
BingoGo6 小时前
PHP clone 之后,为什么改副本会影响原对象?
后端·php
JaguarJack6 小时前
PHP clone 之后,为什么改副本会影响原对象?
后端·php·服务端
小灰灰搞电子7 小时前
Rust+Slint 实现动态消息提示框源码分享
开发语言·后端·rust
小奏技术7 小时前
10 MB 的 Postman 替代品,启动不到 1 秒
后端
东风破_7 小时前
Text2SQL :用自然语言操作 SQLite 数据库
人工智能·后端
IT_陈寒11 小时前
Python的多线程就是个假把式,我算是体验到了
前端·人工智能·后端
码事漫谈11 小时前
如果 AI 要圈养人类,它可能不需要笼子
后端
newerp12 小时前
Golang 调度循环:Go runtime 如何永不停歇地找人干活
后端·程序员·go