How to pass params in GET methods 【Go&React】

https://www.pinterest.jp/pin/108579041007003200/

In the side of frontend(React&Typescript)

useEffect(() => {
const getCollection = async () => {
setLoading(true);
await axios.get("http://localhost:8000/api/v1/get-id", {
headers: {
"Authorization": `Bearer ${YOUR_TOKEN}`, // if you have access token, you can add it here
"Content-Type": "application/json",
},
params: {
Id: Number(id), // You can pass your any value here with Key and Value pair.
}

})
.then((response) => {
// Whatever you want to write
console.log(response);
})
.catch((error) => {
throw new Error(error);
})
};
getCollection();
}, [])
await axios.get(“YOUR_API_URL", { 

In the side of backend(Go&Gin)

func main() {
router := gin.Default()
ua := "" router.Use(CORSMiddleware()) // middleware
router.Use(func(c *gin.Context) {
ua = c.GetHeader("User-Agent")
c.Next()
})
// Its great to version your API's
v1 := router.Group("/api/v1")
{
v1.GET("/get-id", controllers.GetId)
}
// Handle error response when a route is not defined
router.NoRoute(func(c *gin.Context) {
// In gin this is how you return a JSON response
c.JSON(404, gin.H{"message": "Not found"})
}) router.Run(":8000")}func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")

if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}

c.Next()
}
}
func GetId(c *gin.Context) {
id := c.Query("Id")
fmt.Println(id) // Display id backend receives from frontend
db, err := db.ConnectDB() // ConnectDB() is the function to connect to my DB which is not mentioned in this article.
if err != nil {
return
}
sqlStatement := `SELECT * FROM user_collection WHERE id=?;`

// pass id received from frontend and make the query
rows, err := db.Query(sqlStatement, id)
if err != nil {
return
}
}
id := c.Query(“Id”)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
TiShow

TiShow

80% is the creation, the rest is depression. Frontend developer and data scientist, designer. Looking for Physics Ph.D Twitter: @_t_i_show