I started learning GoLang recently. My aim is to expose a webapi. This should be able to accept a json object and should respond with another json object. I am not finding enough resources to learn how to get this working. I really appreciate any help in this regard. A piece of my code is like below.
func HelloService(res http.ResponseWriter, req *http.Request){
io.WriteString(res,"Welcome to service")
}
func main(){
http.HandleFunc("/", HelloService)
http.ListenAndServe(":8080",nil)
http.HandleFunc("/saveuser", saveUser)
}
func saveUser(res http.ResponseWriter, req *http.Request){
ConfigurationRepository.SaveUser(User) //I want to receive an User object when this service is being consumed
}
An http package that wraps "net/http" will be helpful. Examples:
https://github.com/emicklei/go-restful
https://github.com/gin-gonic/gin
Here is a simple service to get you started:
package main
import (
"github.com/emicklei/go-restful"
"log"
"net/http"
)
type User struct {
Name string
}
func postOne(req *restful.Request, resp *restful.Response) {
newUser := new(User)
err := req.ReadEntity(newUser)
if err != nil {
resp.WriteErrorString(http.StatusBadRequest, err.Error())
return
}
log.Printf("new user: '%v'", newUser)
}
func main() {
ws := new(restful.WebService)
ws.Path("/users")
ws.Consumes(restful.MIME_JSON)
ws.Produces(restful.MIME_JSON)
ws.Route(ws.POST("").To(postOne).
Param(ws.BodyParameter("User", "A User").DataType("main.User")))
restful.Add(ws)
http.ListenAndServe(":8080", nil)
}
Here is a curl to test the service by posting a single user:
curl -v -H "Content-Type: application/json" -XPOST "localhost:8080/users" -d '{"name": "Joe"}'