英文:
How to use go-lang server as both file server and back-end logic server
问题
在PHP中,我们可以托管应用程序并使用相同的服务器和端口来处理后端逻辑调用。
我在Go语言中使用了以下方法来实现这一点。有没有更好的方法来实现这个?
r := mux.NewRouter()
http.HandleFunc("/dependencies/", DependencyHandler) //文件服务
http.HandleFunc("/portals/", PortalsHandler) //文件服务
r.HandleFunc("/registeruser", UserRegistrationHandler)
r.HandleFunc("/deleteuser/{username}", DeleteUserHandler)
http.Handle("/",r)
s := &http.Server{
Addr: ":" + strconv.Itoa(serverConfigs.HttpPort),
Handler: nil,
ReadTimeout: time.Duration(serverConfigs.ReadTimeOut) * time.Second,
WriteTimeout: time.Duration(serverConfigs.WriteTimeOut) * time.Second,
MaxHeaderBytes: 1 << 20,
}
英文:
In php we can host application and use the same server,port to handle the back-end logic calls.
I've used the following way to achieve this in go-lang. Is there a better way to achieve this?.
r := mux.NewRouter()
http.HandleFunc("/dependencies/", DependencyHandler) //file serving
http.HandleFunc("/portals/", PortalsHandler) //file serving
r.HandleFunc("/registeruser", UserRegistrationHandler)
r.HandleFunc("/deleteuser/{username}", DeleteUserHandler)
http.Handle("/",r)
s := &http.Server{
Addr: ":" + strconv.Itoa(serverConfigs.HttpPort),
Handler: nil,
ReadTimeout: time.Duration(serverConfigs.ReadTimeOut) * time.Second,
WriteTimeout: time.Duration(serverConfigs.WriteTimeOut) * time.Second,
MaxHeaderBytes: 1 << 20,
}
答案1
得分: 2
你可以使用mux路由器来提供静态文件和实现后端逻辑处理程序。可以使用PathPrefix()和StripPrefix()来实现:
package main
import (
"github.com/gorilla/mux"
"log"
"net/http"
)
func main() {
r := mux.NewRouter()
r.PathPrefix("/portals/").Handler(http.StripPrefix("/portals/", http.FileServer(http.Dir("./portals/"))))
r.PathPrefix("/dependencies/").Handler(http.StripPrefix("/dependencies/", http.FileServer(http.Dir("./dependencies/"))))
r.HandleFunc("/registeruser", UserRegistrationHandler)
r.HandleFunc("/deleteuser/{username}", DeleteUserHandler)
http.Handle("/", r)
log.Println("Listening...")
http.ListenAndServe(":8000", r)
}
英文:
You can serve static files and implement your backend logic handlers with mux router. Use PathPrefix() and StripPrefix() for that:
package main
import (
"github.com/gorilla/mux"
"log"
"net/http"
)
func main() {
r := mux.NewRouter()
r.PathPrefix("/portals/").Handler(http.StripPrefix("/portals/", http.FileServer(http.Dir("./portals/"))))
r.PathPrefix("/dependencies/").Handler(http.StripPrefix("/dependencies/", http.FileServer(http.Dir("./dependencies/"))))
r.HandleFunc("/registeruser", UserRegistrationHandler)
r.HandleFunc("/deleteuser/{username}", DeleteUserHandler)
http.Handle("/", r)
log.Println("Listening...")
http.ListenAndServe(":8000", r)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论