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

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

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

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

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

0回答

165閲覧

Goでchiのhttpルーターを使用しているのですがリクエストのidが取得できません。

hiroki917

総合スコア2

Go

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

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

0クリップ

投稿2023/05/30 05:44

実現したいこと

ルーティングはchiを使用しています。
http://localhost:8080/comment/1
でアクセスが来たら1の部分を取り出してデータベースからid1の情報を取得したいです。

Postmanを使用してリクエスト送ってるのですが空の配列で返ってきます。

別の関数ではURLのidを取得できているのに新しく作った関数ではid取得ができません

該当のソースコード

ルーティングです。 package main import ( "net/http" "github.com/go-chi/chi" "github.com/go-chi/chi/v5/middleware" ) func (app *application) routes() http.Handler { // 新規ルータ作成 mux := chi.NewRouter() // サーバは落とさずにエラーレスポンスを返せるようにリカバリーするmiddlewareです。。ログを記録する mux.Use(middleware.Recoverer) mux.Use(app.enableCORS) mux.Get("/", app.Home) mux.Get("/new", app.New) mux.Get("/hello", app.checkJson) mux.Get("/tweets", app.AllTweets) mux.Get("/article", app.GetArticle) mux.Post("/article", app.PostArticle) mux.Get("/article/{id}", app.GetArticleByID) mux.Put("/article/{id}", app.UpdateArticleByID) mux.Delete("/article/{id}", app.DeleteArticleByID) mux.Get("/users", app.AllGetUsers) mux.Post("/users", app.PostUser) mux.Get("/users/{id}", app.GetDetailUser) mux.Delete("/users/{id}", app.DeleteUserID) mux.Put("/users/{id}", app.UpdateUser) mux.Post("/tweets/new", app.PostTweet) mux.Post("/login", app.LoginUser) mux.Get("/tweet", app.AllGetTweet) mux.Post("/tweet/new", app.CrateTweet) mux.Post("/follow/new", app.CreateFollow) mux.Get("/follow/isFollowing", app.IsFollowing) mux.Post("/follow/unfollow", app.Unfolded) mux.Post("/like", app.CreateLikeCount) mux.Get("/like/all", app.GetAllLikes) mux.Get("/like/{id}", app.GetLikeCount) mux.Get("/comment/{id}", app.GetComments) mux.Post("/comment", app.CreateComment) return mux }
問題の関数です。 package main import ( "encoding/json" "fmt" "io" "log" "net/http" "react-go-mybackend/database" "strconv" "github.com/go-chi/chi/v5" ) type Comment struct { UserId int `json:"user_id"` TweetId int `json:"tweet_id"` Comment string `json:"comment"` } type Comments struct { Comments []Comment `json:"comments"` } func (a *application) GetComments(w http.ResponseWriter, r *http.Request) { param := chi.URLParam(r, "id") ←こちらです id, err := strconv.Atoi(param) log.Println("Requested Path: ", r.URL.Path) log.Println("Requested ID: ", id) log.Println("Requested ID:????? ") // id = 1 db := database.Connect() defer db.Close() rows, err := db.Query("SELECT user_id, tweet_id, comment FROM comments WHERE tweet_id = ?", id) if err != nil { log.Println(err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } defer rows.Close() var comments = Comments{ Comments: make([]Comment, 0), } for rows.Next() { var comment Comment err := rows.Scan(&comment.UserId, &comment.TweetId, &comment.Comment) if err != nil { log.Println(err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } comments.Comments = append(comments.Comments, comment) } if err := rows.Err(); err != nil { log.Println(err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } commentJson, err := json.Marshal(comments) if err != nil { log.Println(err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(commentJson) }

同じ処理でこちらは上手くいきます

func (app *application) DeleteUserID(w http.ResponseWriter, r *http.Request) { db := database.Connect() defer db.Close() id := chi.URLParam(r, "id")  ←こちらはid取得できます。 if id == "" { http.Error(w, "Missing article ID", http.StatusBadRequest) return } stmt, err := db.Prepare("DELETE FROM users WHERE id=?") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer stmt.Close() result, err := stmt.Exec(id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } rowsAffected, err := result.RowsAffected() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if rowsAffected == 0 { http.Error(w, "Article not found", http.StatusNotFound) return } w.WriteHeader(http.StatusOK) fmt.Fprint(w, "Article deleted successfully.") }

試したこと

デバッグしたんのですが

2023/05/30 14:37:04 Requested Path: /comment/1 2023/05/30 14:37:04 Requested ID: 0 2023/05/30 14:37:04 Requested ID:????? の結果が返ってきます。

すみませんどうかお力添えお願いしますm(_ _)m

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問