Skip to content

Instantly share code, notes, and snippets.

@HaraShun
Created October 8, 2016 03:40
Show Gist options
  • Save HaraShun/238708a776a52951edf8b518b5e4f34c to your computer and use it in GitHub Desktop.
Save HaraShun/238708a776a52951edf8b518b5e4f34c to your computer and use it in GitHub Desktop.
Goの簡単REST API サーバ
package main
import (
"fmt"
"io/ioutil"
"time"
"github.com/gin-gonic/gin"
)
//////////////// ▼▼ 追加 ▼▼ ////////////////
type Todo struct {
Name string `json:"name"`
Completed bool `json:"completed"`
Due time.Time `json:"due"`
}
type Todos []Todo
//////////////// ▲▲ 追加 ▲▲ ////////////////
// http://localhost:8080 アクセス時の処理
func Index(c *gin.Context) {
c.String(200, "Hello world")
}
//////////////// ▼▼ 追加 ▼▼ ////////////////
func FileOutput(c *gin.Context) {
contents, err := ioutil.ReadFile("sample.json") // ファイルの読み込み
if err != nil {
fmt.Println(contents, err)
c.JSON(400, gin.H{"status": "bad request"})
return
}
c.Writer.Header().Set("Content-Type", "application/json")
c.String(200, string(contents))
}
//////////////// ▲▲ 追加 ▲▲ ////////////////
//////////////// ▼▼ 追加 ▼▼ ////////////////
func TodoIndex(c *gin.Context) { // http://localhost:8080/todos GETでのアクセス時の処理
todos := Todos{
Todo{Name: "Write presentation", Completed: true, Due: time.Now()},
Todo{Name: "Host meetup", Completed: false, Due: time.Now()},
}
c.JSON(200, todos)
}
//////////////// ▲▲ 追加 ▲▲ ////////////////
//////////////// ▼▼ 追加 ▼▼ ////////////////
func TodoPost(c *gin.Context) { // http://localhost:8080/todo POSTアクセス時の処理
title := c.PostForm("title")
message := c.PostForm("message")
// あとはDBに保存するなりなんなりと
c.JSON(200, gin.H{
"status": "posted",
"title": title,
"message": message,
})
}
//////////////// ▲▲ 追加 ▲▲ ////////////////
func main() {
r := gin.Default()
r.GET("/", Index)
//////////////// ▼▼ 追加 ▼▼ ////////////////
r.GET("/todos", TodoIndex)
//////////////// ▲▲ 追加 ▲▲ ////////////////
//////////////// ▼▼ 追加 ▼▼ ////////////////
r.POST("/todo", TodoPost)
//////////////// ▲▲ 追加 ▲▲ ////////////////
//////////////// ▼▼ 追加 ▼▼ ////////////////
r.GET("/file", FileOutput)
//////////////// ▲▲ 追加 ▲▲ ////////////////
r.Run(":8080")
fmt.Println("server start port 8080.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment