https://note.com/mikantookotasu/n/n2f87fd0d16ad のとおりにやって
オンメモリのget/postに成功 著者はpost失敗したというが
curl http://localhost:8080/albums --include --header "Content-Type: application/json" --request "POST" --data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'をひとつながりで入れて成功した
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
var albums = []album{
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
func main() {
router := gin.Default() // ルーターの初期化
router.GET("/albums", getAlbums) // GETリクエストに対してgetAlbums関数を関連付け
router.GET("/albums/:id", getAlbumByID) // ":"はその項目がパラメータであることを示す
router.POST("/albums", postAlbums) // POSTリクエストに対してpostAlbums関数を関連付け
router.Run("localhost:8080") // ルータをhttp.Serverに接続してサーバ起動
}
// すべてのAlbumsをJSON形式で返す(GET)
func getAlbums(c *gin.Context) {
c.IndentedJSON(http.StatusOK, albums) // IndentedJSONはインデントされた形
}
// ID指定したAlbumをJSON形式で返す(GET [id])
func getAlbumByID(c *gin.Context) {
id := c.Param("id") // URLパラメータからidを取得
// リクエストされたIDに一致するアルバムを検索
for _, a := range albums {
if a.ID == id {
c.IndentedJSON(http.StatusOK, a)
return
}
}
// IDが見つからない場合は404エラーを返す
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
// 新しいアルバムを追加(POST)
func postAlbums(c *gin.Context) {
var newAlbum album
// JSONデータをバインドしてnewAlbumに関連付け
if err := c.BindJSON(&newAlbum); err != nil {
return
}
// newAlbumをalbumsに追加
albums = append(albums, newAlbum)
c.IndentedJSON(http.StatusCreated, newAlbum) // 追加したnewAlbumをJSON形式で返す レスポンスコード201
}
https://zenn.dev/ohke/articles/go-echo-how-to-use-for-backend-api echo 総論
https://qiita.com/yagi_eng/items/b06722dbd7a5652ec239 echoを使ってAPIサーバ
0 件のコメント:
コメントを投稿