Create Post Api with Go example code
To create a “POST” API in Go, you can use the net/http package that is included in the Go standard library. Here’s an example of how you can create a simple “POST” API that listens on a specific port and responds with “Hello, World!” when a client makes a “POST” request to the endpoint:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost { fmt.Fprint(w, "Hello, World!") return } http.Error(w, "Invalid request method", http.StatusBadRequest) }) http.ListenAndServe(":8080", nil) }
In this example, the http.HandleFunc function is used to register a function that will be called whenever a client makes a request to the root endpoint (“/”). The function checks the request method to see if it is a “POST” request, and if it is, it responds with “Hello, World!”. If the request method is not “POST”, it sends an error response with status code “400 Bad Request”. Finally, the http.ListenAndServe function is used to start the server and listen for incoming requests on port 8080.
Create GET api with go example code
Here is an example of a basic GET API written in Go using the popular Gin web framework:
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "Hello, World!", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
This code creates a new Gin router and sets up a route for the root URL (“/”) that responds to GET requests. The route handler is a function that takes a Gin context as its argument. This function sends a JSON response with a message of “Hello, World!” and a status code of 200 OK. Finally, the router is started by calling the Run() method.
You would run this code by running go run main.go, and then making a GET request to http://localhost:8080/ using any HTTP client.
Create PUT API with Go example code
Here is an example of a basic PUT API written in Go using the popular Gin web framework:
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.PUT("/user/:id", func(c *gin.Context) { // Get the ID from the URL parameters id := c.Param("id") // Bind the request body to a struct var user struct { Name string `json:"name" binding:"required"` Age int `json:"age" binding:"required"` } if err := c.ShouldBindJSON(&user); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } // Update the user in the database // ... c.JSON(http.StatusOK, gin.H{ "message": "User updated successfully", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to PUT requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then binds the request body to a struct, in this case the struct is user which contains Name and Age field.
Then it checks if there is any error from the binding process, if there is, it will return a Bad Request with the error message.
If no error, it will update the user in the database (this part is left to you to implement) and then sends a JSON response with a message of “User updated successfully” and a status code of 200 OK. Finally, the router is started by calling the Run() method.
You would run this code by running go run main.go, and then making a PUT request to http://localhost:8080/user/
Create Delete RestAPI with Go example code
Here is an example of a basic DELETE REST API written in Go using the popular Gin web framework:
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.DELETE("/user/:id", func(c *gin.Context) { // Get the ID from the URL parameters id := c.Param("id") // Delete the user from the database // ... c.JSON(http.StatusOK, gin.H{ "message": "User deleted successfully", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to DELETE requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then deletes the user from the database (this part is left to you to implement) and then sends a JSON response with a message of “User deleted successfully” and a status code of 200 OK. Finally, the router is started by calling the Run() method.
You would run this code by running go run main.go, and then making a DELETE request to http://localhost:8080/user/
Create Post RestAPI with Go and Postgresql example code
Here is an example of a basic POST REST API written in Go using the popular Gin web framework and Postgresql as a database:
package main import ( "database/sql" "net/http" "github.com/gin-gonic/gin" _ "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "postgres://user:password@host/dbname") if err != nil { panic(err) } defer db.Close() r := gin.Default() r.POST("/user", func(c *gin.Context) { // Bind the request body to a struct var user struct { Name string `json:"name" binding:"required"` Age int `json:"age" binding:"required"` } if err := c.ShouldBindJSON(&user); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } // Insert the user into the database _, err := db.Exec("INSERT INTO users (name, age) VALUES ($1, $2)", user.Name, user.Age) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusCreated, gin.H{ "message": "User created successfully", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
This code creates a new Gin router and sets up a route for the URL path /user that responds to POST requests.
The route handler is a function that takes a Gin context as its argument. This function first binds the request body to a struct, in this case the struct is user which contains Name and Age field.
Then it checks if there is any error from the binding process, if there is, it will return a Bad Request with the error message.
If no error, it will insert the user into the Postgresql database by executing the SQL statement INSERT INTO users (name, age) VALUES ($1, $2) using the user’s name and age as the parameters and then sends a JSON response with a message of “User created successfully” and a status code of 201 Created.
It also checks if there is any error while executing the query, if so it will return a status code of 500 Internal Server Error with the error message.
Finally, the router is started by calling the Run() method.
You would run this code by running go run main.go, and then making a POST request to http://localhost:8080/user using any HTTP client with json payload of the user such as {“name”:”John”,”age”:25}
Please note that the database connection string is an example and you need to change it to match your database credentials and settings.
Also, it is important to note that you need to have the “github.com/lib/pq” package installed and imported in order to use postgres as a database with Go.
Also, it is assumed that you have the necessary table created in the database and ready to use.
Create Get RestAPI with Go and Postgresql example code
Here is an example of a basic GET REST API written in Go using the popular Gin web framework and Postgresql as a database:
package main import ( "database/sql" "net/http" "github.com/gin-gonic/gin" _ "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "postgres://user:password@host/dbname") if err != nil { panic(err) } defer db.Close() r := gin.Default() r.GET("/user/:id", func(c *gin.Context) { // Get the ID from the URL parameters id := c.Param("id") // Get the user from the database var user struct { Name string Age int } err := db.QueryRow("SELECT name, age FROM users WHERE id = $1", id).Scan(&user.Name, &user.Age) if err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) return } c.JSON(http.StatusOK, gin.H{ "user": user, }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to GET requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then it queries the Postgresql database for user with the corresponding id by executing the SQL statement SELECT name, age FROM users WHERE id = $1 and scan the result into user struct.
Then it checks if there is any error from the query, if there is and the error is not found, it will return a Not Found with the error message.
If no error, it will send a JSON response with the user data and a status code of 200 OK.
Finally, the router is started by calling the Run() method.
You would run this code by running go run main.go, and then making a GET request to http://localhost:8080/user/
Please note that the database connection string is an example and you need to change it to match your database credentials and settings.
Also, it is important to note that you need to have the “github.com/lib/pq” package installed and imported in order to use postgres as a database with Go.
Also, it is assumed that you have the necessary table created in the database and ready to use.
Create Put RestAPI with Go and Postgresql example code
Here is an example of a basic PUT REST API written in Go using the popular Gin web framework and Postgresql as a database:
package main import ( "database/sql" "net/http" "github.com/gin-gonic/gin" _ "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "postgres://user:password@host/dbname") if err != nil { panic(err) } defer db.Close() r := gin.Default() r.PUT("/user/:id", func(c *gin.Context) { // Get the ID from the URL parameters id := c.Param("id") // Bind the request body to a struct var user struct { Name string `json:"name" binding:"required"` Age int `json:"age" binding:"required"` } if err := c.ShouldBindJSON(&user); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } // Update the user in the database _, err := db.Exec("UPDATE users SET name = $1, age = $2 WHERE id = $3", user.Name, user.Age, id) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{ "message": "User updated successfully", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to PUT requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then binds the request body to a struct, in this case the struct is user which contains Name and Age field.
Then it checks if there is any error from the binding process, if there is, it will return a Bad Request with the error message.
If no error, it will update the user in the Postgresql database by executing the SQL statement UPDATE users SET name = $1, age = $2 WHERE id = $3 using the user’s name, age and id as the parameters and then sends a JSON response with a message of “User updated successfully” and a status code of 200 OK.
It also checks if there is any error while executing the query, if so it will return a status code of 500 Internal Server Error with the error message.
Finally, the router is started by calling the Run() method.
You would run this code by running go run main.go, and then making a PUT request to http://localhost:8080/user/
Please note that the database connection string is an example and you need to change it to match your database credentials and settings.
Create Delete RestAPI with Go and Postgresql example code
Here is an example of a basic DELETE REST API written in Go using the popular Gin web framework and Postgresql as a database:
package main import ( "database/sql" "net/http" "github.com/gin-gonic/gin" _ "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "postgres://user:password@host/dbname") if err != nil { panic(err) } defer db.Close() r := gin.Default() r.DELETE("/user/:id", func(c *gin.Context) { // Get the ID from the URL parameters id := c.Param("id") // Delete the user from the database _, err := db.Exec("DELETE FROM users WHERE id = $1", id) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{ "message": "User deleted successfully", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to DELETE requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then deletes the user from the Postgresql database by executing the SQL statement DELETE FROM users WHERE id = $1 using the user’s id as the parameter and then sends a JSON response with a message of “User deleted successfully” and a status code of 200 OK.
It also checks if there is any error while executing the query, if so it will return a status code of 500 Internal Server Error with the error message.
Finally, the router is started by calling the Run() method.
You would run this code by running go run main.go, and then making a DELETE request to http://localhost:8080/user/
How to write unit-testcase for Go RestAPI
Unit testing in Go is typically done using the built-in testing package. You can use this package to create unit tests for your REST API by writing test functions that make HTTP requests to your API and assert that the responses are as expected.
Here’s an example of how you might write a unit test for a GET endpoint that retrieves a user by ID:
package main import ( "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" ) func TestGetUser(t *testing.T) { // Set up the router and a test server router := gin.Default() router.GET("/user/:id", getUser) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/user/1", nil) router.ServeHTTP(w, req) // Assert that the response has the expected status code and body if w.Code != http.StatusOK { t.Errorf("Expected status code %d, got %d", http.StatusOK, w.Code) } expectedBody := `{"user":{"name":"John","age":25}}` if w.Body.String() != expectedBody { t.Errorf("Expected body %s, got %s", expectedBody, w.Body.String()) } }
This test function creates a new Gin router, sets up a route for the /user/:id path that calls the getUser function, and then creates a test server using httptest.NewRecorder().
It creates an HTTP GET request to the endpoint and serves the request to the test server.
The test function uses the testing package’s Errorf function to check that the response has the expected status code (200 OK) and body ({“user”:{“name”:”John”,”age”:25}}).
To run this test, you can use the command go test in your project’s directory. The test function name should be in the format Test* to be recognized as a unit test.
You can also use testing frameworks like testify which provides a lot of useful testing utility functions like assert and require which makes it more readable and easy to use for testing.
It’s also important to note that you may want to consider testing your database interactions in isolation, by using a library like sqlmock which allows you to mock and test your database interactions without hitting an actual database.