LoginSignup
1
1

More than 1 year has passed since last update.

GoでミニマムなWebサーバを書く(net/http, chi)

Posted at

GoでミニマムなWebサーバを書いてみる。以下の2つを書く。

  1. net/httpのみを使った例
  2. chiでパスパラメータを取得する例

環境

  • Ubuntu 20.04 LTS (WSL2)
  • Go 1.19.3

Goはインストール済みであるとする。

1. net/http

以下を実行してプロジェクトを作成する。

mkdir go-http
cd go-http
go mod init go-http
touch main.go

main.goに以下を記述する。

// main.go
package main

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

func main() {
	http.HandleFunc("/world", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

go run main.goを実行してサーバーを立ち上げ、http://localhost:8080/world をブラウザで開く。

以下のように表示されたら成功。

Hello, "/world"

2. chi

以下を実行してプロジェクトを作成する。

mkdir go-chi
cd go-chi
go mod init go-chi
touch main.go

main.goに以下を記述する。

// main.go
package main

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Route("/{username}", func(r chi.Router) {
		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
			articleID := chi.URLParam(r, "username")
			w.Write([]byte("hello, " + articleID))
		})
	})

	http.ListenAndServe(":3000", r)
}

go run main.goを実行してサーバーを立ち上げ、http://localhost:3000/world をブラウザで開く。

以下のように表示されたら成功。

hello, world

参考資料

net/http
https://pkg.go.dev/net/http

go-chi/chi
https://github.com/go-chi/chi

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