Support subdir in baseurl.

Mainly this was a change to helpers.MakePermalink, but to get the local server to run correctly,
we needed to redirect the path of the request from /foo to /.  In addition, I added tests for the
server's code for fixing up the base url with different config file & CLI options.
This commit is contained in:
Nate Finch 2014-08-22 07:59:59 -04:00 committed by spf13
parent 4b979b17cc
commit a31edb3388
5 changed files with 139 additions and 21 deletions

View file

@ -17,6 +17,7 @@ import (
"fmt"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
@ -54,10 +55,6 @@ func init() {
func server(cmd *cobra.Command, args []string) {
InitializeConfig()
if BaseUrl == "" {
BaseUrl = "http://localhost"
}
if cmd.Flags().Lookup("disableLiveReload").Changed {
viper.Set("DisableLiveReload", disableLiveReload)
}
@ -66,10 +63,6 @@ func server(cmd *cobra.Command, args []string) {
viper.Set("Watch", true)
}
if !strings.HasPrefix(BaseUrl, "http://") {
BaseUrl = "http://" + BaseUrl
}
l, err := net.Listen("tcp", ":"+strconv.Itoa(serverPort))
if err == nil {
l.Close()
@ -85,11 +78,11 @@ func server(cmd *cobra.Command, args []string) {
viper.Set("port", serverPort)
if serverAppend {
viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/")+":"+strconv.Itoa(serverPort))
} else {
viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/"))
BaseUrl, err := fixUrl(BaseUrl)
if err != nil {
jww.ERROR.Fatal(err)
}
viper.Set("BaseUrl", BaseUrl)
build(serverWatch)
@ -110,10 +103,57 @@ func serve(port int) {
jww.FEEDBACK.Printf("Web Server is available at %s\n", viper.GetString("BaseUrl"))
fmt.Println("Press ctrl+c to stop")
http.Handle("/", http.FileServer(http.Dir(helpers.AbsPathify(viper.GetString("PublishDir")))))
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
fileserver := http.FileServer(http.Dir(helpers.AbsPathify(viper.GetString("PublishDir"))))
u, err := url.Parse(viper.GetString("BaseUrl"))
if err != nil {
jww.ERROR.Fatalf("Invalid BaseUrl: %s", err)
}
if u.Path == "" || u.Path == "/" {
http.Handle("/", fileserver)
} else {
http.Handle(u.Path+"/", http.StripPrefix(u.Path+"/", fileserver))
}
err = http.ListenAndServe(":"+strconv.Itoa(port), nil)
if err != nil {
jww.ERROR.Printf("Error: %s\n", err.Error())
os.Exit(1)
}
}
func fixUrl(s string) (string, error) {
useLocalhost := false
if s == "" {
s = viper.GetString("BaseUrl")
useLocalhost = true
}
if !strings.HasPrefix(s, "http://") {
s = "http://" + s
}
u, err := url.Parse(s)
if err != nil {
return "", err
}
if serverAppend {
if useLocalhost {
u.Host = fmt.Sprintf("localhost:%d", serverPort)
return u.String(), nil
}
host := u.Host
if strings.Contains(host, ":") {
host, _, err = net.SplitHostPort(u.Host)
if err != nil {
return "", fmt.Errorf("Failed to split BaseUrl hostpost: %s", err)
}
}
u.Host = fmt.Sprintf("%s:%d", host, serverPort)
return u.String(), nil
}
if useLocalhost {
u.Host = "localhost"
}
return u.String(), nil
}