Use PUT HTTP Method in GoLang RESTful Web API

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




Create new folder named src. In src folder, create new folder named entities. In entities folder, create new file named product.entity.go as below:

package entities

type Product struct {
	Id       string  `json:"id"`
	Name     string  `json:"name"`
	Price    float64 `json:"price"`
	Quantity int     `json:"quantity"`
	Status   bool    `json:"status"`
}

In src folder, create new folder named apis. In this folder, create new web api as below:

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"
	"entities"
	"fmt"
	"net/http"
)

func Update(response http.ResponseWriter, request *http.Request) {
	var product entities.Product
	err := json.NewDecoder(request.Body).Decode(&product)
	if err != nil {
		respondWithError(response, http.StatusBadRequest, err.Error())
	} else {
		fmt.Println("Product Info - Updated")
		fmt.Println("id: ", product.Id)
		fmt.Println("name: ", product.Name)
		fmt.Println("price: ", product.Price)
		fmt.Println("quantity: ", product.Quantity)
		fmt.Println("status: ", product.Status)
		respondWithJSON(response, http.StatusOK, product)
	}
}

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)
}

func respondWithError(response http.ResponseWriter, statusCode int, msg string) {
	respondWithJSON(response, statusCode, map[string]string{"error": msg})
}




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/update", productapi.Update).Methods("PUT")

	err := http.ListenAndServe(":3000", router)
	if err != nil {
		fmt.Println(err)
	}
}




Use PostMan Tool test web api with url: http://localhost:3000/api/product/create