質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Go

Go(golang)は、Googleで開発されたオープンソースのプログラミング言語です。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

1回答

467閲覧

GoでAPIを書いているのですが,思ったレスポンスが来ないです

hiroshiga

総合スコア4

Go

Go(golang)は、Googleで開発されたオープンソースのプログラミング言語です。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2021/02/16 09:44

編集2021/02/16 09:45

記事などを参考にしてAPIを書いているのですが,思った挙動にならないです。

Go

1package main 2 3import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "log" 8 "net/http" 9 10 "github.com/gorilla/mux" 11) 12 13type event struct { 14 ID string `json:"ID"` 15 Title string `json:"Title"` 16 Description string `json:"Description"` 17} 18 19type allEvents []event 20 21var events = allEvents{ 22 { 23 ID: "1", 24 Title: "Introduction to Golang", 25 Description: "Come join us for a chance to learn how golang works and get to eventually try it out", 26 }, 27} 28 29func homeLink(w http.ResponseWriter, r *http.Request) { 30 fmt.Fprintf(w, "Welcome home!") 31} 32 33func createEvent(w http.ResponseWriter, r *http.Request) { 34 var newEvent event 35 reqBody, err := ioutil.ReadAll(r.Body) 36 if err != nil { 37 fmt.Fprintf(w, "Kindly enter data with the event title and description only in order to update") 38 } 39 40 json.Unmarshal(reqBody, &newEvent) 41 events = append(events, newEvent) 42 w.WriteHeader(http.StatusCreated) 43 44 json.NewEncoder(w).Encode(newEvent) 45} 46 47func main() { 48 router := mux.NewRouter().StrictSlash(true) 49 router.HandleFunc("/", homeLink) 50 router.HandleFunc("/event", createEvent).Methods("POST") 51 log.Fatal(http.ListenAndServe(":8080", router)) 52} 53

具体的には上のようなコードを実行して以下のようなリクエストをpostmanを使って
localhost:8080/eventでPOSTで送っており,これをそのままレスポンスで返してもらいたいのですが,

{ ID: "2", Title: "sample", Description: "insertevents" }

このようなレスポンスが返ってきます。

{"ID":"","Title":"","Description":""}

以下のようなレスポンスが返ってくるようにするにはどうすれば良いのでしょうか。
初歩的な質問かもしれませんがよろしくお願いいたします。

{ ID: "2", Title: "sample", Description: "insertevents" }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

すみません。リクエストの仕方が間違っていました。
{
"ID": "2",
"Title": "sample",
"Description": "insertevents"
}
このようにリクエストしないとだめでした。

投稿2021/02/16 10:00

hiroshiga

総合スコア4

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問