LoginSignup
1
3

More than 1 year has passed since last update.

Golangでログイン機能を実装する。(Step1:APIで値を返却する)

Last updated at Posted at 2022-08-10

はじめに

前回の記事に付随する記事となります。
前回の記事まででは、UIコンポーネントを利用してログイン機能のデザインのみを作成しました。API疎通するためのバックエンドのシステムを作成します。本記事ではGolangでAPIを作成します。

環境情報

PC:M2 Mac Book Air
Golang:go version go1.19 darwin/arm64

HelloWorld出力

本記事では、go fiberを利用してAPIを作成します。fiberを利用しHelloWorldを出力します。

ディレクトリ構成
~/go/src/fiber_login$ tree
.
├── go.mod
├── go.sum
└── main.go

0 directories, 3 files
go.mod
module fiber_login

go 1.19

require github.com/gofiber/fiber/v2 v2.36.0

require (
	github.com/andybalholm/brotli v1.0.4 // indirect
	github.com/klauspost/compress v1.15.0 // indirect
	github.com/valyala/bytebufferpool v1.0.0 // indirect
	github.com/valyala/fasthttp v1.38.0 // indirect
	github.com/valyala/tcplisten v1.0.0 // indirect
	golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 // indirect
)

main.go
package main

import (
	"fmt"
	"log"

	"github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()
    app.Get("/", func(c *fiber.Ctx) error {
        fmt.Println("🥉 Last handler")
        return c.SendString("Hello, go fiber 👋!")
    })
    
    log.Fatal(app.Listen(":1323"))
}
main.go実行
~/go/src/fiber_login$ go run main.go 

 ┌───────────────────────────────────────────────────┐ 
                    Fiber v2.36.0                    
                http://127.0.0.1:1323               │ 
        (bound on host 0.0.0.0 and port 1323)        
                                                     
  Handlers ............. 2  Processes ........... 1  
  Prefork ....... Disabled  PID ............. 64530  
 └───────────────────────────────────────────────────┘ 

→localhost:1323でListen状態を確認します。

スクリーンショット 2022-08-10 19.48.50.png
→ここまでできれば、肩慣らし完了です。

ログイン機能の前提

本記事では、機能の実装内容を絞りプログラミングしていきます。
下記内容は今後の記事でアップデートしていきます。

実装しない内容
Validationチェックなし
エラーハンドリングなし
DB疎通なし
JWTの生成なし
APIの仕様
エンドポイント:/api/login
メソッド:POST通信
リクエストBody:
{
   user_id:"",
   password:""
}

レスポンス:ステータスコード:200
{
}

→リクエストBodyの値は受け取りますが、リクエストをそのままオウム返しします。

コードの実装

ディレクトリ構成
~/go/src/fiber_login$ tree -I tmp 
.
├── go.mod
├── go.sum
├── main.go
└── model
    └── user.go

1 directory, 4 files
main.go
package main

import (
	"fiber_login/model"
	"fmt"
	"log"

	"github.com/gofiber/fiber/v2"
)

func main() {
	app := fiber.New()
	app.Use(cors.New())
	app.Post("/api/login", func(c *fiber.Ctx) error {

		var body model.User
		c.BodyParser(&body)

		// Userの中身を確認
		fmt.Println(body)

		// json
		return c.Status(fiber.StatusOK).JSON(body)
	})

	log.Fatal(app.Listen(":1323"))
}
model/user.go
package model

type User struct {
	UserID   string `json:"user_id"`
	Password string `json:"password"`
}

■実行結果
スクリーンショット 2022-08-11 13.26.09.png
はい、これで完成。次回はフロントの実装に写って行きます!!!

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