Golang:如何处理和提供子域名?

时间:2017-03-14 19:50:10

标签: go

问题在于为域以及子域x,y,z(或在此示例中为博客,管理员和设计)提供服务。运行以下内容并请求blog.localhost:8080 / firefox无法找到服务器www.blog.localhost:8080。

package main

import (
    "html/template"
    "log"
    "net/http"
)

var tpl *template.Template

const (
    domain = "localhost"
    blogDomain = "blog." + domain
    adminDomain = "admin." + domain
    designDomain = "design." + domain
)


func init() {
     tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
}

func main() {


    // Default Handlers
    http.HandleFunc("/", index)

    // Blog Handlers
    http.HandleFunc(blogDomain+"/", blogIndex)

    // Admin Handlers
    http.HandleFunc(adminDomain+"/", adminIndex)

    // Design Handlers
    http.HandleFunc(designDomain+"/", designIndex)

    http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("static"))))
    http.ListenAndServe(":8080", nil) 

}

func index(res http.ResponseWriter, req *http.Request) {
    err := tpl.ExecuteTemplate(res, "index.gohtml", nil)
    if err != nil {
        log.Fatalln("template didn't execute: ", err)
    }
}

// Blog Handlers
func blogIndex(res http.ResponseWriter, req *http.Request) {
    err := tpl.ExecuteTemplate(res, "index.gohtml", nil)
    if err != nil {
        log.Fatalln("template didn't execute: ", err)
    }
}

// Admin Handlers
func adminIndex(res http.ResponseWriter, req *http.Request) {
    err := tpl.ExecuteTemplate(res, "index.gohtml", nil)
    if err != nil {
        log.Fatalln("template didn't execute: ", err)
    }
}

// Design Handlers
func designIndex(res http.ResponseWriter, req *http.Request) {
    err := tpl.ExecuteTemplate(res, "index.gohtml", nil)
    if err != nil {
        log.Fatalln("template didn't execute: ", err)
    }
}

是否可以使用标准库提供子域名?如果是这样的话?

编辑:请求localhost:8080 /工作正常

EDIT2:我编辑了/ etc / hosts以包含子域名:

127.0.0.1 blog.localhost.com
127.0.0.1 admin.localhost.com
127.0.0.1 design.localhost.com

Ping它们可以正常工作但firefox无法访问它们。

1 个答案:

答案 0 :(得分:2)

鉴于第二次编辑中的hosts文件,您可以将firefox指向例如blog.localhost.com:8080,但您还必须处理该域模式,即http.HandleFunc(blogDomain+":8080/", blogIndex)

如果这不是您想要的,您可以通过端口80(即http.ListenAndServe(":80", nil))收听,您可能需要在sudo中运行您的应用,以便它有权使用该端口,然后你的blog.localhost.com应该有用。