2017-03-14 6 views
0

この問題は、サブドメインx、y、z(またはこの例ではブログ、管理者、デザイン)と同様にドメインにサービスを提供しています。次のコマンドを実行して、blog.localhost:8080/firefox cantがサーバーwww.blog.localhost:8080を見つけたとき。Golang:サブドメインの処理方法と提供方法

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) 
    } 
} 

標準ライブラリを使用してサブドメインを提供できますか?もしそうなら、どのように?

EDIT:ローカルホストの要求:8080 /正常に動作します

EDIT2:私はサブドメインを含めるように/ etc/hostsファイルを編集した:それらへのping

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

が正常に動作しますが、Firefoxはそれらに達することができません。

+0

"firefox cant find the server" --- DNSにありますか?どのIPに解決されますか?正確に「見つけることができない」とはどういう意味ですか? – zerkms

+1

"www.blog.localhost"をどうやって解決しようとしていますか?ローカルDNSサーバを実行していますか、またはhostsファイルに可能なすべてのサブドメインを入力しましたか? – JimB

+0

@zerkms私は、ローカルのVMマシンでFirefoxを実行しています。 127.0.0.1:8080/作品。 blog.127.0.0.1:8080はありません。 Firefoxは状態コードを与えません。ネットワークを調べると応答は空白です。 – Conner

答えて

2

2回目の編集でhostsファイルが指定されている場合は、firefoxにblog.localhost.com:8080を指定できますが、そのドメインパターンも処理する必要があります。つまり、http.HandleFunc(blogDomain+":8080/", blogIndex)です。

それはあなたがあなたの代わりにポート80すなわちhttp.ListenAndServe(":80", nil)に聴くことができます欲しいものはない場合、あなたはそれがそのポートを使用する権限を持つようにsudoでアプリケーションを実行する必要があるかもしれません、そして、あなたのblog.localhost.comは動作するはずです。

+0

私はあなたの最初のソリューションを実装し、それは完全に動作します!私はServeMuxとVirtual Hostingについてもっと読む必要があります。ありがとうございました! – Conner

関連する問題