0

このコマンド「go run webapp/main.go」を実行しています。その理由は、アプリ エンジンがルート ディレクトリからアプリを呼び出すため、ルートからファイルを呼び出すようにパスを変更しました。また、Go のベスト プラクティスのヒントがあれば気にしません。

└── webapp
    ├── app.yaml
    ├── assets
    │   ├── css
    │   │   └── index.css
    │   └── img
    ├── main.go
    ├── main_test.go
    └── templates
        └── index.html

些細なことが間違っている可能性があることに混乱しています。localhost:8080/css/index.css は正常に動作します。localhost:8080/static/css/index.css を提供する別のハンドラー関数もありますが、404 エラーが発生します。コマンド「go run main.go」を使用してコードから「webapp」を削除すると、すべてがスムーズに機能していました。それでも、/static/ ではなく / でどのように機能するのでしょうか。このhttps://stackoverflow.com/a/47997908/6828897の回答に見られるように、ディレクトリとして ./webapp/assets/static を提供する必要があります。http.StripPrefix も試しましたが、運もありません。

package main

import (
    "flag"
    "log"
    "net/http"
    "os"
    "path/filepath"
    "sync"
    "text/template"
)

type templateHandler struct {
    once     sync.Once
    filename string
    templ    *template.Template
}

// ServeHTTP handles the HTTP request.
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    t.once.Do(func() {
        t.templ = template.Must(template.ParseFiles(filepath.Join("webapp", "templates", t.filename)))
    })
    if err := t.templ.Execute(w, r); err != nil {
        log.Printf("Error executing template: %v", err)
        http.Error(w, "Internal server error", http.StatusInternalServerError)
    }
}

func main() {
    dir, err := os.Getwd()
    if err != nil {
        log.Printf(err.Error())
    }
    log.Printf("dir: %s", dir)

    // command flags
    var addr = flag.String("addr", ":8080", "The addr of the application.")
    flag.Parse()

    // env variables
    envPort := os.Getenv("PORT")
    if envPort != "" {
        envPort = ":" + envPort
        addr = &envPort
    }

    fs := http.FileServer(http.Dir("./webapp/assets"))
    http.Handle("/static/", fs)

    log.Printf("Listening on port %s", *addr)

    // http.Handle("/", &templateHandler{filename: "index.html"})

    if err := http.ListenAndServe(*addr, fs); err != nil {
        log.Fatal(err)
    }
}
4

1 に答える 1