0
0

More than 1 year has passed since last update.

Go:健康データの簡易APIサーバーの作り始め

Posted at

作成:2023年1月11日

体重など健康データを保存するアプリとバックエンドを作ってみたく、Go でバックエンドを作成する為の情報収集と練習の為に、バックエンドをシンプルなGo言語で書いてみます。

事前準備

Postmanをインストールしておきます(参考リンク

簡易APIサーバー

GETするコードです(githubのコード置き場:qiita20210111

main.go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

type HealthData struct {
	UserID      int       `json:"user_id"`
	Weifgt   float64   `json:"weight"`
	Date time.Time `json:"date"`
}

var health_data = []HealthData{{
	UserID:      1,
	Weifgt:   55.5,
	Date: time.Now(),
}, {
	UserID:      2,
	Weifgt:   66.6,
	Date: time.Now(),
}, {
	UserID:      3,
	Weifgt:   77.7,
	Date: time.Now(),
}}

func main() {
	handler1 := func(w http.ResponseWriter, r *http.Request) {
		var buf bytes.Buffer
		enc := json.NewEncoder(&buf)
		if err := enc.Encode(&health_data); err != nil {
			log.Fatal(err)
		}
		fmt.Println(buf.String())

		_, err := fmt.Fprint(w, buf.String())
		if err != nil {
			return
		}
	}

	// GET /tasks
	http.HandleFunc("/health_data", handler1)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

実行します。

%go run main.go

ポストマンでGETできていることが確認できました。
image.png

今後、各種機能追加を進めます。

参考
[初心者向け] Golang でシンプルな JSON API を作る
GoでCRUD処理のREST APIを作ろう〜Reactを添えて〜
   タスク管理アプリ、Go、React、MySQL、Docker
Goで超簡単API

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