Install Libraries
Make sure Git is installed on your machine and in your system’s PATH. Install the packages to your $GOPATH with the go tool from shell:
$ go get -u github.com/gorilla/mux
$ go get -u github.com/gorilla/handlers
Web APIs
In src folder, create new folder named apis. In this folder, create new web api as below:
Product API
In apis folder, create new folder named productapi. In productapi folder, create new go file named product.api.go as below:
package productapi
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
type ResponseResult struct {
Id string `json:"id"`
}
func Delete(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
id := vars["id"]
respondWithJSON(response, http.StatusOK, ResponseResult{Id: id})
}
func respondWithJSON(response http.ResponseWriter, statusCode int, data interface{}) {
result, _ := json.Marshal(data)
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(statusCode)
response.Write(result)
}
Structure of Project
Run Application
In src folder, create new file named main.go as below and use go run main.go command to run program:
package main
import (
"apis/productapi"
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/api/product/delete/{id}", productapi.Delete).Methods("DELETE")
err := http.ListenAndServe(":3000", router)
if err != nil {
fmt.Println(err)
}
}
Test Web API
Use PostMan Tool test web api with url: http://localhost:3000/api/product/delete/p01