在Go中将https://www.domain.com重定向到https://domain.com

时间:2016-08-01 14:02:29

标签: go

现在我正在将http://的所有内容重定向到https://,如下所示:

func main() {
    router := httprouter.New()
    router.POST("/api/register", toHandle(register))
    router.GET("/api/token/verify/:token", toHandle(verifyToken))
    router.GET("/api/availability/username/:username", toHandle(usernameAvailability))
    router.POST("/api/search/cities", toHandle(searchCities))
    router.POST("/api/user", toHandle(createUser))
    router.GET("/api/user/:id", toHandle(userById))
    router.POST("/api/login", toHandle(login))
    router.NotFound = &serveStatic{}

    certificate := "/srv/ssl/ssl-bundle.crt"
    privateKey := "/srv/ssl/private.key"

    go func() {
        if err := http.ListenAndServe(":80", http.HandlerFunc(redirectTLS)); err != nil {
            log.Fatalf("ListenAndServe error: %v", err)
        }
    }()
    log.Fatal(http.ListenAndServeTLS(":443", certificate, privateKey, router))  
}

func redirectTLS(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, "https://domain.com"+r.RequestURI, http.StatusMovedPermanently)
}

type serveStatic struct{}

func (df *serveStatic) ServeHTTP(w http.ResponseWriter, req *http.Request) {

    path := filepath.FromSlash(config.DirRoot + req.URL.Path)
    data, err := ioutil.ReadFile(path)

    var contentType string

    if err == nil {

        if strings.HasSuffix(path, ".css") {
            contentType = "text/css"
        } else if strings.HasSuffix(path, ".html") {
            contentType = "text/html"
        } else if strings.HasSuffix(path, ".js") {
            contentType = "application/javascript"
        } else if strings.HasSuffix(path, ".png") {
            contentType = "image/png"
        } else if strings.HasSuffix(path, ".jpg") {
            contentType = "image/jpeg"
        } else if strings.HasSuffix(path, ".ico") {
            contentType = "image/x-icon"
        } else {
            contentType = "text/plain"
        }

        // spew.Dump(path)

        w.Header().Add("Content-Type", contentType)

        // Prefix files with gz such as "all.gz.js" if you want gzipped files to be served.
        if strings.Contains(path, ".gz.") {
            w.Header().Add("Content-Encoding", "gzip")
        }

        w.Write(data)

    } else {

        path := filepath.FromSlash(config.DirRoot + "/index.html")
        data, err = ioutil.ReadFile(path)
        contentType = "text/html"

        if err == nil {
            w.Header().Add("Content-Type", contentType)
            w.Write(data)
        } else {
            w.WriteHeader(404)
            w.Write([]byte("404 - " + http.StatusText(404)))
        }

    }
}

但是这不会将https://www.domain.com重定向到https://domain.com,它只会将http://domain.com重定向到https://domain.com

我怎样才能检测以https://www.domain.com开头的请求?

有关如何实现这一目标的任何建议?

0 个答案:

没有答案