Hello,I’m a beginner,I want to use it net/http build my restful api,look at the information on the Internet,
func TodoHandler(w http.ResponseWriter, r *http.Request) {
var err error
switch r.Method {
case "GET":
err = getController(w, r)
case "POST":
err = postController(w, r)
case "PUT":
err = putController(w, r)
case "DELETE":
err = delController(w, r)
}
if err != nil {
panic(err)
}
}
func getController(w http.ResponseWriter, r *http.Request) error {
id, err := strconv.Atoi(path.Base(r.URL.Path))
if err != nil {
return err
}
todo, err := model.GetTodo(id)
if err != nil {
return err
}
data, err := json.Marshal(&todo)
if err != nil {
return err
}
fmt.Fprint(w, string(data))
return nil
}
func postController(w http.ResponseWriter, r *http.Request) error {
len := r.ContentLength
body := make([]byte, len)
r.Body.Read(body)
todo := new(model.Todo)
json.Unmarshal(body, &todo)
err := todo.Create()
if err != nil {
return err
}
return nil
}
...
,This is what I’ve done,But I don’t know how to do the extension and design like the Internet other restful api.Third party packages are not considered for the time being.
What is a real restful API? This is a very broad topic that touches how you model your REST resources, what Representations you want to use for them, if you try to implement HATEOAS, …
Do you have a concrete question about your code and a specific operation it performs or that does not work?
If you don’t have a question about Go, this is off topic here.
If you want to learn about REST, there are plenty of resources on the web you could read. But note that there are many opinions about what ‘real’ REST is. Take a look at
There are details in the code that might be adjusted, but generally speaking that is how you would go about building a REST interface, yes. Map paths and methods to handlers, in the handlers do the needful and respond with JSON etc.