LoginSignup
0
0

Go でパッケージを自作して API を作ってみる:個人開発メモ

Posted at

更新:2024年2月13日
Go でパッケージを自作して API を作ってみます。

パッケージを自作して API を作成

フォルダ tmp20240213 を作って、その下に main フォルダ作ります。そして main.go を作って、 go mod init と go mod tidy します。

Macbook Terminal
% pwd
/***/tmp20240213/main
% go mod init tmp20230213/main
go: creating new go.mod: module tmp20230213/main
go: to add module requirements and sums:
	go mod tidy
% go mod tidy
% ls
go.mod	main.go
test20240202/main/main.go
package main

import (
	"net/http"
	"tmp20240213/handler"
)

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

フォルダ tmp20240213 の下に handler フォルダ作ります。そして router.go を作って、 go mod init と go mod tidy します。

Macbook Terminal
% pwd
/***/tmp20240213/handler
% go mod init tmp20240213/handler
go: creating new go.mod: module tmp20240213/handler
go: to add module requirements and sums:
	go mod tidy
% go mod tidy
% ls
go.mod		router.go
router.go
package handler

import (
	"fmt"
	"net/http"
)

func Router(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World!!!")
}

カスタムパッケージを参照するように go mod edit と go get します。

Macbook Terminal
% pwd
/***/tmp20240213/main
% go mod edit -replace=tmp20240213/handler=../handler
% go get tmp20240213/handler
go: added tmp20240213/handler v0.0.0-00010101000000-000000000000

プログラムを実行します。

Macbook Terminal 1
% pwd
/***/tmp20240213/main
% go run .
Macbook Terminal 2
% curl http://localhost:3000
Hello World!!!

以上です。

参考

Go 言語でパッケージを自作して、それを呼び出してみる

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