go言語インストール

https://go.dev/dl/

ファイルサーバを作ってみる

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello from Go server!")
    })

    // ファイルサーバーを作成
    fileServer := http.FileServer(http.Dir(".")) 

    // ルート "/" にファイルサーバーを配置
    http.Handle("/", fileServer)

    fmt.Println("Server started on port 8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}
`http.FileServer(http.Dir("."))` を使用して、現在のディレクトリにあるすべてのファイルへのアクセスを許可するファイルサーバーを作成しました。

`http.Handle("/", fileServer)` を使用して、サーバーのルート "/" にファイルサーバーを配置しました。

これで、`http://localhost:8080/some.css` だけでなく、`http://localhost:8080/images/image.jpg` や `http://localhost:8080/scripts/script.js` のように、サーバー内の任意のファイルにアクセスできるようになります。

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS