About net/http restful api

(张阳阳) #1

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 {
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)
	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.

(Lutz Horn) #2

What do you mean by that?

(张阳阳) #3

How to expand in this way, making him look like a real restful API

(Lutz Horn) #4

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?

(张阳阳) #5

There is no mistake in these codes. I mean, is it a restful API if you follow this design? I am a novice in this field, and I want to learn to learn.

(Lutz Horn) #6

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

(Jakob Borg) #7

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.

(Erwan Roussel) #8

You can also use Mux to make beautiful APIs easily :blush:

(system) #9

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.