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
Create new folder named src. In src folder, create new folder named apis. In this folder, create new web api as below:
Demo API
In apis folder, create new folder named demoapi. In demoapi folder, create new go file named demo.api.go as below:
package demoapi
import (
"fmt"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
func Hello(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
fullName := vars["fullName"]
fmt.Fprint(response, "Hello "+fullName)
}
func Sum(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
a := vars["a"]
b := vars["b"]
number1, _ := strconv.ParseInt(a, 10, 64)
number2, _ := strconv.ParseInt(b, 10, 64)
fmt.Fprint(response, number1+number2)
}
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/demoapi"
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/api/demo/hello/{fullName}", demoapi.Hello).Methods("GET")
router.HandleFunc("/api/demo/sum/{a}/{b}", demoapi.Sum).Methods("GET")
err := http.ListenAndServe(":3000", router)
if err != nil {
fmt.Println(err)
}
}
Test Web API
Use PostMan Tool test demo web api with url: http://localhost:3000/api/demo/hello/Kevin
Use PostMan Tool test demo web api with url: http://localhost:3000/api/demo/sum/2/5