Go言語でRESTful APIをつくる

Tuyoshi Akiyama
Aug 9, 2017 · 6 min read

以下の記事を見ながら、シンプルなRESTful APIをGo言語で作っていきます。

様々なアプリケーション上で、安定したAPIをつくる必要性は非常に大事なものになっています。

今回のチュートリアルでは、JSON形式のデータを用いてAPIを作っていきます。

また、encoding/json packageを使います。


まず、main.goファイルをproject内に作り、次の3つの関数を書きます。

package mainimport (
"fmt"
"log"
"net/http"
)
func homePage(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Welcome to the HomePage!")
fmt.Println("Endpoint Hit: homePage")
}
func handleRequests() {
http.HandleFunc("/", homePage)
log.Fatal(http.ListenAndServe(":8081", nil))
}
func main() {
handleRequests()
}
  • homePage関数は全てのリクエストをroot URLに送っています。
  • handleRequests関数は指定したURLのpath(“/”)の時に、homePage関数が出るように設定しています。
  • main関数は、後で作るAPIが起動するようにhandleRequests関数を内包しています。

http://localhost:8081/をブラウザで見ると、 Welcome to the HomePage! が見れます。

次にStructをつくります。ここには、後々取り出したいデータに必要な要素を、設定します。

// Article is a struct for all articles
type Article struct {
ID int
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"content"`
}

APIのendpointsを作って、全てのデータを取り出す関数returnAllArticlesを作ります。また、jsonのpackageを使う為に、 encoding/json パッケージをimportしておきます。

func returnAllAritcles(w http.ResponseWriter, r *http.Request) {
articles := Articles{
Article{Title: "Hello", Desc: "Article Description", Content: "Article Content"},
Article{Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
}
fmt.Println("endpoint hit: returnAllArticles")
json.NewEncoder(w).Encode(articles)
}

まず、変数articlesにArticlesタイプの記事を2つassignします。

この関数returnAllArticlesを通ったことを、ログに書き込みます。

そして、 json.NewEncoder(w).Encode(articles) で先程の変数articlesをJSON形式 にencodeして書き込んでいます。このJSONデータがreponseの一部となります。


更には、 handeRequests関数にreturnAllArticles関数の処理が通るpathの設定を加えます。

func handleRequests() {
http.HandleFunc("/", homePage)
http.HandleFunc("/all", returnAllAritcles)
log.Fatal(http.ListenAndServe(":8081", nil))
}

ここで、 go run main.go でファイルを立ち上げて、 http://localhost:8081/allをブラウザでみるとJSONデータが表示されます。


次にRouter機能を、 gorilla/mux routerというthird-partyのパッケージを使って、書き直します。まず、”github.com/gorilla/mux” をimportしたら、main.goファイルを次のようにします。

func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/all", returnAllAritcles)
log.Fatal(http.ListenAndServe(":8081", myRouter))
}

また、先程全ての記事を取ってくるreturnAllAriticle関数をつくりました。

今度は、一つ一つの記事を取ってくるreturnSingleAritcle関数を作ります。

func returnSingleArticle(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
key := vars["id"]

fmt.Fprintf(w, "Key: " + key)
}
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/all", returnAllAritcles)
myRouter.HandleFunc("/article/{key}", returnSingleArticle)

log.Fatal(http.ListenAndServe(":8081", myRouter))
}

http://localhost:8081/article/1をブラウザで見ると、key: 1が表示されます。

vars := mux.Vars(r)

でmapを作っているので vars["key"] でURLの最後の要素がkeyとして、取り出されています。


参考リンク

  • gorilla/mutex
    g
    o言語のrouterとdispachaerのpackage document
  • encoding/json
    go言語でjsonをencode/decode等の扱うpackage
  • JSONView
    Chrome extention JSONデータをフォーマットする

Tuyoshi Akiyama

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade