gpt4 book ai didi

go - 创建 http 处理程序

转载 作者:IT王子 更新时间:2023-10-29 02:17:23 24 4
gpt4 key购买 nike

我有 main.go 并且我想更改为更好的结构(类似 main2.go ),因为如果项目会长大,对于新开发人员来说代码将不容易解释。

我的想法是创建一个名为 handle 的文件夹并将文件 handle.go 与所有 handles 方法放入其中,我发现的问题是我不知道如何设置 http.HandleFunc("/Handler.go 中的 R1", HandlerOne)http.HandleFunc("/R2", HandlerTwo) 并从 main2.go 调用它。

主.go

package main

import (
"fmt"
"net/http"

)

func HandlerOne(w http.ResponseWriter, req *http.Request) {
fmt.Println("message one")
}

func HandlerTwo(w http.ResponseWriter, req *http.Request) {
fmt.Println("message two")
}

func main() {

http.HandleFunc("/R1", HandlerOne)
http.HandleFunc("/R2", HandlerTwo)

err := http.ListenAndServe(":9998", nil)

if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}

main2.go

package main

import (
"fmt"
"net/http"

)


func main() {

// Call handle.go

err := http.ListenAndServe(":9998", nil)

if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}

处理.go

package handle

import (
"fmt"
"net/http"
)

func HandlerOne(w http.ResponseWriter, req *http.Request) {
fmt.Println("message one")
}

func HandlerTwo(w http.ResponseWriter, req *http.Request) {
fmt.Println("message two")
}

注意:感谢@kluyg 的回答。我要补充一点,我想要的似乎我解释得不是很好:

我想要的是在
中创建一个函数handle.go 我可以在哪里放置句柄的所有映射。即一些类似的

func SetUpMapping(...){
http.HandleFunc("/R1", HandlerOne)
http.HandleFunc("/R2", HandlerTwo)

..... //Others mapping
http.HandleFunc("/RN", HandlerN)

}

其中 ... 应该是对 http 的引用,但这是一个包,主要类似于代码 3

代码 3

main2.go

package main

import (
"fmt"
"net/http"
"handlers/handle"

)


func main() {

// Call handle.go
handle.SetUpMapping(...) // i dont know what parameter put here
err := http.ListenAndServe(":9998", nil)

if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}

最佳答案

我获取了你的代码并将 ma​​in2.go 放入 $GOPATH/handlers 文件夹,并将 handle.go 放入 $GOPATH/handlers/handle 文件夹。然后我把ma​​in2.go改成了

package main

import (
"fmt"
"net/http"

"handlers/handle"
)

func main() {

// Call handle.go

http.HandleFunc("/R1", handle.HandlerOne)
http.HandleFunc("/R2", handle.HandlerTwo)

err := http.ListenAndServe(":9998", nil)

if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}

它编译并运行良好。我相信这就是您要求的。

更新

好的,你可以将它添加到你的 handle.go 中

func SetUpMapping() {
http.HandleFunc("/R1", HandlerOne)
http.HandleFunc("/R2", HandlerTwo)

..... //Others mapping
http.HandleFunc("/RN", HandlerN)

}

然后在 main2.go 中

package main

import (
"fmt"
"net/http"
"handlers/handle"
)


func main() {

// Call handle.go
handle.SetUpMapping() // you don't need any parameters here
err := http.ListenAndServe(":9998", nil)

if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}

关于go - 创建 http 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22993085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com