我正在使用Gorilla Web Toolkit中的Mux库以及捆绑的Go http服务器.
问题是在我的应用程序中,HTTP服务器只是一个组件,它需要自行决定停止和启动.
当我称之为http.ListenAndServe(fmt.Sprintf(":%d", service.Port()), service.router)块时,我似乎无法阻止服务器运行.
我知道这在过去一直是个问题,是不是仍然如此?请问有什么新的解决方案吗?谢谢.
我看到了Mat Ryer撰写的一篇文章,内容涉及如何使用服务器类型和HTTP处理程序类型的包装程序,func(http.ResponseWriter, *http.Request)
我认为这是一种构建REST API的更优雅的方式,但是我完全迷住了使包装器正常运行的想法。我要么在编译时收到类型不匹配的错误,要么在调用时收到404的错误。
这基本上是我目前用于学习的目的。
package main
import(
"log"
"io/ioutil"
"encoding/json"
"os"
"net/http"
"github.com/gorilla/mux"
)
type Config struct {
DebugLevel int `json:"debuglevel"`
ServerPort string `json:"serverport"`
}
func NewConfig() Config {
var didJsonLoad bool = true
jsonFile, err := os.Open("config.json")
if(err != nil){
log.Println(err)
panic(err)
recover()
didJsonLoad = false
}
defer jsonFile.Close()
jsonBytes, _ := ioutil.ReadAll(jsonFile)
config := Config{}
if(didJsonLoad){
err = json.Unmarshal(jsonBytes, &config)
if(err != nil){
log.Println(err)
panic(err)
recover()
}
}
return config
} …Run Code Online (Sandbox Code Playgroud)