项目作者: diegothucao

项目描述 :
This is an essential example to build server with restful api using Golang
高级语言: Go
项目地址: git://github.com/diegothucao/rest-api-golang.git
创建时间: 2019-06-02T03:47:40Z
项目社区:https://github.com/diegothucao/rest-api-golang

开源协议:

下载


Building simple restful apis with Go language

This is an essential example to build server with restful api using Golang.

Step to run

  1. Clone the repo
  2. go build
  3. go run rest-api-golang

Define route

  1. var SetupServer = func(appPort string) {
  2. var router = mux.NewRouter()
  3. router.HandleFunc("/api/login", controller.Login).Methods("POST")
  4. router.HandleFunc("/api/getUser", controller.GetUser).Methods("GET")
  5. router.Use(JwtAuthentication)
  6. err := http.ListenAndServe(":"+appPort, router)
  7. if err != nil {
  8. fmt.Print(err)
  9. }
  10. }

Process a request

  1. var Login = func(w http.ResponseWriter, r *http.Request) {
  2. user := &models.User{}
  3. err := json.NewDecoder(r.Body).Decode(user)
  4. if err != nil {
  5. u.Respond(w, u.Message(false, "Invalid request"))
  6. return
  7. }
  8. user.Password = ""
  9. tk := &models.Token{UserId: user.Email}
  10. token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
  11. tokenString, _ := token.SignedString([]byte(os.Getenv("token_password")))
  12. resp := u.Message(true, "Successful")
  13. resp["data"] = user
  14. resp["token"] = tokenString
  15. u.Respond(w, resp)
  16. }

Then you can request

  1. Post http://localhost:1111/api/login
  2. {
  3. "email": "cao.trung.thu@gmail.com",
  4. "password": "tjhsdkafdksf"
  5. }
  6. Get http://localhost:1111/api/getUser
  7. Token:
  8. "Authorization": `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOiJjYW8udHJ1bmcudGh1QGdtYWlsLmNvbSJ9.7N7vWh73ELZmqG0AxRtuzGVlB8JaAVSncmCQowP6cWQ`

If you see any issue, please do not hesitate to create an issue here or can contact me via email cao.trung.thu@gmail.com or Linkedin

Thanks

references

  1. https://www.tutorialspoint.com/go/
  2. https://golang.org
  3. https://github.com/sohamkamani/jwt-go-example
  4. https://github.com/adigunhammedolalekan/go-contacts