You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Go HTTP服务将/api路径作为默认服务路径

解决方案

有两种常用实现方式,你可以按需选择:

方案1:在根路由下统一挂载/api前缀的子路由

这种方案适合你同时还需要提供/api之外的其他路由的场景:

package main

import (
	"net/http"
)

func main() {
	// 先创建根路由复用器
	mux := http.NewServeMux()

	// 创建/api专属的子路由复用器,里面的路由不需要重复写/api前缀
	apiMux := http.NewServeMux()
	// 示例接口,实际访问路径为 http://localhost:8000/api/hello
	apiMux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello from api"))
	})

	// 将子路由挂载到根路由的/api前缀下
	// 注意:路径末尾的/不能省略,否则无法匹配/api下的子路径
	mux.Handle("/api/", http.StripPrefix("/api", apiMux))

	// 启动服务
	http.ListenAndServe(":8000", mux)
}

如果不需要其他前缀的路由,也可以直接把业务路由挂在/api/路径下,不需要单独拆分子路由复用器。

方案2:全局强制所有请求必须匹配/api前缀

如果你的服务所有接口都要放在/api下,不提供任何前缀之外的接口,可以直接给全局处理器加前缀过滤:

package main

import (
	"net/http"
)

func main() {
	mux := http.NewServeMux()
	// 直接写业务路由即可,不需要加/api前缀
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello from api"))
	})

	// 封装全局处理器,自动校验和剥离/api前缀
	server := http.Server{
		Addr: ":8000",
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// 校验请求路径是否以/api开头
			if len(r.URL.Path) < 4 || r.URL.Path[:4] != "/api" {
				http.NotFound(w, r)
				return
			}
			// 剥离/api前缀后交给业务路由处理
			r.URL.Path = r.URL.Path[4:]
			mux.ServeHTTP(w, r)
		}),
	}

	server.ListenAndServe()
}

两种方案最终效果一致:原来的http://localhost:8000/xxx会返回404,只有http://localhost:8000/api/xxx能正常匹配到业务路由。

内容的提问来源于stack exchange,提问作者Aju George Jacob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:48:04