You need to enable JavaScript to run this app. 如何在Golang中创建简单路由?新手API开发求助
优惠活动
大模型
产品
解决方案
定价
更多

如何在Golang中创建简单路由?新手API开发求助

在Golang中创建简单路由的正确方式

首先纠正你代码里的几个关键错误:

  • 函数参数类型顺序错误:应该是w http.ResponseWriter(响应写入器)在前,r *http.Request(请求对象)在后,你搞反了两者的类型和顺序。
  • 响应写入语法错误:正确写法是w.Write([]byte("Hello world")),不是w Write.byte[]这种不符合Go语法的格式。

基础单路由实现

用Go标准库net/http就能快速实现简单路由,不需要额外依赖。下面是完整的可运行示例:

package main

import (
    "net/http"
)

// 定义处理函数:参数必须是http.ResponseWriter和*http.Request
func helloHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello world"))
}

func main() {
    // 注册路由:将路径"/hello"与处理函数绑定
    http.HandleFunc("/hello", helloHandler)
    // 启动HTTP服务,监听本地8080端口
    // 第二个参数为nil表示使用默认的ServeMux(路由多路复用器)
    http.ListenAndServe(":8080", nil)
}

运行这段代码后,访问http://localhost:8080/hello就能看到"Hello world"的响应。

多路由扩展

如果需要多个路由,只需注册更多的处理函数即可:

func goodbyeHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Goodbye!"))
}

func main() {
    http.HandleFunc("/hello", helloHandler)
    http.HandleFunc("/goodbye", goodbyeHandler)
    http.ListenAndServe(":8080", nil)
}

限制请求方法

如果需要限定路由只接受特定的HTTP方法(比如仅GET),可以在处理函数里判断请求方法:

func helloHandler(w http.ResponseWriter, r *http.Request) {
    // 只允许GET请求
    if r.Method != http.MethodGet {
        // 返回405状态码(方法不允许)
        w.WriteHeader(http.StatusMethodNotAllowed)
        w.Write([]byte("Method not allowed"))
        return
    }
    w.Write([]byte("Hello world"))
}

内容的提问来源于stack exchange,提问作者Saulo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:23:16