1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

go言語のお勉強1

Last updated at Posted at 2025-03-28

経緯

転職活動してたらgoの求人が多い
元々興味はあったし、dockerとかterraformはgo製らしいし、AWSでもGCPでも使えるしで良さげ
第2言語として習得を目指す

調査から

go言語をひたすら書いて実行するだけなら
https://go.dev/tour

dockerhubにあるコンテナ確認
https://hub.docker.com/_/golang/tags

使うなら現時点での最新だと golang:1.24.1-alpine かな?

コンテナ内の状況確認
/go直下に/binと/srcあるけど中身何もない
もちろんだけどgoコマンドは動く

$ docker run -it golang:1.24.1-alpine sh
/go # ls -lah *
bin:
total 8K     
drwxrwxrwt    2 root     root        4.0K Mar  4 22:01 .
drwxrwxrwt    4 root     root        4.0K Mar  4 22:01 ..

src:
total 8K     
drwxrwxrwt    2 root     root        4.0K Mar  4 22:01 .
drwxrwxrwt    4 root     root        4.0K Mar  4 22:01 ..

/go # go version
go version go1.24.1 linux/arm64

/go # vi main.go
package main
import "fmt"
func main() {
	fmt.Println("hello world")
}

/go # go run main.go
hello

最低限実行環境を目指す

hello worldを出力するwebサーバを作りたい

dir ━━ app
    ┃  ┗ main.go
    ┃  ┗ hoge.go...
    ┃
    ┗ docker-compose.yml
    ┗ Dockerfile
    ┗ Makefile

ファイル

Makefile
clean:
	docker compose down --rmi all --volumes
upd:
	docker compose up -d
logs:
	docker compose logs -f --tail=20
docker-compose.yml
services:
  go-web:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8080:80
Dockerfile
FROM golang:1.24.1-alpine as golang
WORKDIR /app
COPY app .
RUN go build -o server main.go
CMD ["./server"]
app/main.go
package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "hello world")
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":80", nil)
}

webサーバ動かす

$ make upd
$ docker ps
CONTAINER ID   IMAGE                COMMAND      CREATED         STATUS         PORTS                                   NAMES
73248aa3cb3c   go_practice-go-web   "./server"   6 minutes ago   Up 6 minutes   0.0.0.0:8080->80/tcp, :::8080->80/tcp   go_practice-go-web-1

http://localhost:8080 にアクセスして「hello world」出ればok!

次はwebサーバ以外の用途とか、フレームワーク利用しながらgo言語の仕様を勉強していきたい

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?