1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GoでHttpサーバー(簡易CGI動作)を作る

Posted at

#GoでHttpサーバと簡単なCGIプログラム

go言語でhttpサーバと簡易CGI動作確認用プログラムを作ります。
実行ファイル直下にhtmlフォルダを作成して、index.html以外の適当なHTMLファイルを作成してください。

httptest.go
package main

import (
	"fmt"
	"net/http"
)

func cgiRun(w http.ResponseWriter, r *http.Request) {
	tmp := r.URL.RawQuery
	fmt.Fprintf(w, "%s", tmp)
}
func main() {
	http.HandleFunc("/cgi", cgiRun)
	http.HandleFunc("/html/", func(w http.ResponseWriter, r *http.Request) {
		//html/にアクセスしてindex.htmlが存在しないとき
		http.ServeFile(w, r, r.URL.Path[1:])
	})
	http.ListenAndServe(":8080", nil)
}

http://localhost:8080/cgi?a=aa&b=bb にアクセスするとa=aa&b=bbが表示されます。
http://localhost:8080/html にアクセスするとhtmlフォルダ内のファイルリストが表示されます。
cgiRunの関数部分を改造すれば、簡単なCGIが組めそう

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?