'Route'
type provides 'Methods' function, it is used to support HTTP requests like POST,
GET, PUT etc.,
Example
router.HandleFunc("/users",
CreateUser).Methods("POST")
Above
statement maps POST request to the url /users to CreateUser function.
App.go
package main import ( "crypto/rand" "fmt" "net/http" "encoding/json" "io/ioutil" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter() router.HandleFunc("/", HomePageHandler) router.HandleFunc("/welcome/{name}", WelcomeUser) router.HandleFunc("/users", CreateUser).Methods("POST") http.Handle("/", router) http.ListenAndServe(":8080", nil) } // HomePageHandler send Hello World message to the client func HomePageHandler(writer http.ResponseWriter, request *http.Request) { dataToWrite := []byte("Hello World") writer.Header().Set("Content-Type", "text/html") writer.Write(dataToWrite) } //WelcomeUser display welcome message to given user func WelcomeUser(writer http.ResponseWriter, request *http.Request) { vars := mux.Vars(request) userName := vars["name"] dataToWrite := []byte("Hello " + userName + ", Welcome to Go language") writer.Header().Set("Content-Type", "text/html") writer.WriteHeader(http.StatusOK) writer.Write(dataToWrite) } //CreateUser creates new user func CreateUser(writer http.ResponseWriter, request *http.Request) { defer request.Body.Close() requestBytes, _ := ioutil.ReadAll(request.Body) user := User{} json.Unmarshal(requestBytes, &user) user.ID = *GenerateRandomString() responseBytes, _ := json.Marshal(user) writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(http.StatusCreated) writer.Write(responseBytes) } //User type represents a user object type User struct { FirstName string LastName string ID string } //GenerateRandomString generate random string func GenerateRandomString() *string { tempBytes := make([]byte, 16) _, err := rand.Read(tempBytes) if err != nil { fmt.Println("Error: ", err) return nil } uuid := fmt.Sprintf("%X-%X-%X-%X-%X", tempBytes[0:4], tempBytes[4:6], tempBytes[6:8], tempBytes[8:10], tempBytes[10:]) return &uuid }
Run
App.go.
Use any
Rest client like postman and hit below request to create new user.
Method: POST
Body:
{
"FirstName" :
"Krishna",
"LastName" : "Maj"
}
Headers
Content-Type
: application/json
No comments:
Post a Comment