0
0

Goで簡易WEBサーバを作成

Posted at

記事概要

簡易WEBサーバを作成。

スクリプト

package main

import (
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
)

func main() {
	port := "8080"  // デフォルトのポート番号
	ip := "0.0.0.0" // IP

	// コマンドライン引数からポート番号を取得
	if len(os.Args) > 1 {
		port = os.Args[1]
	}

	// / へのアクセスが来た時に dist フォルダ内のコンテンツを表示するハンドラを設定
	http.Handle("/", http.FileServer(http.Dir("./dist")))

	// /hoge へのアクセスが来た時にリダイレクトするハンドラを設定
	http.HandleFunc("/hoge", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "http://localhost:3000", http.StatusFound)
	})

	// /piyo へのアクセスが来た時にリバースプロキシとして転送するハンドラを設定
	filesProxy := httputil.NewSingleHostReverseProxy(&url.URL{
		Scheme: "http",
		Host:   "localhost:5001",
	})
	http.Handle("/piyo", http.StripPrefix("/", filesProxy))

	addr := ip + ":" + port
	log.Print("サーバーを起動 => " + "http://" + addr)
	// サーバーを起動し、指定したIPアドレスとポート番号で待機
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		log.Fatal("サーバーの起動に失敗しました: ", err)
	}
}

説明

結構忘れていたので、ChartGPTに手伝ってもらった。

  1. distフォルダの下を見ている。
  2. http://localhost/hogehttp://localhost:3000にリダイレクト。
  3. http://localhost/piyohttp://localhost:5001/piyoにリバースプロキシ。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0