tkancf.com

curlでJSONを簡単に送れるようになったらしいので試した

投稿日: 2025-02-22 16:16

curlでJSONを簡単に送れるようになったらしいので試した

知ったきっかけ↓

--jsonオプションについて

以下manページから引用
要するにheaderオプションとかを設定してくれるショートカット的なオプションらしい

--json <data>
(HTTP) Sends the specified JSON data in a POST request to the HTTP server. --json works as a shortcut for passing on these three options:
--data [arg]
--header "Content-Type: application/json"
--header "Accept: application/json"

実際に試してみる

goで簡単なAPIを作ってcurlでPOSTリクエストを送ってみる

package main
import (
"log"
"fmt"
"encoding/json"
"github.com/gofiber/fiber/v2"
)
type RequestData struct {
Name string `json:"name"`
Message string `json:"message"`
}
type ResponseData struct {
Status string `json:"status"`
Message string `json:"message"`
}
func main() {
app := fiber.New(fiber.Config{
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Post("/api", handlePost)
log.Fatal(app.Listen(":8000"))
}
func handlePost(c *fiber.Ctx) error {
var request RequestData
if err := c.BodyParser(&request); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "Failed to parse request body",
})
}
response := ResponseData{
Status: "success",
Message: fmt.Sprintf("Name: %s Message: %s", request.Name, request.Message),
}
return c.JSON(response)
}

いい感じ

Terminal window
❰tkan❙~/src/github.com/tkancf/json-test❱✔≻ curl --json '{"name":"tkancf", "message":"こんにちは"}' localhost:8000/api
{"status":"success","message":"Name: tkancf Message: こんにちは"}⏎

いつの間に増えたのか