Go RESTful API

Gorilla/mux

mux is powerful RESTful API support (implement router) for Golang.

Preparation

To install this, use go get

go get -u github.com/gorilla/mux

Sample (Overall)

Support Following functions

  • Simple GET API (Return json string)
  • PATH parameter
  • Simple GET API (Only GET available)
  • Simple POST API (Only POST available)

This is just example. Mux has a lot of functions, please check web site. You can find what you want to do.

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"github.com/gorilla/mux"
)

type Personal struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

/*
 *
 */
func hello(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	person := Personal{
		Name: "Jiro",
		Age:  18,
	}
	json.NewEncoder(w).Encode(person)
}

/*
 *
 */
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "Category: %v\n", vars["category"])
}

/**
 */
func GETHandle(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "GET")
}

/*
 *
 */
func POSTHandle(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	defer r.Body.Close()
	body, err := ioutil.ReadAll(r.Body)
	if err == nil {
		fmt.Fprint(w, string(body))
	}
	fmt.Fprintf(w, "POST")
}

func main() {
	router := mux.NewRouter()

	router.HandleFunc("/hello", hello)
	// Path parameters
	router.HandleFunc("/articles/{category}", ArticlesCategoryHandler) // http://localhost:8000/articles/bobobon
	// GET
	router.PathPrefix("/goget").Methods("GET").HandlerFunc(GETHandle)
	// POST
	router.HandleFunc("/gopost", POSTHandle).Methods("POST")
	http.ListenAndServe(":8000", router)
}

You can test following URL

http://localhost:8000/hello
http://localhost:8000/articles/bobobo
http://localhost:8000/goget

http://localhost:8000/gopost (POST, you need to use any clients to POST test)

golang
スポンサーリンク
Professional Programmer2

コメント