curlでJSONを簡単に送れるようになったらしいので試した
知ったきっかけ↓
curlでJSONを簡単に送れるようになったと聞いて。 pic.twitter.com/5KIYAmjgZm
— うらがみ⛄ (@backpaper0) February 22, 2025
--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)
}
いい感じ
❰tkan❙~/src/github.com/tkancf/json-test❱✔≻ curl --json '{"name":"tkancf", "message":"こんにちは"}' localhost:8000/api
{"status":"success","message":"Name: tkancf Message: こんにちは"}⏎
いつの間に増えたのか
- リリースノート: curl - Changes in 7.82.0
- Changes in 7.82.0
- 該当のPR: curl —json by bagder · Pull Request #8314 · curl/curl
- 2年以上前のリリースだった