LoginSignup
31
26

More than 5 years have passed since last update.

Go言語でJSONを返すシンプルなAPIサーバーを作るメモ

Last updated at Posted at 2015-06-09

このライブラリを使うといい感じに作れるみたいです。
https://github.com/ant0ine/go-json-rest

Golang初心者すぎるのでまずは動かすところから。

goのバージョン

こんな感じです。

$ go version
go version go1.4 darwin/amd64

コピペでJSONサーバー

go getコマンドでライブラリをダウンロードしておきます。

$ go get github.com/ant0ine/go-json-rest/rest

パッケージが$GOPATH/src以下に入っていることが確認できます。

$ ls $GOPATH/src/github.com/ant0ine
go-json-rest

APIpサーバープログラムを記述します。

api.go
package main

import (
    "github.com/ant0ine/go-json-rest/rest"
    "log"
    "net/http"
)

func main() {
    api := rest.NewApi()
    api.Use(rest.DefaultDevStack...)
    api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
        w.WriteJson(map[string]string{"Body": "Hello World!"})
    }))
    log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}

実行

go runで実行できます。 localhost:8080にアクセスするとJSONが返ってきていることがわかるとおもいます。

$ go run api.go

09/Jun/2015:18:32:19 +0900 200 92μs "GET / HTTP/1.1" - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36"

31
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
26