Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I Have a problem with my API

i have an API

with format API routes look like this

localhost:8081/getdate/param1/:param1/param2/:param2

it was successfully when i just use a paramater with string,

but the problem is when parameter should be like this

REG/112/111

it read as an url ,not a param

how i can solve this?

What I have tried:

search := c.Params.ByName("search")
	client := &http.Client{}
	response, err := http.NewRequest(http.MethodGet, companyhelper.GetHisUrl(cmpId)+"/tregistration/search/"+search, nil)
	if err != nil {
		responseJson.JSONResponse(c, http.StatusBadGateway, gin.H{"tregistration": "Gagal Tersambung"}, gin.H{
			"code":    http.StatusBadGateway,
			"message": "Data Not Found Error Gateway",
		})
	}


The problem is in search parameter
Posted
Updated 29-Dec-23 8:08am
v2

1 solution

I understand you're encountering an issue with API parameters containing special characters like "/". Here's how to solve it:

1. URL-Encode the Parameter:

Before constructing the request URL, encode the "search" parameter value using a URL encoding function:


import "net/url"

searchEncoded := url.QueryEscape(search)
response, err := http.NewRequest(http.MethodGet, companyhelper.GetHisUrl(cmpId)+"/tregistration/search/"+searchEncoded, nil)


2. Adjust the Route Definition (if necessary):

If you have control over the API route definition, consider removing unnecessary slashes or using more flexible path parameters:


// Example: Allow entire path segment as a parameter
router.GET("/getdate/:param1/:param2", func(c *gin.Context) {
    param1 := c.Param("param1")
    param2 := c.Param("param2")
    // ...
})


3. Reconstruct the URL with a URL Builder (optional):

For complex URLs with multiple parameters, use a URL builder library to ensure proper encoding:


import "net/url"

u, err := url.Parse(companyhelper.GetHisUrl(cmpId) + "/tregistration/search/")
if err != nil {
    // Handle error
}
u.RawQuery = url.Values{"search": {search}}.Encode()
finalURL := u.String()
response, err := http.NewRequest(http.MethodGet, finalURL, nil)
 
Share this answer
 
Comments
Dave Kreskowiak 2-Jan-24 12:58pm    
Why are you getting downvoted? Because your answer SCREAMS ChatGPT, and that's not allowed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900