如何将go-lang服务器用作文件服务器和后端逻辑服务器

时间:2015-08-29 16:09:23

标签: go

在php中我们可以托管应用程序并使用相同的服务器端口来处理后端逻辑调用。

我已经使用以下方法在go-lang中实现了这一点。有没有更好的方法来实现这一目标?。

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 个答案:

答案 0 :(得分: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)
}